computer architecture coursebook

16
1 Computer Architechure Coursebook Peter Wilkinson, Colchester Institute <[email protected]> Table of Contents Boolean Algebra ........................................................................................................... 2 Overview ............................................................................................................. 2 Truth tables ......................................................................................................... 2 Definitions of operators ......................................................................................... 2 Order of evaluation ............................................................................................... 3 Electrical equivalent of Boolean gates .............................................................................. 4 Simple treatment of gates ....................................................................................... 4 AND gate ............................................................................................................ 4 OR gate .............................................................................................................. 4 NOT gate ............................................................................................................ 5 Truth tables and logic expressions for complex circuts ................................................. 5 Exercise .............................................................................................................. 6 Atanua logic simulator ................................................................................................... 6 Instal .................................................................................................................. 6 Licence ............................................................................................................... 6 Run .................................................................................................................... 6 First Atanua circuit ............................................................................................... 7 Exercises ............................................................................................................. 7 Adders: half adder and full adder ..................................................................................... 7 Half-adder adds two binary digits and returns a sum and a carry .................................... 7 Full adder ............................................................................................................ 8 How do we make a full adder from a half adder? ........................................................ 8 ATP ........................................................................................................................... 9 History of ATP .................................................................................................... 9 The Simulated System ........................................................................................... 9 Syntax ............................................................................................................... 10 Interrupt system .................................................................................................. 14 Code examples ................................................................................................... 14 Updates ............................................................................................................. 16

Upload: peter-wilkinson

Post on 16-Mar-2016

215 views

Category:

Documents


1 download

DESCRIPTION

Computer architecture coursebook

TRANSCRIPT

Page 1: Computer architecture coursebook

1

Computer Architechure CoursebookPeter Wilkinson, Colchester Institute <[email protected]>

Table of ContentsBoolean Algebra ........................................................................................................... 2

Overview ............................................................................................................. 2Truth tables ......................................................................................................... 2Definitions of operators ......................................................................................... 2Order of evaluation ............................................................................................... 3

Electrical equivalent of Boolean gates .............................................................................. 4Simple treatment of gates ....................................................................................... 4AND gate ............................................................................................................ 4OR gate .............................................................................................................. 4NOT gate ............................................................................................................ 5Truth tables and logic expressions for complex circuts ................................................. 5Exercise .............................................................................................................. 6

Atanua logic simulator ................................................................................................... 6Instal .................................................................................................................. 6Licence ............................................................................................................... 6Run .................................................................................................................... 6First Atanua circuit ............................................................................................... 7Exercises ............................................................................................................. 7

Adders: half adder and full adder ..................................................................................... 7Half-adder adds two binary digits and returns a sum and a carry .................................... 7Full adder ............................................................................................................ 8How do we make a full adder from a half adder? ........................................................ 8

ATP ........................................................................................................................... 9History of ATP .................................................................................................... 9The Simulated System ........................................................................................... 9Syntax ............................................................................................................... 10Interrupt system .................................................................................................. 14Code examples ................................................................................................... 14Updates ............................................................................................................. 16

Page 2: Computer architecture coursebook

Computer Architechure Coursebook

2

Boolean Algebra

OverviewBoolean algebra is named after George Boole. He was the first person to develop a successful algebraof logic, which he did in 1847. It is a two value logic. The two values can be 1 and 0, on and off,true and false. The operators considered here are AND, OR, XOR and NOT. There are other operatorsbut we shall not be looking at them. Different books use different symbols for the operators. We shallstick to one set mostly, to avoid confusion, but you need to know the other sets exist.

Truth tablesIn arithmetic it is not possible to define operations such as plus and times by listing all the possibleinput and all the possible output values because there are too many numbers (an infinite number ofnumbers, in fact). However since there are only two values in boolean logic it is (usually) quite possibleto list all the possible inputs and all the possible outputs for an operation. Such a listing is usuallycalled a Truth Table.

Definitions of operators

AND

AND is often written as ^ and sometimes as a dot “.”

0 0 0

0 1 0

1 0 0

1 1 1

Table 1. Truth table for AND

OR

OR is often written as v and sometimes as a plus “+”

0 0 0

0 1 1

1 0 1

