Microprocessors · Lecture Notes
Chapter 2.2: 8086 Registers
Most of what an assembly program does happens in a few small memory cells inside the processor. These cells are called registers. The 8086 has fourteen registers, and the name of each describes a job: AX is the accumulator, CX is the counter, SP points to the top of the stack, and IP holds the place of the next instruction. This chapter first explains what a register is and why it is so much faster than memory. It then examines the 8086’s register set group by group: the 8-bit and 16-bit uses of the four data registers, how instructions use these registers implicitly, access to the stack and to strings through the pointer and index registers, and the segment registers and IP. The second half of the chapter is devoted to the flags register. It shows with examples in which results the six status flags are set, how the ALU produces these bits in hardware, and how the three control flags change the way the processor works. Every piece of code is traced line by line with the values of the registers, flags, and memory at each step.
Learning outcomes
- Recognize the register set
- Count the fourteen registers of the 8086 by group; explain which ones can be split into two 8-bit halves and why writing to one half does not change the other.
- Know the implicit roles
- State which registers MUL, DIV, LOOP, REP, IN, OUT, PUSH, POP, and the string instructions use without the registers being written in the instruction.
- Use register pairs
- Know in which access each of the pairs CS:IP, SS:SP, SS:BP, DS:BX, DS:SI, and ES:DI is used, and compute the physical address.
- Compute the status flags
- Find the CF, PF, AF, ZF, SF, and OF flags by hand after an addition or subtraction; explain the difference between CF and OF in the unsigned and signed interpretations.
- Manage the control flags
- Explain how DF, IF, and TF change the processor’s behavior; read and write the flags with CLD/STD, CLI/STI, LAHF/SAHF, and PUSHF/POPF.
- Trace code
- Trace a short 8086 program by writing the state of the registers, flags, memory, and stack at each step in table form.
2.2.1The register concept
2.2.1.1What is a register?
In a digital design course, when D flip-flops are lined up side by side and connected to a common clock signal, a register results. At the rising edge of the clock the bits at the input are loaded into the flip-flops and stay there until the next load. The registers inside a microprocessor are built this way. The difference is in their number and roles: the processor uses a few dozen registers at the same time and reaches each of them through instructions.
A register is a very fast, small memory cell inside the processor. The 8086’s registers are 16 bits wide. All the registers the programmer can read and write directly with instructions are called the register set; the 8086’s register set has fourteen registers.
There are also registers inside the processor that the programmer cannot see. The instruction register that holds the instruction being decoded, the temporary registers that feed the ALU’s inputs, and the prefetch queue are among them. In this chapter “register” means the fourteen registers the programmer can use by name.
While a program runs, temporary data, memory addresses, loop counters, and results of operations are kept in registers. Figure 2.2.1 shows the relationship between the processor and memory. The registers are inside the processor and connected to the ALU by short internal paths. Memory is outside the processor, at the other end of the address and data buses.
2.2.1.2Registers and memory: the speed gap
The 8086 talks to external memory in bus cycles. A bus cycle consists of at least four clock cycles (T1, T2, T3, T4). In T1 the address is put on the bus, in T2 the read or write signal is issued, in T3 the data is ready on the bus, and in T4 the cycle closes. If the memory is slow, wait cycles are added in between. On a 5 MHz 8086 one clock cycle takes 200 ns; so a single memory read is at least 800 ns.
A register access never goes out on the external bus. The contents of the register reach the ALU within the same clock cycle. Table 2.2.1 gives a few examples from the clock-cycle counts in Intel’s 8086 manual. EA is the extra cycles spent computing the effective address. Its value depends on the address form: 5 for a single-register address like [BX], 6 for a direct address like [0500h], and 9 for register plus constant like [BX+2].
| Instruction | Operands | Clock cycles | Time at 5 MHz |
|---|---|---|---|
MOV AX, BX | register ← register | 2 | 0.4 µs |
MOV AX, [BX] | register ← memory | 8 + 5 = 13 | 2.6 µs |
ADD AX, BX | register ← register + register | 3 | 0.6 µs |
ADD AX, [BX] | register ← register + memory | 9 + 5 = 14 | 2.8 µs |
ADD [BX], AX | memory ← memory + register | 16 + 5 = 21 | 4.2 µs |
The table gives a clear result: the same addition takes about five times as long when one of the operands is in memory, and seven times as long when the result is written to memory. The ADD [BX], AX instruction reads memory first and then writes; it spends two bus cycles. That is why a well-written assembly program keeps frequently used values in registers and goes to memory only when necessary. Compilers for high-level languages work on the same principle: they place a loop’s counter and intermediate results in registers as much as possible.
The number of registers, however, is small. Every register takes space on the processor chip. Inside an instruction there is also a field that selects the register: in 8086 instructions this field is 3 bits and selects one of 23 = 8 registers. Increasing the number of registers both enlarges the chip and lengthens the instructions. With 1978 technology the 8086’s designers made do with eight general-purpose registers.
2.2.1.3There is no memory-to-memory operation
In the 8086’s two-operand instructions (MOV, ADD, SUB, AND, CMP …) at least one of the operands must be a register or a constant. There is no MOV or ADD that copies one memory cell directly to another or adds two memory cells. This rule comes from the instruction format: inside an instruction there is room to describe only one memory address.
x DW 1
y DW 2
MOV x, y ; ERROR: no memory-to-memory MOV
MOV AX, y ; right: first into a register
MOV x, AX ; then into memoryThe assembler does not accept the first line and gives an error message. The correct way is to carry the value through a register. The register works here like a relay station. The only exception to this rule is the string instructions. MOVSB moves a byte directly from DS:SI to ES:DI. It takes both addresses implicitly from the SI and DI registers without writing them in the instruction.
Thinking of variables as in a high-level language and writing MOV total, number or ADD result, value. Because both operands are in memory, the assembler does not accept these lines. One of the values is first taken into a register.
2.2.2The 8086 register set
2.2.2.1Fourteen registers and their groups
The 8086’s fourteen registers are gathered into four groups by role (Figure 2.2.2):
- Data registers: AX, BX, CX, DX. Each is 16 bits and can be split into two 8-bit halves: AH/AL, BH/BL, CH/CL, DH/DL.
- Pointer and index registers: SP (stack pointer), BP (base pointer), SI (source index), DI (destination index). These point to a location in memory; they have no 8-bit parts.
- Segment registers: CS (code), DS (data), SS (stack), ES (extra). Each determines the start of a segment in memory.
- Special registers: IP (instruction pointer) and FLAGS (the flags register).
The count is as follows: 4 data + 4 pointer/index + 4 segment + IP + FLAGS = 14. In this course the first eight registers, that is, AX, BX, CX, DX, SP, BP, SI, and DI, are counted as general-purpose registers. What these eight have in common is that they can be used freely as operands in instructions like MOV, ADD, and AND. ADD SI, 4 and MOV BP, AX are valid instructions. The segment registers, IP, and FLAGS, however, cannot be operands in arithmetic instructions.
The letter X in the register names stands for “extended.” The 8080 processor before the 8086 had 8-bit registers such as A, B, C, and D. The 8086 extended them to 16 bits and named them AX, BX, CX, and DX; the 8-bit halves were called with the letters H (high) and L (low). This naming was chosen so that 8080 programs could be ported easily to the 8086. It continues in today’s x86 processors: in 32-bit processors the lowest 16 bits of the register EAX, and in 64-bit processors of RAX, is still AX.
2.2.2.2Where the registers sit in the BIU and EU
The 8086 consists of two units: the bus interface unit (BIU), which accesses memory and I/O, and the execution unit (EU), which decodes and executes instructions. The fourteen registers are shared between these two units, and this sharing makes it easier to understand the roles of the registers.
| Unit | Registers | Role in address generation |
|---|---|---|
| EU | AX, BX, CX, DX | data; BX can also hold an offset |
| EU | SP, BP, SI, DI | 16-bit offset |
| EU | FLAGS | none; it holds the ALU result and the control bits |
| BIU | CS, DS, SS, ES | segment start (paragraph number) |
| BIU | IP | offset within the code segment |
The EU works only with 16-bit numbers. When a memory operand is needed, it computes the effective address, that is, the offset within the segment, from BX, BP, SI, DI, and the constant in the instruction, and gives it to the BIU. It is the BIU that combines the 20-bit physical address with the segment register. That is the reason the segment registers and IP sit in the BIU: independently of the EU, the BIU prefetches the next instruction bytes from CS:IP and puts them in the queue. This arrangement also settles the question “which register gives which part of the address?” The segment register gives the upper part of the address; the pointer and index registers give the position within the segment.
2.2.2.3General-purpose registers and implicit roles
As their name suggests, general-purpose registers can be used interchangeably in most instructions. It is possible to write ADD SI, DX in place of ADD AX, BX. Even so, some instructions use a particular register without its name appearing in the instruction.
An implicit operand is an operand that does not appear in the way the instruction is written but is read or written by the definition of the instruction. In the MUL BX instruction only BX is written; AX, which is multiplied, and DX, which receives the high half of the result, are implicit operands.
Table 2.2.3 gives the names of the eight general-purpose registers and their implicit roles together. The English names of the registers are abbreviations of their roles, and this makes the table easier to remember.
| Register | Ad | 8-bit halves | Implicit use (examples) |
|---|---|---|---|
AX | accumulator | AH, AL | MUL, DIV, IN, OUT, LODS/STOS |
BX | base | BH, BL | memory addressing [BX], XLAT |
CX | count | CH, CL | LOOP, REP, shift count CL |
DX | data | DH, DL | upper half of MUL/DIV, port address |
SP | stack pointer | — | PUSH, POP, CALL, RET |
BP | base pointer | — | stack frame [BP+n] |
SI | source index | — | string source DS:SI |
DI | destination index | — | string destination ES:DI |
Implicit roles were chosen to shorten the 8086’s instruction encoding. If the LOOP instruction had to say which register holds the counter, a register field would have to be added to every LOOP. Because the counter is always CX, LOOP is only two bytes: the opcode and the jump displacement. The price is flexibility. If CX is being used for another job in a program, it must be saved before LOOP. A programmer who does not know the implicit roles may not notice that a MUL instruction silently erased the value in DX.
2.2.2.48-bit and 16-bit use: AX = AH : AL
AX, BX, CX, and DX can be used both as a single 16-bit register and as two separate 8-bit registers. The high-order 8 bits of AX (bits 15–8) are called AH and the low-order 8 bits (bits 7–0) AL. These are not separate hardware; they are the two halves of the same 16 flip-flops. That is why the following equality holds at every moment:
AX = AH × 256 + AL (in hexadecimal: AX = AH : AL)
When an instruction writes to AL, only the lower 8 flip-flops are loaded; the upper half stays in place. The best way to see this behavior is to trace a short program. The code is the same as the program in the slides:
MOV AX, 1234h ; AH=12h, AL=34h
MOV AL, 0FFh ; low half only
ADD AL, 1 ; 8-bit add
MOV AX, 12FFh
ADD AX, 1 ; 16-bit add| Row | Instruction | AX | AH | AL | CF | ZF |
|---|---|---|---|---|---|---|
| 1 | MOV AX, 1234h | 1234h | 12h | 34h | 0 | 0 |
| 2 | MOV AL, 0FFh | 12FFh | 12h | FFh | 0 | 0 |
| 3 | ADD AL, 1 | 1200h | 12h | 00h | 1 | 1 |
| 4 | MOV AX, 12FFh | 12FFh | 12h | FFh | 1 | 1 |
| 5 | ADD AX, 1 | 1300h | 13h | 00h | 0 | 0 |
The first row writes 1234h into AX. In hexadecimal notation every two digits are a byte; so AH = 12h and AL = 34h. The second row changes only AL: AL = FFh, AH = 12h stays, and AX = 12FFh. The third row is the most instructive. ADD AL, 1 is an 8-bit addition: FFh + 01h = 100h. The result is 9 bits but the destination is 8 bits. The lower 8 bits, 00h, are written to AL. The overflowing 1 is not added to AH; it goes to the carry flag (CF). Because the result is zero, the zero flag is also set (ZF = 1). AX is now 1200h (Figure 2.2.3).
ADD AL, 1. AL = FFh + 1 = 00h; the carry does not pass to AH but goes to CF. AH = 12h stays in place.The fourth row makes AX 12FFh again. Because MOV does not change the flags, CF = 1 and ZF = 1 are preserved. The fifth row does the same “+1” operation, this time on 16 bits: 12FFh + 0001h = 1300h. This time the carry out of the low byte passes to AH, and 12h becomes 13h. Because the 16-bit result fits in 16 bits, CF = 0. Since the result is not zero, ZF is 0 too.
The difference between these two additions comes from the width at which the ALU works. The processor understands the operation width from the name of the operands: AL is an 8-bit register and AX a 16-bit one. In the instruction code this information is carried by a single bit, the W bit: W = 0 means a byte operation and W = 1 a word operation. ADD AL, 1 is encoded as 04 01 and ADD AX, 1 as 05 01 00; the opcodes differ only in the lowest bit.
If INC BL executes with BX = 12FFh, what does BX become?
INC works on the 8-bit BL: FFh + 1 = 100h, and 00h is written to BL. The carry does not pass to BH; BH = 12h stays and BX = 1200h. ZF = 1. The INC instruction never changes the carry flag; CF keeps its previous value. If CF had been set to 1 beforehand, it stays 1 after INC.
The 8-bit halves are also related to the low-byte-first layout in memory. If MOV [0300h], AX executes with AX = 1234h, the 34h in AL is written to address 0300h and the 12h in AH to address 0301h. The low byte goes to the low address. The same rule holds when reading from memory: MOV AX, [0300h] fills AL from 0300h and AH from 0301h.
Thinking that when AL is written the whole of AX changes. MOV AL, 5 does not touch AH. If AX was 1234h before, it becomes 1205h after the instruction, not 0005h. If the whole of AX is wanted to be 5, MOV AX, 5 is written.
Only the four data registers have halves. A notation like MOV SL, 5 or MOV BPL, 0 does not exist on the 8086. A program that wants to reach the low byte of SI first copies SI to AX and works on AL.
2.2.3The data registers
2.2.3.1AX: the accumulator
AX is the most used register of the 8086. It takes its name from the accumulator of older processors. In a processor with an accumulator every arithmetic operation takes one operand from the accumulator and writes the result back there; the results “accumulate” there. The 8086 has dropped this requirement: ADD BX, CX works without touching the accumulator. Still, many instructions use AX or AL implicitly:
MUL,IMUL,DIV,IDIV: the multiplicand and dividend sit in AX (or AL, or DX:AX), and the result is written to AX.INandOUT: the data read from a port comes into AL or AX; the data to be written to a port is in AL or AX.CBW: extends the signed byte in AL into AX.DAAandDAS: correct the BCD result in AL.LODSBloads a byte into AL, andSTOSBwrites the byte in AL to memory.
The privilege of AX shows in instruction length too. Many 8086 instructions have a short form specific to the accumulator. Table 2.2.5 puts the machine codes the assembler produces side by side.
| Instruction | Machine code | Length |
|---|---|---|
ADD AX, 1234h | 05 34 12 | 3 bytes |
ADD BX, 1234h | 81 C3 34 12 | 4 bytes |
MOV AX, [0300h] | A1 00 03 | 3 bytes |
MOV BX, [0300h] | 8B 1E 00 03 | 4 bytes |
In the general form, after the opcode comes a byte that describes the operands (the ModR/M byte: C3, 1E). In the accumulator form the fact that the destination is AX is hidden inside the opcode; this byte is not needed. One byte less is a gain both in memory space and in a bus cycle in the prefetch queue. That is why compilers and experienced programmers build frequent computations on AX.
The short example in the slides adds AX to itself:
ADD AX, AX ; AX = AX + AX
MOV AX, 0005h
ADD AX, AX ; AX = 000Ah
MOV AH, 4Ch ; DOS: exit
INT 21h| Instruction | AX | Note |
|---|---|---|
ADD AX, AX | 0000h | 0 + 0 = 0; ZF = 1, PF = 1 |
MOV AX, 0005h | 0005h | 5 is written to AX |
ADD AX, AX | 000Ah | 5 + 5 = 10 = 000Ah; ZF = 0 |
MOV AH, 4Ch | 4C0Ah | only AH changes; AL = 0Ah stays |
INT 21h | 4C0Ah | DOS service 4Ch: the program ends, exit code AL = 10 |
Adding a value to itself is multiplying by 2. In a binary number this is a shift of all the bits one place left: 0101b + 0101b = 1010b. The last two rows are interesting too. DOS service 4Ch expects the service number in AH and the program’s exit code in AL. Because MOV AH, 4Ch does not touch AL, the program ends with exit code 10. If the exit code is to be 0, MOV AX, 4C00h is written; this single instruction fills both AH and AL.
2.2.3.2BX: the base register
BX is 16 bits like AX and is split into BH and BL. What sets it apart from the other data registers is that it can be used in memory addressing. A register inside square brackets says that the register’s value will be used as an offset. [BX] means “the memory cell BX points to.”
A base register is a register that holds the base part of the address in indirect addressing. On the 8086 the base registers are BX and BP. The registers that can be used inside square brackets are only BX, BP, SI, and DI; [AX], [CX], and [DX] cannot be written.
This restriction too comes from instruction encoding. The 8086’s addressing field (the R/M field) selects one of eight address forms with a 3-bit code: [BX+SI], [BX+DI], [BP+SI], [BP+DI], [SI], [DI], [BP] (or a direct address), and [BX]. AX, CX, and DX are not in the list. The line MOV AX, [CX] therefore gets an error from the assembler. If an address in CX has to be used, it is first copied to BX: MOV BX, CX and MOV AX, [BX].
The meaning of the square brackets is the point beginners confuse most often. Figure 2.2.4 shows the difference.
MOV BL, [0500h] copies the byte 25h at address DS:0500h into BL. The number 500h is not written to BL; the square brackets mean “the value at this address.”MOV BL, [0500h] reads from memory: if address DS:0500h holds 25h, BL = 25h. MOV BX, 0500h, on the other hand, never goes to memory; it writes the number 0500h into BX. The first instruction is 4 bytes and spends a bus cycle. The second is 3 bytes and the number is inside the instruction. This distinction is the basic distinction between a constant and memory contents. To put a number in a register, square brackets are not used.
The trace program in the slides uses BX as a pointer. Suppose the bytes 25h, 17h, 00h, and 9Ch are at memory addresses 0500h–0503h.
MOV BX, 0500h ; BX = address
MOV AL, [BX] ; AL = [0500h]
MOV DL, [0501h] ; direct address
ADD AL, DL ; AL = 25h + 17h
MOV [BX+2], AL ; [0502h] = AL| Row | Instruction | BX | AL | DL | 0500h–0503h |
|---|---|---|---|---|---|
| 1 | MOV BX, 0500h | 0500h | 00h | 00h | 25 17 00 9C |
| 2 | MOV AL, [BX] | 0500h | 25h | 00h | 25 17 00 9C |
| 3 | MOV DL, [0501h] | 0500h | 25h | 17h | 25 17 00 9C |
| 4 | ADD AL, DL | 0500h | 3Ch | 17h | 25 17 00 9C |
| 5 | MOV [BX+2], AL | 0500h | 3Ch | 17h | 25 17 3C 9C |
The first row writes a number to BX; from now on this number will be used as an address. In the second row [BX] is the byte BX points to: AL = 25h. The third row does the same kind of read by writing the address inside the instruction, and DL = 17h. The fourth row adds two registers: 25h + 17h = 3Ch. In the fifth row the effective address of [BX+2] is 0500h + 2 = 0502h; AL is written to this address. BX does not change; what changes is memory (Figure 2.2.5).
[BX+2].The addresses in the program are offsets. The processor looks them up within the DS segment, because the default segment for accesses made with BX is DS. emu8086 loads a .COM program with DS = 0700h. In this case the physical address of the offset 0500h is 0700h × 10h + 0500h = 07000h + 0500h = 07500h. The byte written in the fifth row appears in emu8086’s memory window at physical address 07502h.
That BX can hold an address makes it indispensable in array and table operations. While BX points to the start of an array, the form [BX+SI] reaches the SI-th element of the array; the array is walked by incrementing SI on each pass. The XLAT instruction also uses BX implicitly: it treats AL as an index into the table BX points to and does AL ← [BX+AL] in a single instruction.
2.2.3.3CX: the count register
CX is a 16-bit register split into CH and CL. It is used in loops, repetition, and counting; its name comes from this (count register). Three kinds of instructions use CX implicitly:
LOOP label: first does CX ← CX − 1, then jumps to the label if CX ≠ 0. It does not affect the flags.- The
REPprefix: repeats the string instruction after it CX times; CX decreases by one each pass. - Shift and rotate instructions: if the count is greater than 1 it is given in CL:
SHL AX, CL.
The LOOP label instruction does the following two steps in a single instruction: (1) CX ← CX − 1; (2) if CX ≠ 0, IP ← the address of the label, otherwise move on to the next instruction. The decrement is done before the test.
The program in the slides computes the sum 5 + 4 + 3 + 2 + 1. CX is both the counter and the value being added.
MOV CX, 5 ; counter
MOV AX, 0 ; sum
AGAIN: ADD AX, CX
LOOP AGAIN ; CX--, jump if ≠0
MOV DX, AX ; result| Step | Instruction | CX | AX | DX | Next |
|---|---|---|---|---|---|
| 1 | MOV CX, 5 | 0005h | 0000h | 0000h | row 2 |
| 2 | MOV AX, 0 | 0005h | 0000h | 0000h | AGAIN |
| 3 | ADD AX, CX | 0005h | 0005h | 0000h | LOOP |
| 4 | LOOP AGAIN | 0004h | 0005h | 0000h | jumps |
| 5 | ADD AX, CX | 0004h | 0009h | 0000h | LOOP |
| 6 | LOOP AGAIN | 0003h | 0009h | 0000h | jumps |
| 7 | ADD AX, CX | 0003h | 000Ch | 0000h | LOOP |
| 8 | LOOP AGAIN | 0002h | 000Ch | 0000h | jumps |
| 9 | ADD AX, CX | 0002h | 000Eh | 0000h | LOOP |
| 10 | LOOP AGAIN | 0001h | 000Eh | 0000h | jumps |
| 11 | ADD AX, CX | 0001h | 000Fh | 0000h | LOOP |
| 12 | LOOP AGAIN | 0000h | 000Fh | 0000h | falls through |
| 13 | MOV DX, AX | 0000h | 000Fh | 000Fh | — |
The loop body runs five times with CX = 5, 4, 3, 2, 1. The fifth LOOP lowers CX from 1 to 0 and does not jump; the program leaves the loop. The body does not run at all with CX = 0. The total is 15 = 000Fh. Check with Gauss’s formula: 5 × 6 / 2 = 15.
The time of the loop is also easy to compute. When LOOP jumps it takes 17 clock cycles and when it does not jump it takes 5; ADD AX, CX is 3 cycles. For five passes 5 × 3 + 4 × 17 + 5 = 88 cycles are spent. This value also shows how the share of loop control in the total time shrinks as the body grows.
The CX = 0 trap
Because LOOP decrements before it tests, entering the loop with CX = 0 gives an unexpected result. The first LOOP computes 0000h − 1 = FFFFh. FFFFh is not zero; the processor jumps. The loop then runs with FFFFh, FFFEh, …, 0001h, and the total number of passes is 65,536.
MOV CX, 0
MOV BX, 0
MOV DX, 0
D: ADD BX, 1 ; pass counter (low word)
ADC DX, 0 ; high word
LOOP DThis program counts the number of passes in the 32-bit pair DX:BX. When the program ends, DX:BX = 0001:0000h = 65,536. Note that the pass count does not fit in 16 bits; had the counter been BX alone, it would have returned to 0 after 65,536 passes and one would think the loop never ran.
The way to protect against this trap is the JCXZ instruction: “jump if CX is zero.” It is placed right before the loop and skips the whole loop if the counter is zero.
MOV CX, 0
MOV AX, 0
JCXZ skip ; if CX = 0, do not enter the loop
D: ADD AX, CX
LOOP D
skip: MOV DX, AXIn this program JCXZ jumps straight to the label skip; the loop body does not run even once and AX = DX = 0 remains. JCXZ, like LOOP, does not look at the flags; it tests CX directly.
Shifting with CL
On the 8086, shift and rotate instructions take the count either as 1 or in CL. The notation SHL AX, 4 does not exist on the 8086; it came with the 80186. For the 8086 the same job is written like this:
MOV AX, 0003h
MOV CL, 4
SHL AX, CL ; AX = 0030hA four-bit left shift is multiplication by 24 = 16: 3 × 16 = 48 = 0030h. In hexadecimal notation this means appending a 0 to the number. The same operation appears when a segment register is converted to a physical address.
2.2.3.4DX: the data register
DX is split into DH and DL. It has two important implicit roles: holding the high half of AX in wide multiplication and division, and carrying the I/O port number.
Multiplication. The product of two 16-bit numbers can grow to 32 bits: FFFFh × FFFFh = FFFE0001h. The result does not fit in a single 16-bit register. The 8086 therefore splits the result of a 16-bit multiplication across two registers: the high 16 bits are written to DX and the low 16 bits to AX. This pair is written DX:AX (Figure 2.2.6). In an 8-bit multiplication, however, the result is 16 bits and fits entirely in AX: MUL BL → AX = AL × BL. In this case DX does not change.
MUL BX: AX is multiplied by BX, and the 32-bit result is written to the pair DX:AX. DX is the high half and AX the low half.Division. In a 16-bit division the dividend is the 32-bit DX:AX. The quotient is written to AX and the remainder to DX. For example, with DX = 0012h, AX = 3405h, and BX = 0100h, DIV BX computes 00123405h ÷ 0100h. The quotient is 1234h and the remainder 0005h: AX = 1234h, DX = 0005h. If the quotient does not fit in 16 bits, the processor raises a type 0 interrupt (divide error). That is why DX is cleared before dividing a 16-bit number; if a leftover value remains in DX, the dividend becomes much larger than expected.
Port number. The IN and OUT instructions take the port number in two ways. Ports between 0 and 255 can be written into the instruction as a constant: IN AL, 60h. For ports above 255 the number is put in DX: OUT DX, AL. On the PC the first serial port (COM1) starts at 03F8h and the printer port at 0378h; these are reached only with DX. DX being 16 bits covers the whole 65,536-port I/O address space.
DOS calls. Many INT 21h services expect a memory address in DX. Service 09h, which writes a string to the screen, takes the address of the string from DS:DX: LEA DX, message.
The program in the slides shows two of these roles together:
MOV AX, 1234h
MOV BX, 0100h
MUL BX ; DX:AX = AX*BX
MOV AX, 00FFh
MOV BL, 2
MUL BL ; AX = AL*BL
MOV DX, 03F8h ; port address
OUT DX, AL ; write to port| Row | Instruction | AX | BX | DX | CF | OF | SF ZF AF PF |
|---|---|---|---|---|---|---|---|
| 1 | MOV AX, 1234h | 1234h | 0000h | 0000h | 0 | 0 | 0 0 0 0 |
| 2 | MOV BX, 0100h | 1234h | 0100h | 0000h | 0 | 0 | 0 0 0 0 |
| 3 | MUL BX | 3400h | 0100h | 0012h | 1 | 1 | ? ? ? ? |
| 4 | MOV AX, 00FFh | 00FFh | 0100h | 0012h | 1 | 1 | ? ? ? ? |
| 5 | MOV BL, 2 | 00FFh | 0102h | 0012h | 1 | 1 | ? ? ? ? |
| 6 | MUL BL | 01FEh | 0102h | 0012h | 1 | 1 | ? ? ? ? |
| 7 | MOV DX, 03F8h | 01FEh | 0102h | 03F8h | 1 | 1 | ? ? ? ? |
| 8 | OUT DX, AL | 01FEh | 0102h | 03F8h | 1 | 1 | ? ? ? ? |
In the third row 1234h × 0100h = 00123400h is computed. Multiplying by 0100h shifts the hexadecimal number two digits to the left. The 32-bit result is split in two: DX = 0012h, AX = 3400h. MUL sets CF = OF = 1 if the high half of the result is not zero. These two flags mean “the result did not fit in the lower half; DX must be looked at too.” After MUL, SF, ZF, AF, and PF are undefined: Intel has not specified the value of these flags and a program must not rely on them. The “?” mark in the table shows this.
The fifth row changes only BL. Because BX was 0100h beforehand, BH = 01h stays and BX = 0102h. The sixth row is an 8-bit multiplication: AL × BL = FFh × 02h = 255 × 2 = 510 = 01FEh. The result is written to the whole of AX; the 0012h in DX stays as it is. Because the high half AH = 01h is not zero, CF = OF = 1 again.
In the seventh row DX holds not data this time but a port number: 03F8h is the data register of the first serial port. The eighth row sends the FEh in AL to this port. OUT uses only the low byte of AX; the 01h in AH does not go to the port. A single byte, FEh, is written to the port.
Thinking the result of MUL is only in AX and going on using DX for another job. A 16-bit MUL always erases the value in DX; DX is written even if the result is small. If there is a value that must be kept in DX, it is pushed onto the stack before the MUL.
With AL = 10h and BL = 03h, what are AX, CF, and OF after MUL BL?
10h × 03h = 16 × 3 = 48 = 0030h. AX = 0030h. Because the high half AH = 00h, the result fit in AL and CF = OF = 0. In this case the program can go on by looking only at AL. Had CF been 1, the result would have to be sought in the whole of AX.
2.2.4The pointer and index registers
The SP, BP, SI, and DI registers are 16 bits and have no 8-bit halves. All four mostly hold not data but an offset: the distance of a cell in memory from the start of the segment it belongs to. SP and BP work in the stack segment (SS), and SI and DI in the data segments (DS, ES). They can also be used in arithmetic instructions: ADD SI, 2 is the usual way to advance an index while walking an array.
2.2.4.1SP: the stack pointer
The stack is a region of memory that works in last-in, first-out (LIFO) order. The stack pointer (SP) holds the offset of the topmost item of the stack. The physical address of the stack is always given by the pair SS:SP.
The 8086’s stack is recognized by three properties. First, items are always 16 bits: PUSH AX is valid, PUSH AL is not. The assembler counts the line PUSH AL as an error. Second, the stack grows downward in memory; each PUSH writes to a lower address. Third, the order of operation is fixed:
PUSH source: first SP ← SP − 2, then [SS:SP] ← source. The low byte is written to SP and the high byte to SP + 1.POP destination: first destination ← [SS:SP], then SP ← SP + 2.
SP always points to the last valid item on the stack. When a new item is to be put on the stack, room is made first and then it is written. POP does not erase the cell it reads; the value stays in memory, but since SP has moved above it, it is no longer considered part of the stack. The next PUSH writes over that cell.
Tracing the following program makes these rules concrete. Assume the stack is empty and SP starts from 0000h.
MOV AX, 1111h
PUSH AX
MOV BX, 2222h
PUSH BX
POP CX
POP DX| Instruction | SP | Stack (address: value) | CX | DX |
|---|---|---|---|---|
MOV AX, 1111h | 0000h | empty | 0000h | 0000h |
PUSH AX | FFFEh | FFFEh: 1111h | 0000h | 0000h |
MOV BX, 2222h | FFFEh | FFFEh: 1111h | 0000h | 0000h |
PUSH BX | FFFCh | FFFCh: 2222h, FFFEh: 1111h | 0000h | 0000h |
POP CX | FFFEh | FFFEh: 1111h | 2222h | 0000h |
POP DX | 0000h | empty | 2222h | 1111h |
The first PUSH makes SP FFFEh by computing 0000h − 2. In 16-bit arithmetic, going below 0 means wrapping to the top; so SP = 0000h is a start from which the whole 64 KB stack segment can be used. The value 1111h is written to the bytes FFFEh–FFFFh. The second PUSH lowers SP to FFFCh and puts 2222h there. Figure 2.2.7 shows the stack at this moment. SP points to the topmost item, that is, the most recently pushed 2222h.
The POPs run in the reverse order. POP CX takes the topmost 2222h and SP rises to FFFEh. POP DX takes 1111h and SP becomes 0000h again. In the end CX = 2222h and DX = 1111h: the values have come back in the reverse of the order they were pushed. That is what LIFO order means. To save and restore AX and BX in a program, PUSH AX, PUSH BX and then POP BX, POP AX are written; the POP order is the reverse of the PUSH order.
The fact “SP = FFFEh when the stack is empty” is not a general rule. When DOS loads a .COM program it makes SP FFFEh and puts the word 0000h at address FFFEh. So the RET at the end of the program takes this zero into IP and returns to the DOS exit code at the start of the program. emu8086 also starts .COM programs this way. If the same program were run as a .COM file, SP would drop first to FFFCh and then to FFFAh; the values and order would not change.
The implicit users of SP are not only PUSH and POP. CALL pushes the return address onto the stack and RET takes it from the stack. An interrupt pushes FLAGS, CS, and IP; IRET takes all three back. PUSHF and POPF move the flags register. All these instructions update SP themselves. If the programmer writes to SP directly (MOV SP, …), the position of the stack is changed; this is done only at the start of a program or when changing the stack segment.
Not balancing the number of PUSHes and POPs. If an extra PUSH is left inside a procedure, RET takes that value into IP instead of the return address and the program jumps to a random address. Skipping a POP in a conditional branch gives the same result. On every exit path the stack must return to the state it had at entry.
2.2.4.2BP: the base pointer
BP (base pointer) is used to point to a fixed location on the stack. Memory accesses made with BP use the SS segment by default: [BP+4] is the address SS:BP+4. [BX+4], written with BX, goes to the DS segment. The only difference between the two base registers is this default segment.
SP points to the top of the stack but keeps changing inside a procedure: every PUSH and POP moves it. Reaching parameters relative to SP is therefore laborious; after a PUSH the offset of the same parameter grows by 2 bytes. BP solves this problem. At the start of the procedure the current value of SP is copied to BP. From then on, however much SP changes, BP stays fixed and each parameter is always at the same distance from BP.
MOV BX, 1234h
PUSH BX ; parameter
CALL ADDP
MOV DX, AX ; result
RET
ADDP PROC
PUSH BP
MOV BP, SP ; frame base
MOV AX, [BP+4] ; 1st param
POP BP
RET 2
ADDP ENDPThe procedure body is the same as the one in the slides. The calling part has been added with three lines that push the parameter onto the stack and take the result into DX. The program starts as a .COM program with SP = FFFEh.
| Instruction | SP | BP | AX | Stack (address: value) |
|---|---|---|---|---|
MOV BX, 1234h | FFFEh | 0000h | 0000h | FFFE: 0000 |
PUSH BX | FFFCh | 0000h | 0000h | FFFC: 1234, FFFE: 0000 |
CALL ADDP | FFFAh | 0000h | 0000h | FFFA: 0107, FFFC: 1234, … |
PUSH BP | FFF8h | 0000h | 0000h | FFF8: 0000, FFFA: 0107, FFFC: 1234, … |
MOV BP, SP | FFF8h | FFF8h | 0000h | same |
MOV AX, [BP+4] | FFF8h | FFF8h | 1234h | same |
POP BP | FFFAh | 0000h | 1234h | FFFA: 0107, FFFC: 1234, … |
RET 2 | FFFEh | 0000h | 1234h | FFFE: 0000 |
MOV DX, AX | FFFEh | 0000h | 1234h | FFFE: 0000 |
CALL pushes the return address 0107h onto the stack. This is the address of the instruction after the CALL, that is, of MOV DX, AX: the program starts at 0100h, MOV BX, 1234h is 3 bytes, PUSH BX is 1 byte, CALL is 3 bytes, and 0100h + 7 = 0107h. The PUSH BP at procedure entry saves the caller’s BP value. With MOV BP, SP, BP = FFF8h and the base of the frame is fixed. Now the frame reads like this:
[BP]= FFF8h: the saved old BP;[BP+2]= FFFAh: the return address 0107h;[BP+4]= FFFCh: the first parameter 1234h.
MOV AX, [BP+4] takes the parameter into AX. POP BP restores the caller’s BP. RET 2 does two jobs: it takes the return address into IP and also adds 2 to SP, discarding the parameter on the stack. SP returns to the value FFFEh it had at entry; the stack is in the state it had before the call. Even if an extra PUSH had been done in the procedure, [BP+4] would not have changed; that is the worth of BP.
Let ADDP be called with two parameters: first PUSH a, then PUSH b. At which addresses are a and b inside the procedure, and how many bytes must RET discard on return?
The last pushed, b, is right above the return address: [BP+4] = b, and a, pushed before it, is at [BP+6]. Two parameters take 4 bytes; the return is done with RET 4. Each time the number of parameters grows, the offset of the first parameter grows by 2 bytes, but the last parameter is always at [BP+4].
2.2.4.3SI and DI: the index registers
SI (source index) and DI (destination index) take their names from their roles in the string instructions. String instructions work on consecutive bytes or words in memory: copy (MOVS), compare (CMPS), scan (SCAS), load (LODS), and store (STOS). The operands of these instructions are not written in the instruction; they are implicit:
- The source is always DS:SI: MOVSB, CMPSB, and LODSB read from here.
- The destination is always ES:DI: MOVSB, STOSB, and SCASB write or compare here.
- After each step SI and DI increase or decrease by 1 (byte) or 2 (word) according to the DF flag.
Outside the string instructions, SI and DI are ordinary index registers. When MOV AL, [SI] or MOV [DI], AL is written, both use the DS segment by default. The ES:DI rule is only for the destination of string instructions. This distinction matters when DS and ES point to different segments.
An index register is a register that holds a position within an array or string. The 8086’s index registers are SI and DI. When used together with a base register ([BX+SI], [BP+DI+5]), the effective address is the sum of the two registers and the constant.
The program in the slides copies the string “ABC” from 0200h to 0300h. In a .COM program DS = ES, so the two areas are in the same segment.
CLD ; DF=0: addresses go up
MOV SI, 0200h ; source
MOV DI, 0300h ; destination
MOV CX, 3 ; byte count
REP MOVSB ; ES:[DI] ← DS:[SI]| Step | Instruction | SI | DI | CX | DF | 0300h–0302h |
|---|---|---|---|---|---|---|
| 1 | CLD | 0000h | 0000h | 0000h | 0 | — — — |
| 2 | MOV SI, 0200h | 0200h | 0000h | 0000h | 0 | — — — |
| 3 | MOV DI, 0300h | 0200h | 0300h | 0000h | 0 | — — — |
| 4 | MOV CX, 3 | 0200h | 0300h | 0003h | 0 | — — — |
| 5 | REP MOVSB (pass 1) | 0201h | 0301h | 0002h | 0 | A — — |
| 6 | REP MOVSB (pass 2) | 0202h | 0302h | 0001h | 0 | A B — |
| 7 | REP MOVSB (pass 3) | 0203h | 0303h | 0000h | 0 | A B C |
CLD clears DF: SI and DI will increase at every step. SI points to the start of the source and DI to the start of the destination; CX says how many bytes will be copied. On each pass REP MOVSB does four things: it copies the byte at DS:SI to ES:DI, increments SI by 1, increments DI by 1, and decrements CX by 1. When CX reaches zero the repetition ends. After three passes “ABC” has been copied to the destination, and SI and DI point just past the copied area (Figure 2.2.8).
The REP prefix uses CX and MOVSB uses SI and DI implicitly. A single two-byte instruction (F3 A4) does the work of an entire loop. Writing the same copy with MOV AL, [SI], MOV [DI], AL, INC SI, INC DI, and LOOP takes five instructions and more clock cycles on every pass. The clearest gain from giving the registers implicit roles in the 8086’s design is seen here.
2.2.5The segment registers and IP
The 8086’s address bus is 20 bits and addresses 1 MB of memory. Its registers, however, are 16 bits and by themselves can point to only 64 KB. The two ends are reconciled by dividing memory into segments: every memory access consists of a segment register and a 16-bit offset. This section treats segmentation from the registers’ point of view: how to write to the segment registers, which register pairs with which segment, and how IP advances.
2.2.5.1Writing to the segment registers
There are four segment registers: CS (code segment), DS (data segment), SS (stack segment), and ES (extra segment). Each holds a 16-bit paragraph number. The physical address where a segment starts is 16 times this number; the segment extends from there for at most 64 KB.
The physical address (20 bits) = segment register × 10h + offset. Multiplying by 10h (16) is appending a 0 to the end of the hexadecimal number. If DS = 2000h and BX = 0500h, the physical address of the access [BX] is 20000h + 0500h = 20500h.
The rules for writing to the segment registers are stricter than for the other registers:
- A constant cannot be loaded.
MOV DS, 2000hcannot be written; the assembler rejects the line. The value is first put in a general-purpose register:MOV AX, 2000handMOV DS, AX. - CS cannot be written with MOV. A change in CS means the program jumps somewhere else; this is done with far JMP, far CALL, RETF, INT, and IRET. The line
MOV CS, AXis also rejected. - There is no MOV from segment to segment.
MOV ES, DScannot be written. The value is transferred either through a register (MOV AX, DS,MOV ES, AX) or through the stack (PUSH DS,POP ES). - Arithmetic cannot be done with the segment registers.
ADD DS, 10horINC ESdo not exist.
The reason for these restrictions is that the segment registers are in the BIU, not the EU. The ALU’s output is not directly connected to the segment registers; data reaches the segment registers only through MOV and POP, from a register or a memory word. The following short program sets up and uses a data segment. Suppose the byte 5Ah is at physical address 20500h.
MOV AX, 2000h
MOV DS, AX ; DS = 2000h: segment starts at 20000h
MOV BX, 0500h
MOV AL, [BX] ; AL ← [20500h]
MOV [BX+1], AL ; [20501h] ← AL| Instruction | AX | DS | BX | Physical address | 20500h–20501h |
|---|---|---|---|---|---|
MOV AX, 2000h | 2000h | 0700h | 0000h | — | 5A 00 |
MOV DS, AX | 2000h | 2000h | 0000h | — | 5A 00 |
MOV BX, 0500h | 2000h | 2000h | 0500h | — | 5A 00 |
MOV AL, [BX] | 205Ah | 2000h | 0500h | 20500h (read) | 5A 00 |
MOV [BX+1], AL | 205Ah | 2000h | 0500h | 20501h (write) | 5A 5A |
DS is initially 0700h, given by the .COM loader. After the second row, every access made with BX is relative to the base 20000h. When 5Ah is read into AL, the 20h in AH stays in place, so AX = 205Ah; the independence of the 8-bit halves is seen here too.
2.2.5.2Register pairs
An offset by itself is not an address; which segment it belongs to must also be known. The 8086 chooses a segment register by default for each type of access. Since the programmer does not write this, these pairs are also part of the implicit roles (Table 2.2.14).
| Pair | Use | Example |
|---|---|---|
CS:IP | next instruction | every instruction fetch |
SS:SP | top of the stack | PUSH, POP, CALL, RET, INT |
SS:BP | stack frame | MOV AX, [BP+4] |
DS:BX, DS:SI, DS:DI | data | MOV AL, [BX+SI] |
DS:SI → ES:DI | string instructions | MOVSB, CMPSB |
The rule can be summarized briefly: if the address contains BP the segment is SS, and if not it is DS. [BP+SI] uses SS and [BX+SI] uses DS. The destination of string instructions is always ES. The default segment can be changed by adding a segment prefix in front of the instruction: MOV AL, ES:[BX] reads the data from the ES segment. A prefix cannot be used for instruction fetch (CS:IP) and stack operations (SS:SP). The string destination ES:DI cannot be changed either; only the segment of the source DS:SI can be redirected to another segment with a prefix.
With DS = 1000h, SS = 3000h, SI = 0020h, and BP = 0020h, which physical addresses do MOV AL, [SI] and MOV AL, [BP] read?
[SI] does not contain BP; the segment is DS: 1000h × 10h + 0020h = 10000h + 0020h = 10020h. [BP], on the other hand, uses the SS segment: 30000h + 0020h = 30020h. The two instructions have the same offset but their physical addresses are 128 KB apart.
Trying to access an array with BP. If MOV BP, OFFSET array and MOV AL, [BP] are written, the access goes to the SS segment. In .COM programs the mistake stays hidden because DS = SS; in a .EXE program where DS and SS differ, the wrong memory is read. For data arrays BX, SI, or DI is used.
2.2.5.3IP: the instruction pointer
The instruction pointer (IP) holds the offset of the next instruction to be executed within the code segment. The physical address of the next instruction is CS × 10h + IP. In other processors this register is called the program counter (PC).
While an instruction executes, IP is advanced by the length of the instruction and points to the next instruction. 8086 instructions are between 1 and 6 bytes; so IP does not grow in regular steps. The addresses in the AX = AH : AL program of Table 2.2.4 are a good example of this (Table 2.2.15).
| Address of the instruction | Instruction | Machine code | Length | Next IP |
|---|---|---|---|---|
| 0100h | MOV AX, 1234h | B8 34 12 | 3 | 0103h |
| 0103h | MOV AL, 0FFh | B0 FF | 2 | 0105h |
| 0105h | ADD AL, 1 | 04 01 | 2 | 0107h |
| 0107h | MOV AX, 12FFh | B8 FF 12 | 3 | 010Ah |
| 010Ah | ADD AX, 1 | 05 01 00 | 3 | 010Dh |
Instructions that carry a 16-bit constant are 3 bytes, and those that carry an 8-bit constant are 2 bytes. The low byte of a constant in machine code comes first: 1234h is written as 34 12.
The instructions that take IP out of sequence are these: JMP and the conditional jumps, LOOP, CALL, RET, INT, and IRET. IP cannot be written with MOV and cannot be read with MOV; IP is not an operand the programmer reaches by name. There is an indirect way to learn the value of IP: the CALL instruction pushes the return address onto the stack, and with a POP this value can be taken into a register.
Because of the BIU’s prefetch arrangement, inside the processor the bytes in the queue and the address IP points to may differ for a moment. From the programmer’s point of view this difference is invisible; IP always gives the address of the next instruction to be executed. When a jump occurs the queue is flushed and fetching starts again from the new CS:IP.
2.2.6The flags register and the status flags
2.2.6.1Structure of the flags register
When an addition is done, the processor produces not only the result but also records a few facts about it. Is the result zero? Negative? Did it fit in 8 bits? These facts are one-bit indicators and are called flags. The 8086 gathers its flags in the 16-bit flags register (FLAGS). This register is also called the status register.
Only 9 of the register’s 16 bits are used (Figure 2.2.9). They fall into two groups:
The status flags are CF, PF, AF, ZF, SF, and OF. After arithmetic and logic instructions the processor sets (1) or clears (0) them itself according to the result. The control flags are DF, IF, and TF. They are not affected by results; the programmer changes how the processor works by setting them.
The main users of the status flags are the conditional jump instructions. JZ looks at ZF, JC at CF, JS at SF, and JO at OF; signed comparisons such as JG and JL evaluate SF and OF together. Every if and every loop condition in a high-level language becomes, in assembly, a comparison followed by a jump that looks at the flags. Knowing when and how the flags are set is therefore fundamental to 8086 programming.
The bit order of the flags is not random. The five flags in the low byte (SF, ZF, AF, PF, CF) are in the same places as in the flags byte of the 8080 processor. This arrangement was kept to ease the translation of 8080 programs, and it is the reason the LAHF/SAHF instructions exist. OF and the control flags were added with the 8086 and put in the high byte.
2.2.6.2How are flags produced in hardware?
The status flags are produced from the ALU’s output with a few simple gates. With digital design knowledge, building this circuit is not hard. In an n-bit adder, let ri be the i-th bit of the result and ci the carry into the i-th bit; cn is the carry out of the top bit. In an 8-bit operation n = 8.
| Flag | Logic expression | Circuit |
|---|---|---|
| CF | c8 (borrow in subtraction) | carry out of the last full adder |
| AF | c4 | carry from bit 3 to bit 4 |
| ZF | ¬(r7 + r6 + … + r0) | 8-input NOR gate |
| SF | r7 | copy of the top bit (no gate) |
| PF | ¬(r7 ⊕ r6 ⊕ … ⊕ r0) | XOR tree and a NOT gate at the output |
| OF | c7 ⊕ c8 | XOR of the carries into and out of the top bit |
In a 16-bit operation c16 is used for CF, r15 for SF, and c15 ⊕ c16 for OF; ZF looks at all 16 bits. AF and PF, however, are produced from only the low byte even in a 16-bit operation. The point to notice in the table is that all the flags are produced at the same time and together with the result. The processor does not ask “signed or unsigned?”; after every addition it sets all six flags at once. The program decides which one is meaningful.
Subtraction is done in the ALU as addition of the two’s complement: A − B = A + ¬B + 1. A carry out of the top bit in this addition means no borrow was taken. The 8086 sets CF in subtraction as the inverse of this carry; thus CF = 1 always means “a borrow was taken.” The same inversion is done for AF.
2.2.6.3SF: the sign flag
The sign flag (SF) is a copy of the most significant bit (MSB) of the result. It is bit 7 in an 8-bit operation and bit 15 in a 16-bit operation. In two’s complement the MSB is the sign bit: if 1 the number is negative, if 0 it is positive or zero. SF therefore says whether the result is negative when interpreted as signed.
| Result (8 bits) | Binary | Signed value | MSB | SF |
|---|---|---|---|---|
35h | 0011 0101 | +53 | 0 | 0 |
7Fh | 0111 1111 | +127 | 0 | 0 |
80h | 1000 0000 | −128 | 1 | 1 |
C2h | 1100 0010 | −62 | 1 | 1 |
FFh | 1111 1111 | −1 | 1 | 1 |
The rule is short: for results from 00h to 7Fh, SF = 0, and for those from 80h to FFh, SF = 1. In 16 bits the boundary is between 7FFFh and 8000h. The processor does not know whether a number is signed or unsigned. The byte C2h is 194 as unsigned and −62 as signed; in both interpretations SF = 1. Reading SF as “negative” is the programmer’s choice and is meaningful only when working with signed numbers.
Thinking SF gives the sign of the true mathematical result. In 70h + 10h = 80h two positive numbers are added and the true result is +128. Even so SF = 1, because the MSB of the 8-bit result is 1. The result did not fit in the signed range; OF shows this. SF gives the correct sign only when OF = 0.
2.2.6.4ZF and PF: the zero and parity flags
The zero flag (ZF) is 1 if all bits of the result are zero; otherwise it is 0. The value of the flag and the value of the result look opposite: ZF = 1 means “the result is zero.” This confusion is cleared by reading the flag as a question: “is the result zero?” If yes, 1.
ZF is used most in equality tests. CMP AX, BX computes AX − BX but writes the result nowhere; it only sets the flags. If AX = BX the difference is zero and ZF = 1. The following JE (jump if equal, the same instruction as JZ) looks at ZF. With AX = BX = 1234h, after CMP ZF = 1, PF = 1, and the other status flags are 0.
Three ways of clearing a register give an interesting comparison in terms of ZF. SUB AL, AL and XOR AL, AL make the result zero, so they set ZF = 1 and CF = 0. MOV AL, 0, however, does not touch the flags at all; the flags left from the previous operation stay. If the register is to be cleared right before a conditional jump, this difference matters.
The parity flag (PF) is 1 if the number of 1s in the low 8 bits of the result is even, and 0 if it is odd. In 16-bit operations too only the low byte is looked at. Figure 2.2.10 gives two examples.
The number zero has no 1s at all; since zero is an even number, PF = 1 for 00h. PF’s historical use was error checking in serial communication. A parity bit is added to every character sent, and the receiver checks the parity of the byte it receives; a single-bit corruption changes the parity and is noticed. In today’s programs PF is rarely used, but every arithmetic and logic operation of the 8086 still sets it. The JP and JNP instructions look at this flag.
After ADD AX, 0009h with AX = 7FF8h, what are ZF and PF?
7FF8h + 0009h = 8001h. The result is not zero: ZF = 0. For PF only the low byte 01h = 0000 0001b is looked at. It has one 1, an odd number: PF = 0. The 1 in the high byte 80h is not counted.
2.2.6.5AF: the auxiliary carry flag
The auxiliary carry flag (AF) is 1 if during the operation there is a carry (in addition) or a borrow (in subtraction) from bit 3 to bit 4, and 0 if not. In other words, it shows whether there was an overflow from the low nibble (a group of 4 bits) to the upper nibble.
This flag is specific to binary-coded decimal (BCD) arithmetic. In BCD each decimal digit is held in a separate nibble: the number 17 is written 0001 0111 = 17h. When BCD numbers are added with a binary adder, the result is not always valid BCD. In the example in Figure 2.2.11, 08h + 09h gives 11h; the correct BCD answer is 17. Because the low nibble passed 16, the 6 of the decimal system has “been lost.” AF = 1 says this loss happened. The DAA (decimal adjust after addition) instruction looks at AF and adds 6 to the low nibble: 11h + 06h = 17h. After DAA, AL = 17h.
One property of AF is that the programmer cannot reach it directly. There is no conditional jump instruction that tests AF. There is no special instruction that sets or clears AF either. Only DAA, DAS, AAA, and AAS use it. AF can still be read and written: LAHF and PUSHF copy it together with the other flags into a register or onto the stack; SAHF and POPF write it back.
What is AF in the operations 05h − 07h and 9Ch + 64h?
In 05h − 07h the low nibbles are 5 − 7; since 5 is less than 7, a borrow is taken from bit 4: AF = 1. In 9Ch + 64h the low nibbles are C + 4 = 12 + 4 = 16; since it exceeds 15, a carry passes to bit 4: AF = 1.
2.2.6.6CF: the carry flag
The carry flag (CF) is 1 if in an n-bit addition the result does not fit in n bits, that is, a carry comes out beyond the top bit. In subtraction, if a larger number is subtracted from a smaller one and a borrow is taken, CF = 1 as well. CF is the overflow indicator for unsigned numbers.
| Operation (8 bits) | Unsigned interpretation | Result | CF |
|---|---|---|---|
FFh + 01h | 255 + 1 = 256 > 255 | 00h | 1 |
80h + 80h | 128 + 128 = 256 > 255 | 00h | 1 |
70h + 10h | 112 + 16 = 128 ≤ 255 | 80h | 0 |
05h − 07h | 5 − 7 < 0 (borrow) | FEh | 1 |
07h − 05h | 7 − 5 = 2 | 02h | 0 |
In the example 05h − 07h the result is FEh. In the unsigned interpretation this is 254 and is not the true result −2; CF = 1 reports this. The same FEh is −2 in the signed interpretation and is correct. So in a signed subtraction CF = 1 is not an error; whether there is an error is told by OF.
CF has a few properties that differ from the other flags:
- The programmer can change it.
STCmakes CF 1,CLCmakes it 0, andCMCflips it. CF is the only status flag that can be set and cleared directly. - INC and DEC do not touch CF. With AL = FFh,
ADD AL, 1makes CF = 1;INC ALproduces the same result but leaves CF at its previous value. This design is so that changing a loop counter with INC/DEC does not disturb the carry of a multiword addition. - In shift and rotate instructions the last bit pushed out goes to CF.
SHL AL, 1with AL = 81h gives AL = 02h and CF = 1. - Multiword arithmetic.
ADC(add with carry) adds CF to the sum, andSBB(subtract with borrow) subtracts CF. In this way a 16-bit processor can add 32- or 64-bit numbers piece by piece.
A 32-bit addition is the best-known use of ADC. Let 1 be added to DX:AX = 0001FFFFh:
MOV AX, 0FFFFh ; low word
MOV DX, 0001h ; high word
ADD AX, 1 ; AX = 0000h, CF = 1
ADC DX, 0 ; DX = 0001h + 0 + CF = 0002hIn the low word FFFFh + 1 = 10000h; AX = 0000h and the overflowing 1 waits in CF. ADC adds both the 0 and CF to the high word: DX = 0002h. The result is DX:AX = 00020000h. Just as in a decimal addition the carry moves to the digit on the left, here CF has been carried from word to word.
2.2.6.7OF: the overflow flag
The overflow flag (OF) is 1 if the result, interpreted as signed, does not fit in the number of bits used. In 8 bits the signed range is −128 … +127, and in 16 bits −32,768 … +32,767. CF shows unsigned overflow and OF shows signed overflow.
There are two equivalent ways to find OF for addition:
- The sign rule. If two positive numbers are added and the result is negative, or two negative numbers are added and the result is positive, OF = 1. The sum of two numbers of different signs never overflows, because the result stays between the two numbers.
- The carry rule. If the carry into the MSB and the carry out of the MSB differ, OF = 1 (c7 ⊕ c8 in Table 2.2.16).
For subtraction the sign rule is adapted as follows: if a negative is subtracted from a positive and a negative result is found, or a positive is subtracted from a negative and a positive result is found, OF = 1. For example, in 80h − 01h = 7Fh, −128 − 1 = −129 was meant to be computed and the result came out +127: OF = 1. The difference of two numbers with the same sign never overflows.
Table 2.2.19 gives the four possible combinations of CF and OF with an example each. Each row must be read both as unsigned and as signed.
| Operation | Unsigned interpretation | Signed interpretation | Result | CF | OF |
|---|---|---|---|---|---|
05h + 03h | 5 + 3 = 8 | 5 + 3 = 8 | 08h | 0 | 0 |
7Fh + 01h | 127 + 1 = 128 | 127 + 1 ≠ −128 | 80h | 0 | 1 |
FFh + 01h | 255 + 1 ≠ 0 | −1 + 1 = 0 | 00h | 1 | 0 |
80h + 80h | 128 + 128 ≠ 0 | −128 + (−128) ≠ 0 | 00h | 1 | 1 |
The rows can also be checked with the carry rule. In 7Fh + 01h all of the low seven bits are 1; in the addition a carry goes into bit 7 (c7 = 1) but no carry comes out of bit 7 (c8 = 0). The two differ: OF = 1. In FFh + 01h both c7 and c8 are 1: OF = 0, CF = 1. In 80h + 80h no carry goes into bit 7 (c7 = 0), but the sum of the two 1s produces a carry out of bit 7 (c8 = 1): OF = 1, CF = 1.
CF and OF are independent of each other; all four combinations are seen in the table. The processor always computes both. If the program works with unsigned numbers it looks at CF (and jumps such as JA and JB), and if it works with signed numbers it looks at OF (and jumps such as JG, JL, and JO).
After MOV AL, 0C8h and ADD AL, 64h, what are AL and the six status flags?
C8h + 64h = 12Ch. The low byte 2Ch is written to AL, and the overflowing 1 goes to CF: CF = 1. In the signed interpretation C8h = −56 and 64h = +100; −56 + 100 = 44 = 2Ch is correct, and the sum of numbers of different signs does not overflow: OF = 0. 2Ch = 0010 1100b; since the MSB is 0, SF = 0, and since the result is not zero, ZF = 0. The low byte has three 1s: PF = 0. The low nibbles are 8 + 4 = 12, which does not exceed 15: AF = 0.
Using the word “overflow” for both flags and counting CF = 1 as an error in a signed computation. In −1 + 1 (FFh + 01h), CF = 1 but the signed result 0 is perfectly correct. Only OF tells whether a signed computation is correct.
INC and DEC set OF too. With AL = 7Fh, INC AL makes AL = 80h; +127 + 1 has exceeded the signed range and OF = 1, SF = 1. In the NEG instruction the only overflow case is the smallest negative number: NEG AL with AL = 80h again produces 80h, because +128 cannot be represented in 8 bits; in this case OF = 1.
2.2.7The control flags
DF, IF, and TF do not describe the result of an operation; they determine how the processor will work from now on. Arithmetic instructions do not touch these flags. The programmer sets them with special instructions or by changing the flags register through the stack.
2.2.7.1DF: the direction flag
The direction flag (DF) determines in which direction the string instructions walk through memory (Figure 2.2.12):
- DF = 0: from a low address toward a high one; at each step SI and DI increase. The
CLDinstruction makes DF 0. - DF = 1: from a high address toward a low one; at each step SI and DI decrease. The
STDinstruction makes DF 1.
The step size depends on the width of the instruction: 1 for byte instructions (MOVSB, LODSB …) and 2 for word instructions (MOVSW, LODSW …). DF affects only the string instructions. An ordinary instruction such as MOV AL, [SI] never changes SI.
DF = 0 is enough to process an array from start to end, and most programs use it. For this reason, instead of trusting the value of DF, it is a good habit to write CLD or STD before every string operation. If another routine has left DF at 1, a copy loop that does not write CLD walks through memory in the reverse direction.
The real justification for walking backward is overlapping areas. If the source and destination overlap in memory, the direction of the copy determines the result. If the destination is ahead of the source (at a higher address), the copy must be done from the end to the start. Otherwise the not-yet-read bytes of the source get overwritten by the bytes written to the destination.
2.2.7.2Code trace: overlapping copy with DF = 1
The program in the slides shifts the string “KLMN” in memory one byte to the right. The source is arr..arr+3 and the destination is arr+1..arr+4; the two areas overlap in three bytes.
org 100h
mov si, offset arr+3 ; source
mov di, offset arr+4 ; destination
mov cx, 4
std ; DF = 1
rep movsb
cld
ret
arr db 'KLMN', 0The program starts at 0100h. The instructions take 3 + 3 + 3 + 1 + 2 + 1 + 1 = 14 bytes; so arr is placed at address 010Eh. 'K' is at 010Eh, 'L' at 010Fh, 'M' at 0110h, 'N' at 0111h, and the terminating 0 at 0112h. SI is set to point to the last byte of the source (arr+3 = 0111h) and DI to the last byte of the destination (arr+4 = 0112h).
std, before the copy: SI = 0111h ('N'), DI = 0112h, CX = 4, DF = 1.| Row | Instruction | SI | DI | CX | DF | 010Eh … 0112h |
|---|---|---|---|---|---|---|
| 2 | mov si, offset arr+3 | 0111h | 0000h | 0 | 0 | K L M N · |
| 3 | mov di, offset arr+4 | 0111h | 0112h | 0 | 0 | K L M N · |
| 4 | mov cx, 4 | 0111h | 0112h | 4 | 0 | K L M N · |
| 5 | std | 0111h | 0112h | 4 | 1 | K L M N · |
| 6 | rep movsb (pass 1) | 0110h | 0111h | 3 | 1 | K L M N N |
| 6 | rep movsb (pass 2) | 010Fh | 0110h | 2 | 1 | K L M M N |
| 6 | rep movsb (pass 3) | 010Eh | 010Fh | 1 | 1 | K L L M N |
| 6 | rep movsb (pass 4) | 010Dh | 010Eh | 0 | 1 | K K L M N |
| 7 | cld | 010Dh | 010Eh | 0 | 0 | K K L M N |
In the first pass the 'N' at 0111h is copied to 0112h. The terminating zero is overwritten, but this byte is not part of the source. In the second pass the 'M' at 0110h is written to 0111h. The 'N' at 0111h had already been read and moved in the previous pass; overwriting it does no harm. Each pass overwrites the byte read in the previous pass, not the byte to be read in the next. After the fourth pass memory holds “KKLMN”: the string has shifted one place right, and the 'K' at the start has stayed in place (Figure 2.2.14). The cld on the last line returns DF to the value the rest of the program expects.
Let us try the same shift in the forward direction with CLD: SI = arr, DI = arr+1, CX = 4. The first pass writes 'K' to 010Fh and overwrites 'L'. The second pass reads from 010Fh, but 'K' is there now; 'K' is written to 0110h. Every pass reads the 'K' written by the previous pass. The result is “KKKKK.” The rule is summarized like this: if the destination is ahead of the source, copy backward (STD); if behind it, copy forward (CLD).
Setting SI and DI to the start of the areas when copying backward with STD. With DF = 1 the string instruction decrements addresses; SI and DI must point to the last byte of the areas. In a word copy (MOVSW) the address of the last word is given, that is, the address one before the last byte.
2.2.7.3IF: the interrupt flag
The 8086 has an input pin called INTR. When a peripheral such as the keyboard, a timer, or a serial port wants service from the processor, it activates this pin. The processor finishes the current instruction, interrupts the program, and runs an interrupt service routine (ISR). The interrupt flag (IF) determines whether these requests are accepted:
- IF = 1: maskable interrupt requests coming on INTR are accepted.
STImakes IF 1. - IF = 0: these requests are ignored, that is, masked.
CLImakes IF 0.
IF does not block everything. The non-maskable interrupt coming on the NMI pin is not affected by IF; it is reserved for events that cannot be postponed, such as a power failure or a memory parity error. Software interrupts the program starts itself with the INT n instruction do not look at IF either. IF filters only the requests that come from outside, on the INTR pin.
The stack example shows well why a program may want to turn interrupts off. To move the stack, both SS and SP are changed. If an interrupt arrives after SS has changed but before SP has, the processor pushes FLAGS, CS, and IP onto a half-built, wrong stack. These two instructions are a unit that must not be interrupted:
CLI ; disable interrupts
MOV AX, 9000h
MOV SS, AX ; new stack segment
MOV SP, 0FFFEh ; new stack top
STI ; enable interruptsThe 8086 itself takes a precaution against this danger: after an instruction that writes to a segment register, it accepts no interrupt until the next instruction completes. If MOV SP, … is written right after MOV SS, AX, the two instructions run uninterrupted. Even so, the CLI/STI pair shows the intent clearly. Keeping interrupts off for a long time is harmful: keystrokes can be lost and the clock can fall behind. The code between CLI and STI is kept as short as possible.
When the processor accepts an interrupt it makes IF 0 itself; so the ISR is not immediately interrupted by a new interrupt of the same kind. The IRET at the end of the routine restores the old FLAGS from the stack, and IF returns to its old value, that is, 1.
2.2.7.4TF: the trap flag
The trap flag (TF) was put in for on-chip debugging. When TF = 1 the processor works in single-step mode: after each instruction finishes, it automatically raises a type 1 interrupt (INT 1) (Figure 2.2.15).
The flow is as follows. The program executes an instruction. Because TF = 1, the processor pushes FLAGS, CS, and IP onto the stack, clears TF and IF, and jumps to the routine the type 1 interrupt vector points to. This routine is part of a debugger: it prints the registers on the screen and waits for the user to press a key. While the routine runs, TF = 0, so it is not itself single-stepped. The IRET at the end takes FLAGS from the stack; TF becomes 1 again and the program’s next instruction is executed. Then the cycle repeats. The T (trace) command in DOS’s DEBUG program and emu8086’s “single step” button use this arrangement.
There is no instruction that sets or clears TF directly. There are STC/CLC for CF, STD/CLD for DF, and STI/CLI for IF; for TF there is none. TF is set by changing the whole flags register through the stack. TF is bit 8 of the flags register and its mask is 0100h; the step-by-step trace of the method is in Table 2.2.26.
| Flag | Bit | When 1 | When 0 | Instructions that set/clear |
|---|---|---|---|---|
| DF | 10 | string addresses decrease | string addresses increase | STD / CLD |
| IF | 9 | INTR interrupts are accepted | INTR interrupts are masked | STI / CLI |
| TF | 8 | INT 1 after every instruction | normal operation | none; use PUSHF/POPF |
2.2.8Instructions that change the flags
2.2.8.1The effect of instructions on the flags
The flags change in two ways: some instructions set or clear them directly, while arithmetic and logic instructions update them as a side effect. Table 2.2.22 gives the direct instructions.
| Instruction | Effect | Instruction | Effect |
|---|---|---|---|
CLC | CF = 0 | CLD | DF = 0 |
STC | CF = 1 | STD | DF = 1 |
CMC | CF = ¬CF | CLI / STI | IF = 0 / 1 |
LAHF | AH ← SF ZF – AF – PF – CF | SAHF | AH → low flags byte |
PUSHF | push FLAGS onto the stack | POPF | load FLAGS from the stack |
The effect of instruction groups on the status flags is collected in Table 2.2.23. The table helps find which instruction last changed the flags before a conditional jump.
| Instruction group | Effect on the flags |
|---|---|
| ADD, ADC, SUB, SBB, CMP, NEG | all of CF, PF, AF, ZF, SF, OF are updated |
| INC, DEC | all except CF are updated |
| AND, OR, XOR, TEST | CF = OF = 0; PF, ZF, SF are updated; AF undefined |
| MUL, IMUL | CF = OF = whether the high half of the result is significant; SF, ZF, AF, PF undefined |
| DIV, IDIV | all six status flags undefined |
| SHL, SHR, SAR | CF = the last bit shifted out; PF, ZF, SF are updated |
| ROL, ROR, RCL, RCR | only CF and OF change |
| MOV, PUSH, POP, XCHG, LEA, LOOP, JMP, Jcc | do not affect the flags |
The word “undefined” means that Intel has not documented the value of the flag after that instruction. The real processor leaves some value, but this value can vary with the processor model. A correct program does not look at an undefined flag. Another subtle point is TEST and CMP: both compute like AND and SUB but do not write the result, only set the flags. For example, TEST AL, 80h tests bit 7 of AL. With AL = B5h the result is 80h, giving ZF = 0 and SF = 1; AL does not change.
2.2.8.2Code trace: LAHF, SAHF, and CMC
LAHF (load AH from flags) copies the low byte of the flags register into AH. SAHF (store AH into flags) works in the opposite direction: it writes AH into the low byte of the flags register. The layout of the low byte is as follows:
| Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Flag | SF | ZF | – | AF | – | PF | – | CF |
| Value | SF | ZF | 0 | AF | 0 | PF | 1 | CF |
Bit 1 always reads as 1 on the 8086; bits 3 and 5 are 0. Because OF, DF, IF, and TF are in the high byte, LAHF and SAHF cannot reach them. The program in the slides traces these two instructions together with three instructions that change CF:
org 100h
mov al, 0FFh
add al, 1 ; CF ZF AF PF = 1
lahf ; AH ← flags
cmc ; flip CF
clc ; CF = 0
stc ; CF = 1
mov ah, 0C1h ; 1100 0001b
sahf ; flags ← AH
ret| Row | Instruction | AH | SF | ZF | AF | PF | CF |
|---|---|---|---|---|---|---|---|
| 2 | mov al, 0FFh | 00h | 0 | 0 | 0 | 0 | 0 |
| 3 | add al, 1 | 00h | 0 | 1 | 1 | 1 | 1 |
| 4 | lahf | 57h | 0 | 1 | 1 | 1 | 1 |
| 5 | cmc | 57h | 0 | 1 | 1 | 1 | 0 |
| 6 | clc | 57h | 0 | 1 | 1 | 1 | 0 |
| 7 | stc | 57h | 0 | 1 | 1 | 1 | 1 |
| 8 | mov ah, 0C1h | C1h | 0 | 1 | 1 | 1 | 1 |
| 9 | sahf | C1h | 1 | 1 | 0 | 0 | 1 |
In the third row FFh + 1 = 00h is computed. Four flags are set at once: the result did not fit in 8 bits (CF = 1), the result is zero (ZF = 1), the low nibble F + 1 overflowed (AF = 1), and 00h has zero 1s and zero is even (PF = 1). SF = 0, because the MSB of 00h is 0.
In the fourth row LAHF copies this state to AH. Written from left to right the bits are SF = 0, ZF = 1, 0, AF = 1, 0, PF = 1, 1, CF = 1: 0101 0111b = 57h (Figure 2.2.16). If the fixed 1 of bit 1 is forgotten, 55h is found; this is a common calculation mistake.
lahf. AH = 57h = 0101 0111b; bit 1 is always 1.In the fifth row CMC flips CF from 1 to 0. The CLC in the sixth row makes CF 0; since CF is already 0, there is no visible change. In the seventh row STC makes CF 1. These three instructions touch only CF; the table shows clearly that ZF, AF, and PF do not change. These instructions are used, for example, when a routine reports success or failure with CF, and to prepare the carry at the start of an ADC/SBB chain.
The eighth row writes C1h = 1100 0001b to AH. If this bit pattern is read in the layout of the flags byte, bit 7 (SF), bit 6 (ZF), and bit 0 (CF) are 1; AF (bit 4) and PF (bit 2) are 0. In the ninth row SAHF writes this byte into the flags: SF = 1, ZF = 1, CF = 1, AF = 0, PF = 0 (Figure 2.2.17). SF and ZF both being 1 is a situation a normal operation cannot produce: a result cannot be both zero and negative. SAHF brings the flags to the desired value independently of any result. OF, DF, IF, and TF are not affected by this instruction.
sahf: AH = C1h has been written into the flags byte; SF = ZF = CF = 1, AF = PF = 0.After MOV AL, 5, CMP AL, 5, and LAHF, what is AH?
CMP computes 5 − 5 = 0: ZF = 1; since the result is 00h, PF = 1; since there is no borrow, CF = 0; since there is no nibble borrow, AF = 0; since the MSB is 0, SF = 0. The flags byte SF ZF 0 AF 0 PF 1 CF = 0 1 0 0 0 1 1 0 = 0100 0110b = 46h.
2.2.8.3All the flags with PUSHF and POPF
LAHF and SAHF reach only the low byte. All 16 bits of the flags register are pushed onto the stack with PUSHF and taken back from the stack with POPF. Between the two instructions the word on the stack can be taken into a register and the desired bit changed. This is the only way to set TF, which has no direct instruction. The following program shows the same method on DF; DF is bit 10 and its mask is 0400h.
PUSHF ; FLAGS → stack
POP AX ; AX = FLAGS
OR AX, 0400h ; bit 10 (DF) ← 1
PUSH AX
POPF ; FLAGS ← AX
PUSHF ; check:
POP BX ; BX = new FLAGS| Instruction | AX | BX | SP | DF | Top of the stack |
|---|---|---|---|---|---|
PUSHF | 0000h | 0000h | FFFCh | 0 | F202h |
POP AX | F202h | 0000h | FFFEh | 0 | 0000h |
OR AX, 0400h | F602h | 0000h | FFFEh | 0 | 0000h |
PUSH AX | F602h | 0000h | FFFCh | 0 | F602h |
POPF | F602h | 0000h | FFFEh | 1 | 0000h |
PUSHF | F602h | 0000h | FFFCh | 1 | F602h |
POP BX | F602h | F602h | FFFEh | 1 | 0000h |
At the start IF = 1 and the other flags are 0. The word PUSHF pushes is F202h. Its breakdown is instructive: the F000h part is bits 12–15, which always read as 1 on the 8086; 0200h is bit 9, that is, IF = 1; 0002h is bit 1 and is always 1. OR AX, 0400h sets only bit 10 to 1 and keeps the other bits: F602h. POPF loads this value into the flags register and DF = 1. The last two rows are the check: when the flags are read again, BX = F602h.
For TF the same code is written with OR AX, 0100h. To clear a bit, AND with an inverted mask is used instead of OR: AND AX, 0FEFFh clears TF and AND AX, 0FBFFh clears DF. One benefit of working through the stack is that it preserves the other flags. When the change is finished, SP returns to the value it had at entry; the numbers of PUSHes and POPs are equal.
Another use of PUSHF/POPF is saving the flags across a routine. If a routine does PUSHF at its start and POPF at its end, the caller’s flags are not disturbed, whatever arithmetic is done inside. Interrupts work on the same principle: the processor pushes FLAGS onto the stack on entering an interrupt, and IRET takes it back.
2.2.9Common mistakes
The assembler cannot catch most mistakes about registers and flags; the program runs but gives a wrong result. The following mistakes are the most common in beginners’ programs.
Thinking the carry of an 8-bit operation passes to the neighboring half. With AX = 12FFh, ADD AL, 1 gives 1200h, not 1300h. The carry of an 8-bit operation goes to CF. If the carry is to be passed to AH, ADC AH, 0 is written next, or the operation is done on 16 bits from the start.
Forgetting the square brackets or putting them in unnecessarily. MOV AX, BX copies the value of BX; MOV AX, [BX] reads the memory word BX points to. MOV SI, [array] loads into SI not the address of the array but its first word; for the address MOV SI, OFFSET array or LEA SI, array is written.
Not accounting for implicit operands. Changing CL for SHL AX, CL inside a loop while CX is the loop counter, or using a 16-bit MUL or DIV while keeping a value in DX. Which registers instructions silently change is collected in Table 2.2.3; a conflicting register is pushed onto the stack and popped back afterward.
Not clearing DX before DIV. To divide a 16-bit number in AX by BX, if only DIV BX is written, the dividend is DX:AX. If DX holds a leftover value from a previous operation, the quotient may not fit in 16 bits and the processor raises a divide-error interrupt. Before an unsigned division MOV DX, 0 is written, and before a signed one CWD.
Thinking MOV changes the flags. Writing MOV AX, 0 and then JZ does not test whether AX is zero; JZ looks at the ZF of the last arithmetic operation before the MOV. Whether a register is zero is tested with CMP AX, 0, TEST AX, AX, or OR AX, AX.
Confusing CF and OF. Testing overflow with OF in a program that works with unsigned numbers, or with CF in one that works with signed numbers. In 7Fh + 01h, CF = 0 but the signed result is wrong; in FFh + 01h, CF = 1 but the signed result is correct.
Forgetting bit 1 in the LAHF byte calculation. In the byte LAHF produces, bit 1 is always 1. With the flags SF = 0, ZF = 1, AF = 1, PF = 1, CF = 1, AH = 57h, not 55h.
Writing a constant to a segment register or confusing the segment with BP. MOV DS, @data cannot be written; it is taken into AX first. An access [BP+SI] is made in SS, not DS.
2.2.10Exercises and solutions
The five exercises in the slides are solved here with their intermediate steps. The results can be checked by running them in emu8086.
1. With AX = 3A7Fh, what is AX after MOV AL, 0 and then INC AH?
MOV AL, 0 changes only the low byte: AH = 3Ah stays, AL = 00h, and AX = 3A00h. INC AH increments only the high byte: 3Ah + 1 = 3Bh. The result is AX = 3B00h. Neither instruction touches the other half.
2. Find AL, CF, ZF, SF, OF, and PF after MOV AL, 9Ch / ADD AL, 64h.
First the binary addition: 1001 1100 + 0110 0100 = 1 0000 0000. The result is 100h; the low byte 00h is written to AL and the overflowing 1 goes to CF: CF = 1. Since the result is zero, ZF = 1, and since the MSB is 0, SF = 0. In the signed interpretation 9Ch = −100 and 64h = +100; −100 + 100 = 0 is correct, and the sum of two numbers of different signs does not overflow: OF = 0. 00h has zero 1s, an even number: PF = 1. The low nibbles are C + 4 = 16; a carry comes out of bit 3: AF = 1.
3. MOV AL, 50h / ADD AL, 50h: what are CF and OF? Why do they differ?
50h + 50h = A0h. In the unsigned interpretation 80 + 80 = 160, which is less than 255; the result fits in 8 bits: CF = 0. In the signed interpretation two positive numbers, +80 and +80, were added; +160 exceeds the upper limit of the signed range, +127. Because the MSB of A0h is 1, the result looks like −96. The sum of two positives came out negative: OF = 1 (SF is 1 too). The two flags are answers to different questions: CF reports unsigned overflow and OF signed overflow.
4. What is SP after 3 PUSHes and 1 POP when SP = 0100h?
Each PUSH subtracts 2 from SP and each POP adds 2: 0100h − 3 × 2 + 2 = 0100h − 6 + 2 = 0100h − 4 = 00FCh. The intermediate values are 00FEh, 00FCh, 00FAh, and after the POP 00FCh. Two items remain on the stack.
5. How many times does a LOOP loop that starts with MOV CX, 0 run?
LOOP decrements first and then tests. The first LOOP computes 0 − 1 = FFFFh and jumps. As CX goes down from FFFFh to 1 the loop runs 65,535 more times; with the first pass it runs 65,536 times in total. If the pass count is counted in the 32-bit pair DX:BX, 0001:0000h = 65,536 results. To prevent this case, JCXZ is put before the loop.
2.2.11Summary
- A register is a very fast, small memory cell inside the processor. A register access does not go out on the external bus; a memory access takes a bus cycle of at least four clock cycles. On the 8086 there is no memory-to-memory MOV or ADD.
- The 8086 has 14 registers: 4 data registers (AX, BX, CX, DX), 4 pointer and index registers (SP, BP, SI, DI), 4 segment registers (CS, DS, SS, ES), IP, and FLAGS. All are 16 bits; only AX, BX, CX, and DX are split into two 8-bit halves. Writing to one half does not change the other, and the carry of an 8-bit operation goes to CF, not to the neighboring half.
- Some instructions use registers implicitly: MUL/DIV → AX and DX; LOOP/REP → CX; shift count → CL; IN/OUT → AL/AX and, for ports above 255, DX; PUSH/POP/CALL/RET → SP; string instructions → DS:SI and ES:DI.
- Inside square brackets only BX, BP, SI, and DI can be used. Addresses that contain BP use SS, the others use DS.
- SP points to the top of the stack. PUSH first decrements SP by 2 and then writes; POP first reads and then increments SP by 2. BP, staying fixed throughout a procedure, allows parameters to be reached at fixed distances such as
[BP+4]. - A constant cannot be loaded into a segment register, and CS cannot be written with MOV. Physical address = segment × 10h + offset. IP is the offset of the next instruction; it advances by the instruction length and cannot be written with MOV.
- 9 bits of the flags register are used. Status flags: CF (unsigned overflow, borrow), PF (an even number of 1s in the low byte), AF (carry from bit 3 to bit 4), ZF (the result is zero), SF (the MSB of the result), OF (signed overflow). Control flags: DF (string direction), IF (permission for INTR interrupts), TF (single step).
- In hardware CF is the last carry, ZF is a NOR gate, SF is a copy of the MSB, PF is the inverse of an XOR tree, and OF is the XOR of the carries into and out of the MSB.
- CLC/STC/CMC change CF, CLD/STD change DF, and CLI/STI change IF. LAHF copies the low byte of the flags into AH, SAHF writes AH to this byte; PUSHF/POPF move the whole flags register to and from the stack. TF can be changed only with PUSHF/POPF.
- MOV, PUSH, POP, XCHG, LEA, LOOP, and the jump instructions do not affect the flags; INC and DEC do not touch CF; after MUL and DIV some flags are undefined.
2.2.12Key terms
- register
- register set
- general-purpose register
- accumulator
- base register
- counter register
- high / low byte
- implicit operand
- pointer register
- stack pointer (SP)
- base pointer (BP)
- index register
- source / destination index (DI)
- stack
- stack frame
- segment register
- offset
- physical address
- default segment
- instruction pointer (IP)
- flag
- flags register (FLAGS)
- status flag
- control flag
- carry flag (CF)
- parity flag (PF)
- auxiliary carry flag (AF)
- zero flag (ZF)
- sign flag (SF)
- overflow flag (OF)
- direction flag (DF)
- interrupt flag (IF)
- trap flag (TF)
- single-step
- maskable / non-maskable interrupt
- string instruction
2.2.13Test Yourself
INC BLexecutes with BX = 12FFh and CF = 1. What do BX, ZF, and CF become?Answer
INC works on the 8-bit BL: FFh + 1 = 00h, BH does not change, and BX = 1200h. Because the result is zero, ZF = 1. Because INC does not touch CF, CF stays 1; the reason it is 1 is not this INC but the earlier state.
MOV AL, 0F0h,ADD AL, 10h, andADC AH, 0execute with AX = 0000h. What are AX and CF?Answer
F0h + 10h = 100h: AL = 00h, CF = 1. ADC adds CF together with 0 to AH: AH = 00h + 0 + 1 = 01h. AX = 0100h. Because ADC’s own addition produces no carry, CF = 0 in the end. Together the two instructions have done a 16-bit addition by carrying the 8-bit carry into the upper byte.
At the start of a .COM program (SP = FFFEh),
PUSH AXexecutes with AX = ABCDh. What does SP become, and which byte is written to which address?Answer
PUSH first decrements SP by 2: SP = FFFCh. The word is written low byte first: SS:FFFCh ← CDh, SS:FFFDh ← ABh. The word 0000h at FFFEh stays in place.
Is there a difference between
XOR AX, AXandMOV AX, 0as far as AX is concerned? What is the difference as far as the flags are concerned?Answer
Both give AX = 0000h. XOR sets the flags according to the result: ZF = 1, PF = 1, SF = 0, CF = OF = 0 (AF undefined). MOV changes no flag; the flags left from the previous operation are preserved. XOR is also 2 bytes, while
MOV AX, 0is 3 bytes.After
MOV AX, 0FFFFh,MOV BX, 0002h,MUL BX, what are DX, AX, CF, and OF?Answer
FFFFh × 2 = 1FFFEh (65,535 × 2 = 131,070). The 32-bit result is 0001FFFEh: DX = 0001h, AX = FFFEh. Because the high half is not zero, CF = OF = 1. SF, ZF, AF, and PF are undefined.
What are CF and OF in the 8-bit operations
80h − 01hand7Fh − FFh?Answer
80h − 01h = 7Fh. Unsigned 128 − 1 = 127 is correct, no borrow: CF = 0. Signed −128 − 1 = −129 does not fit; the result came out +127: OF = 1. 7Fh − FFh = 80h. Unsigned 127 − 255 is negative, a borrow is taken: CF = 1. Signed +127 − (−1) = +128 does not fit: OF = 1.
With DF = 1 and SI = 0205h, if addresses 0204h and 0205h hold 11h and 22h, what are AL and SI after two
LODSBs?Answer
The first LODSB takes the 22h at DS:0205h into AL, and SI = 0204h. The second LODSB takes the 11h at 0204h, and SI = 0203h. The result is AL = 11h, SI = 0203h.
MOV AL, 7Fhand thenINC AL: what do AL, SF, OF, and CF become?Answer
AL = 80h. Because the MSB is 1, SF = 1. +127 + 1 = +128 does not fit in the signed range: OF = 1. INC does not change CF; CF keeps its previous value (0 in this program).
Why are interrupts turned off automatically at the start of an interrupt service routine? Is NMI blocked during this time too?
Answer
When accepting an interrupt, the processor pushes FLAGS onto the stack and then clears IF and TF. Because IF = 0, new requests coming from INTR cannot interrupt the routine right away; if it wants, the routine turns interrupts on with STI. IRET restores the old FLAGS. Because NMI is not affected by IF, it is accepted during this time too.
2.2.14Further reading
- Intel, The 8086 Family User's Manual (1979), Chapter 2: the register model, the full definition of the flags, and the clock-cycle count of every instruction are in this source; the values in Table 2.2.1 are taken from here.
- B. B. Brey, The Intel Microprocessors (8th edition), Chapters 2 and 3: the programming model, addressing modes, and default segments, along with the extension from the 8086 to the current x86.
- M. A. Mazidi, J. G. Mazidi, The x86 PC: Assembly Language, Design, and Interfacing (5th edition), Chapter 1: registers, the flags register, and many examples in which the flags are computed by hand.
- M. Morris Mano, Digital Design: the gate-level design of adders, parity generators, and registers; for the digital-design basis of the flag circuits.
2.2.15References
- Intel, The 8086 Family User's Manual, 1979.
- Barry B. Brey, The Intel Microprocessors, 8th edition, Pearson, 2009.
- Muhammad Ali Mazidi, Janice G. Mazidi, The x86 PC: Assembly Language, Design, and Interfacing, 5th edition, 2010.
- emu8086 documentation: the 8086 instructions and Addressing modes sections.
- Mehmet Bodur, Mikroişlemcilere Giriş: Assembler ile Yazılım ve Arayüz.
Related pages: Chapter 2.2 slides · © Sercan Külcü. All rights reserved.