1 1 1

Table 2. Truth table for OR

The result is true if either or both inputs are true, otherwise it is false. This is not like the way OR isused in every day speech. It is more like the way we use the word any.

XOR

0 0 0

0 1 1

Page 3: Computer architecture coursebook

Computer Architechure Coursebook

3

1 0 1

1 1 0

Table 3. Truth table for XOR

The result is true if either but not both inputs are true, otherwise it is false. This is more like the wayOR is used in everyday speech. For example in the sentence “When I eat out I usually have a starteror afters”. This is really an XOR since it is clear that the speaker does not eat both a starter and afters.

NOT

0 1

1 0

Table 4. Truth table for NOT

The result is true if x is false; false if x is true;

Order of evaluationIn complex expressions brackets are evaluated first then NOT, AND and OR. It is wise to use bracketsto make order of evaluation explicit.

It is often possible to know the value of an expression before it is fully evaluated. For example assoon as a true term is evaluated in an OR expression or a false term in an AND expression thereis no need to even look at the other term. Good compliers take advantage of this to optimize thecode they generate. This means that parts of an expression may never be visited. This can be arich source of bugs when writing programs which contain boolean expressions with embeddedfunctions

Consider this fragment:

if( i || myFunc() ) {

A good compiler may simply not call myFunc() if i is true. If you are relying on myFunc()to do something for you, it may not get done!

Brackets are used in the normal way to force the order of evaluation. So in the expressioninside the brackets is evaluated first and then negated. The simplest way to show way this expressionevaluates is with a truth table.

x y

0 0 0 1

0 1 0 1

1 0 0 1

1 1 1 0

Table 5. Truth table for

Page 4: Computer architecture coursebook

Computer Architechure Coursebook

4

Electrical equivalent of Boolean gates

Simple treatment of gatesTo help you understand how boolean operations actually work this paper illustrates them as simpleelectrical circuits. The elements of the circuits are switches, a cell and a bulb.

Figure 1. Switch - (off, 0, false)

The switch is on (1 or true) when it is closed and passing current and off (0, or false) when it is openand blocking current.

Figure 2. Bulb

The bulb is on (1 or true) when current is passing.

AND gateThe bulb is only on if both switches are closed. See Fig Table 3 If either switch is open (0, or false)the bulb will not light - it will be false, or 0. It only takes one of the switches to be open to stop theflow of current.

Figure 3. AND gate

OR gateThe bulb is on if either or both the switches are closed (1, true, passing current). Only if both switchesare open (0, false, blocking current) will the light be on. Only needs one of the switches to be closedto allow current through to the bulb.

Page 5: Computer architecture coursebook

Computer Architechure Coursebook

5

Figure 4. AND gate

NOT gateOnly consider the bulb outside the box. If the switch is closed (1, true, passing current) the currentwill flow though it and the not through the bulb so the bulb will be off (0, false). When the switchis open (0, false), as in the diagram, current flows through the bulb (1, true). The extra bulb in thegray box is only to stop too much current flowing out of the cell when the switch is closed. It is notimportant if is it on or not.

Figure 5. Not gate

Truth tables and logic expressions for complex circutsThe circuit below is for a half-duplex telegraph circuit. The "switches" are Morse keys and the "lamp"would be a sounder, which would click. Because it is half-duplex x can send to y and y can send tox, but not both at the same time.

Figure 6. Half duplex telegraph

When both key x and key y are up (0, false) neither station is sending; both cells are out of the circuit.

When key x is down, so long as key y is up, then light b will come on. When key y is down, so longas key x is up, then light a will come on.

x y ¬x ¬y ais y^¬x b is x^¬y

0 0 1 1 0 0

0 1 1 0 1 0

1 0 0 1 0 1

1 1 0 0 0 0

Table 6. Truth table for half-duplex telegraph

Equation 1. Light b is on when key x is down and key y is up

Page 6: Computer architecture coursebook

Computer Architechure Coursebook

6

Equation 2. Light a is on when key y is down and key x is up

ExerciseDraw the truth table and equation for the circuit that lets you turn on and off the light from the topand bottom of the stairs.

Figure 7. Two way lighting circuit

Atanua logic simulator

InstalCopy or unzip the Atanua files into a new folder. There is no install proceedure as such but you maywant to make a shortcut.

LicenceWe have a classroom licence for Atanua. The software should not be copied outside the classroom

RunAtanua will open with a screen like this:

Figure 8. Atanua screen shot

The "buttons" along the top select sets of objects down the left hand side.

Page 7: Computer architecture coursebook

Computer Architechure Coursebook

7

First Atanua circuit1. Select top button Base if not already selected

2. Select side button logic AND and place it on the black surface

3. Select top button in

4. Select side button x and place it to left of the AND gate

5. Select side button y and place it to left of the AND gate and below the x key

6. Select top button out

7. Select side button LED red and place it to right of the AND gate

8. Select top button Wires toggle the button to (live)

9. Pull wires from the pads under each button into the pads on the left, input, side of the AND gateand from the pad under the right, output, side of the AND gate to the pad under the LED

10. Press the x and y keys on the keyboard to test the circuit. The led should light if and only if bothkeys are pressed, i.e.

Exercises1. Work out how to put corners in the wires to neaten the diagram

2. Make an OR circuit

3. Make a three input AND circuit (needs two AND gates)

Adders: half adder and full adderHalf-adder adds two binary digits and returns a sumand a carry

A half-adder takes two single digit inputs, called here x and y; adds them together and returns twosingle digit outputs, the sum and the carry. The sum is the result of adding the two digits together,ignoring carry and the carry is a single digit which is set to 1 if the sum caused a carry.

x y carry sum

0 0 0 0

0 1 0 1

1 0 0 1

1 1 1 0

Table 7. Truth table for half adder

Notice how the sum column is 1 only when exactly one of the inputs is 1 and the carry column is 1only when both inputs are one, which is what we would expect. sum and carry can be replaced withXOR and AND thus:

x y AND XOR

0 0 0 0

Page 8: Computer architecture coursebook

Computer Architechure Coursebook

8

x y AND XOR

0 1 0 1

1 0 0 1

1 1 1 0

Table 8. Truth table for half adder

Verify that this table is the same as the one above, and that the XOR and AND columns are correct.

Full adderIf a half adder can add two 1 digit numbers and return sum and carry, what more do we need to doto make a general one-column adder? To answer this question consider what happens after the half-adder has added the first column

A full adder has three inputs (a digit from one number to be added, a digit from the other number tobe added and carry from the column before).

Figure 9. Carry with two columns

How do we make a full adder from a half adder?If we have a way of adding two numbers but need to add three, how do we do it?

Observe that:

x + y + z (that is: add x, y and z together all at once)

is exactly the same as

(x + y) + z (that is: add x and y together and add the result to z)

What this suggests is intuitively logical: we can use two half-adder circuits. The first will add x and yto produce a partial sum, while the second will add carry-in to that sum to produce the final sum forthe column. If either half-adder produces a carry, there will be an output carry.

Figure 10. Full adder from two half adders

Page 9: Computer architecture coursebook

Computer Architechure Coursebook

9

Thus, carry-out will be an OR function of the half-adder Carry outputs. The resulting full adder circuitis shown

ATPThis document is a reference to ATP and not a general tutorial. It describes the system that ATP issimulating, and is a reference to the op codes. It refers to version 3.3 build 147

History of ATPAssembler Training Program (ATP) was originated to support the hypothetical processor described in(Knott & Waites 2000). The original ATP was written in Visual Basic and was difficult to distributeand maintain. ATP V3 is a Java applet. As such it is straightforward to distribute: users simply openthe web page; and easy to maintain: only the web page source needs to be changed for all users tohave a new version.

The Simulated SystemATP is a simulation of a microprocessor and associated memory, and simple BIOS. It also incorporatesan assembler program with a built in editor. The BIOS supports integer and character input and output;and string input. The processor can do a range of simple operations including basic integer arithmetic.

For experiments on interrupt driven i/o a single interrupt line and associated vector is provided.

Memory

The simulated processor is word addressed. This means that is the smallest element of memory thatcan be addressed is a 1610 bit word. The system has just over 1 k words of RAM, visible from thegrid at bottom right of the ATP screen. Notice that the memory display column headers, row headersand cell contents are all in hex.

Interrupt vector

For most simple applications the interrupt vector can be ignored, and should not be changed unless youknow what you are doing. This section can be skipped unless you plan to change the interrupt vectors

Registers

There are 14 registers.

Ten general purpose registers: R0 to R9. R0, although a general register, is used by the softwareinterrupts SWI PUTCHAR, SWI PUTINT and SWI GETCHAR.

PC is the program counter. This is increased by one for one-word instructions and two for two wordinstructions so that after execution of an instruction it points to the next instruction to be executed.

VR is he oVeRflow register. This holds the remainder after DIV (divide) and (possibly) the high orderword on MUL (multiply) if the result does not fit into one word. If there is no remainder, or the resultof a multiply does not need a high order word, then VR will contain zero after the operation.

SP is the stack pointer. If hardware interrupts are to be used this should be set to the top of stack.Conventionally 04FF16 is the top of stack but knowledgeable users may use other values (but takecare!)

Flags

C Carry. Set if and only if previous operation sets the 17th bit.

Page 10: Computer architecture coursebook

Computer Architechure Coursebook

10

V Overflow. Set if previous operation would have set any bit in notional high order word and clearotherwise. The register VR will hold the actual high order word result.

Z Zero. Set if previous operation would have resulted in all bits in 16 bit register being zero, otherwiseunset

S Sign. Set if high order bit is set, i.e. if result of previous operation could be regarded as negative16 bit signed number, otherwise unset

I Interrupt. If set then hardware interrupts can occur. If unset they cannot.

Memory map

Description Syntax

0 - 04FF16 Available for user code and data. When processorstarts PC is set to 0 so location 0 shouldcontain an executable instruction (if only a jmp tosomewhere else.

If interrupts are used the top of this portion ofmemory is used as a stack, starting from 04FF andgrowing downwards.

xxx - 04FF16 Top of stack This is the recommend location forthe top of the stack since it gives the most room togrow, however it can be located anywhere in usermemory.. Stack grows downwards towards usermemory. The register SP is the stack pointer.

050016 Keyboard interrupt vector. When a key is struckand if the contents of this location is not 0 thecurrent value of PC is saved and the value in thislocation is loaded into PC. Hence there shouldbe code to handle the keystroke at the locationpointed to by the contents of 050016 This handlercode should be terminated by an iret instruction.If 050016 contains 0 (the usual situation) then thebuilt-in keyboard handler is used.

051016 The keyboard is mapped here. If this location isread the ASCII value of the most recently pressedkey will be found. Reading this location setslocation 051116 to 0

051116 Key ready. Contains 0 if no key has been pressedsince the location 051016 was last read otherwise 1

Table 9. memory map

SyntaxIn the following examples of syntax value stands for a number, regD for a destination register, regS fora source register, and reg for a register which can be source or destination or source and destination.Items in square brackets are optional.

Description Syntax

Set contents of unnamed memory cell(s) DATA value[,value[,value]...]

Set contents of named memory cell(s) someName DATA value[,value[,value]...]

Page 11: Computer architecture coursebook

Computer Architechure Coursebook

11

Description Syntax

Set instruction counter ORG 27

Label myLabel:

Table 10. Directives - Executed at assemble-time and generate no code

Mode Description Syntax

Direct mode Register to register operation OP regD, regS

Immediate Mode Register and literal numberoperation

OP reg, @33

Indexed mode Load or store from/to an addressdetermined from adding thenumber (33 in this example) tothe content of the register

OP regD, 33+regS

Table 11. Addressing Modes

Entry Syntax

Operating system call SWI NAME_OF_OF_CALL

Table 12. Others

DATA

Can have just one value or comma delimited list. The DATA directive assembles values into memoryat current assemble-time counter (see ORG). If optional label is used (to left of DATA) this is giventhe value of the location in memory used

Single characters in single quotes are converted to ASCII before assembly. Example:

mylabel DATA 65, ’B’, 66

ORG

As the assembler assembles the program in to memory it uses an internal counter to keep track ofwhere the code for the next statement should be assembled. This starts from 0 by default. Users cancontrol the value in the counter with the ORG directive. Example:

ORG 120

Sets the instruction counter to 12010

Direct mode operations

Direct mode operations involve two registers. Example:

MOV R1, R2

Moves whatever is in R2 into R1

Immediate mode operations

Immediate mode opcodes involve one register and one literal number Example

MOV R1, @33

Page 12: Computer architecture coursebook

Computer Architechure Coursebook

12

Moves 3310 into register 1

Index mode operations

Immediate mode opcodes involve one register and a memory cell whose address is calculated byadding a literal number to the value currently stored in a register. Only LDR (load register frommemory) and STR (store register to memory) work with indexed mode.

LDR R4, 34+R1 ; load contents of memory location; formed by adding R1 to 34; into register R4

Loads whatever is in the memory address R1+3410 into register R4

Labels

A label is assigned the current value of the instruction counter at the point where the label isencountered. labels are used as the target of jumps. Example Inserts a label mylabel between the twomov statements. The values assigned to labels can be seen in the symbol table.

MOV R1, R2 mylabel: MOV R3, R4

Inserts a label mylabel between the two mov statements. The values assigned to labels can be seenin the symbol table.

OP Codes

MOV Move contents of second operand into first. Direct and immediate mode.

CMP Compares second operand with first. Actually, it subtracts second from first and sets the flagsbut does not change either operand. Direct and immediate mode.

MUL Multiplies first operand by second and leaves result in first. If result is too big to fit in first thenoverflow flag is set and overflow is stored in VR. Direct and immediate mode.

XOR Xors first operand with second and leaves result in first. Direct and immediate mode.

SUB Subtract second operand from first and leaves result in first. Direct and immediate mode.

LDR Loads contents of effective address into first operand register.

STR Stores contents of first operand register into an effective address . Effective address can be anumber or a number+a register. (Indexed mode)

INC Adds one to register.

DEC Subtracts one from register.

JEQ Jump if EQual (i.e. if Zero flag set)

JNE Jump if Not Equal (i.e. if Zero flag is clear)

JGT Jump if Greater Than

JLE Jump if Less than or Equal

JLT Jump if Less Than

JVC Jump if oVerflow Clear

Page 13: Computer architecture coursebook

Computer Architechure Coursebook

13

JVSJump if oVerflow Set

IRET Return from interrupt. Atomically (resets the interrupt flag, jumps to the address found at thetop of the stack, and pops the stack)

STI Sets the interrupt flag, thus permitting interrupts to occur

CLI Clears (resets) the interrupt flag, thus preventing interrupts from occurring

PUSH Pushes contents of register onto the stack and decreses SP by one. (copies the contents ofregister into memory address pointed to by SP). The stack should be set up before executing PUSHor unexpected things will happen

POP Pops the stack into register and increases SP by one. (copies the contents memory address pointedto by SP into register). The stack should be set up before executing POP or unexpected things willhappen

Operating system calls

There is assumed to be a very simple operating system to perform keyboard input and screen output.Programs need to be able to call into the operating system to do input and output. The opcode SWI<somefunction> calls into the operating system. In this processor all calls to the operating system passin and get out data through R0. Thus, although R0 is a general register it is best to avoid using it soit is vacant for any operating system calls that need to be made.

mov r0, @5swi putint ; put 5 out on screen (put unsigned int)

Outputs the value in R0 as an unsigned base 10 integer.

mov r0, @-5swi putsint ; put -5 out on screen (put signed int)

Outputs the value in R0 as an signed base 10 integer.

mov r0, @65swi putchar ; put A out on screen

Outputs the value in R0 as an ASCII character

swi getint; R0 now contains the number the user entered

Gets an integer from the input window as a base 10 integer. The thread of execution stops and waitsuntil the user presses the [input] button. If the number is preceeded by a minus sign it will be interpretedas a signed negative number. It the string can not be interpreted as a base 10 integer the message"PANIC: not a number" will be written in the status window and zero will be stored in R0. Executionwill continue.

jmp start ; jump over buffer to next executable line BUFFER data 5 data " "start: mov r0, @BUFFER ; move *address* of buffer into R0 swi getstr

Gets a string from the user. Before the call R0 should be set to contain the address of a buffer, thatis a series of addresses, large enough to contain the anticipated string. When the user types the stringand hits return the buffer will be filled with the string formated as follows. The string format has thefirst (lowest) word as a number representing the string length (not including the first word), thus thestring “ABC” would be represented in memory as

Page 14: Computer architecture coursebook

Computer Architechure Coursebook

14

Address Value Description

55 3 Length word

56 65 ASCII "A"

57 66 ASCII "B"

58 67 ASCII "C"

Table 13. String "ABC" in memory starting at 55

Numbers and characters

Unadorned numbers in programs are interpreted as base 10. Precede numbers with & to have theminterpreted as hex (base 16). Although characters can be used in DATA statements (in single quotes),they can’t be used in immediate statements (this is a bug!)

Interrupt systemThis is an advanced topic. By default interrupts are disabled and this section can be ignored.

There is a single simulated hardware interrupt line that is "raised" then a key is pushed. If interrupts areenabled, that is if the I flag is set, the current value of PC is pushed onto the stack, the I flag is clearedto prevent further interrupts, and a jmp is executed to the address stored in the keyboard interruptvector (050016). The code at that address (not at 050016 but at the address pointed to by 050016) isperformed. This code should be terminated by an iret instruction, which pops the stored value ofPC from the stack and executes a jmp to it and resets the I flag.

Code examples

Add two static numbers

MOV R1, @5MOV R2, @3ADD R2, R1

Moves 5 into R1; 3 into R2; and adds contents of R1 (5) into R2

Add two numbers from memory

ORG &10 ; start assembling at 10 hex (16 decimal)N1 DATA 5 ; put 5 into memory address 10 hex and call it N1 N2 DATA 3 ; put 3 into memory address 11 hex and call it N2ORG 0 ; go back to assembling at 0LDR R1, N1 ; load R1 with contents of memory address N1 LDR R2, N2 ; load R2 with contents of memory address N2ADD R2, R1 ; add R1 into R2

Stores 5 into 1016 and names it N1; Stores 3 into 1116 and names it N2. Loads contents of N1 into R1;contents of N2 into R2 then added R1 into R2 3

Loop and output

Loop MOV R1, @10 ; loop limit MOV R2, @0 ; loop startTOP: ; label

Page 15: Computer architecture coursebook

Computer Architechure Coursebook

15

MOV R0, R2 SWI PUTINT ; put whatever is in R0 out as a base 10 number INC R2 ; up the loop count CMP R2, R1 ; reached limit? JNE TOP ; no - jump to TOP else drop out and end

Stores 5 into 1016 and names it N1; Stores 3 into 1116 and names it N2. Loads contents of N1 into R1;contents of N2 into R2 then added R1 into R2 3

Arrays

ORG &100my_str DATA "hello world"ORG &0MOV R1, @3LDR R0, my_str+R1

Is more or less equivalent to the high level code

char my_str[] = "hello world";my_str[3];

Stores 5 into 1016 and names it N1; Stores 3 into 1116 and names it N2. Loads contents of N1 into R1;contents of N2 into R2 then added R1 into R2 3

Non-blocking input - polling

mylab: ldr r1, 1297 ; load r1 from 0x511 cmp r1, @0 ; compare to zero jeq mylab ; jump if zero ; carry on if not zero ldr r0, 1296 ; load r0 from 0x510 swi putchar ; put r0 on screen as a character jmp mylab ; go again

Non-blocking input - interuppt driven

org &500 data &400

org 0 stiloop: mov r0, r1 swi putint

mov r0, @32 swi putchar

inc r1 cmp r1, @9 jne loop mov r1, @0 mov r0, @12 swi putchar jmp loop

Page 16: Computer architecture coursebook

Computer Architechure Coursebook

16

org &400 mov r8, r0 ldr r0, 1296 ; load r0 from 0x510 swi putchar mov r0, r8 iret

UpdatesThis table of updates starts with build 146

Buildnumber

Date Changes

146 April 29,2011

Added swi putsint to put out signed integer

Added PUSH

Added POP

147 May 2,2011

Added IRET and tested interrupt driven I/O

Fixed bug where memory location 0000 got set to 0000 as result of parsingORG

May 16,2011

Updated this document. Errors in polling and interurrpt examples

Table 14. Updates