Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 67 ยท Instruction Set Architecture

Assembly Language Basics

Learn assembly language: mnemonics, labels, directives and pseudo-instructions, then write programs for a small teaching ISA and build a two-pass assembler in Python.

Machine code is just numbers, and nobody wants to write 0x2890 when they mean "load the array element". Assembly language is a thin, human-readable layer over machine code. Each line stands for (usually) one machine instruction, written with a short name called a mnemonic, and with names for registers and memory locations instead of numbers. A program called an assembler translates it into the binary the processor runs.

Assembly matters even if you never write much of it. Reading it shows you what your compiler produced, how function calls really work, and what a "simple" line of C costs. In this lesson you will learn the pieces of the language, write programs for our TC16 teaching ISA from the last few lessons, and build a working assembler and simulator in Python.

From source to machine code

flowchart LR
  S["Assembly source<br/>.asm text"] --> A["Assembler"]
  A --> M["Machine code<br/>numbers in memory"]
  M --> C["CPU<br/>fetch, decode, execute"]

The assembler is a translator; the CPU only ever sees the numbers.

The key difference between assembly and a high-level language is the one-to-one nature of the translation. A C compiler decides how to implement your for loop; an assembler does exactly what you wrote, instruction for instruction. Because each ISA has its own instructions, assembly language is specific to one processor family, unlike C, which can be compiled for all of them.

Anatomy of a line

An assembly line has up to four parts, all optional except that it must have something:

TEXT
loop:   lw   r4, arr(r2)    ; r4 = arr[i]
  • A label (loop:) names the address of this line. You can then refer to it from a jump or a branch instead of counting words by hand.
  • A mnemonic (lw) names the operation.
  • Operands (r4, arr(r2)) are registers, constants, labels or memory expressions such as offset(register).
  • A comment starts at a semicolon (;) in our syntax and runs to the end of the line. Other assemblers use #, // or @. Good assembly programs have a comment on nearly every line, because the code itself explains so little.

Labels also name data. If you place a label in front of a data word, its value is the address of that word, which is how arr(r2) above works: arr is the address of the array and r2 holds the index, the base-plus-offset mode from Addressing Modes.

The TC16 instruction set in assembly

You met the encodings in Instruction Formats and Encoding. In assembly, the instructions look like this:

Instruction Meaning
add rd, rs, rt rd = rs + rt
sub rd, rs, rt rd = rs - rt
and, or, xor rd, rs, rt bitwise operations
slt rd, rs, rt rd = 1 if rs < rt (signed), else 0
sll, srl rd, rs, rt shift rs left/right by the value in rt
addi rd, rs, imm rd = rs + imm (imm from -32 to 31)
lw rt, off(rs) rt = memory[rs + off]
sw rt, off(rs) memory[rs + off] = rt
beq ra, rb, label if ra == rb, jump to label
bne ra, rb, label if ra != rb, jump to label
j label jump to label
halt stop the machine

Remember that r0 always reads as zero and ignores writes. This one fixed register gives you several handy idioms for free.

Pseudo-instructions

A pseudo-instruction is a convenience that the assembler expands into a real instruction. Our assembler supports three:

You write Assembler emits Why it works
li rd, 5 addi rd, r0, 5 r0 is zero, so 0 + 5 = 5
mov rd, rs addi rd, rs, 0 adding zero copies the value
nop add r0, r0, r0 (the word 0) writes to r0 are ignored

Real assemblers have many: MIPS has li and la, RISC-V has li, mv, ret and j. They make the code easier to read at no cost in hardware.

Directives

A directive is an instruction to the assembler, not the CPU. It produces no instruction (though it may produce data). TC16 has two:

  • .org address sets the address where the following lines are placed.
  • .word v1, v2, ... reserves memory words holding the given values.

Real assemblers add many more, such as sections (.text, .data), strings (.ascii), alignment and constants.

A first program

Here is a TC16 program that sums an array of five numbers. It uses a loop, a label, a base-plus-offset load, a branch and a store.

TEXT
        li   r1, 0          ; sum = 0
        li   r2, 0          ; i = 0
        li   r3, 5          ; n = 5
loop:   beq  r2, r3, done   ; stop when i == n
        lw   r4, arr(r2)    ; r4 = arr[i]
        add  r1, r1, r4     ; sum += r4
        addi r2, r2, 1      ; i++
        j    loop
done:   sw   r1, result(r0) ; store the answer
        halt
        .org 16
arr:    .word 3, 1, 4, 1, 5
result: .word 0

Read it like a C program: sum = 0; for (i = 0; i != 5; i++) sum += arr[i]; result = sum;. The data lives at addresses 16 and up because a lw immediate can only hold values up to 31, so the label arr has to be a small number. The assembler checks this for you and complains if an address does not fit, a limit you saw when we discussed the 6-bit immediate.

How an assembler works: two passes

The assembler has to turn labels into numbers, and that causes a classic problem: when it reaches beq r2, r3, done, it has not yet seen the line labelled done. The standard fix is two passes over the source.

  1. Pass 1 reads every line, strips comments, and keeps a running location counter. Whenever it sees a label, it records the current address in a symbol table. Directives like .org change the counter, .word advances it, and each instruction advances it by one word.
  2. Pass 2 goes through the recorded lines again and encodes each instruction, looking up labels in the symbol table. For a branch it computes the PC-relative offset target - (address + 1).

The first TryIt performs only pass 1 on a tiny program, so you can see the addresses and the symbol table.

Python Assembler pass 1: addresses and the symbol table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The gap between address 3 and address 8 is the effect of .org 8. Labels table and end get the addresses 8 and 11, and loop gets 1: it labels the second line, because the first line (li) took address 0.

A complete assembler and simulator

Now the whole thing. The code below has three parts: assemble (both passes, producing a dictionary from address to machine word), run (a TC16 simulator that does fetch, decode and execute until halt), and two programs. The simulator uses 16-bit registers, ignores writes to r0, and treats slt as a signed comparison. It also shows the assembler's error messages for typical mistakes.

Python Assemble and run TC16 programs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The sum program assembles to ten words and computes 14 (3 + 1 + 4 + 1 + 5) in 31 executed instructions; the Fibonacci program leaves 55 in memory after 66. Look at the first line of machine code, 1200 1400 1605 44C4 ..., and compare it with the source. 1200 is li r1, 0 (an addi with opcode 1, ra = 1), and 44C4 is the beq, whose low six bits 000100 hold the offset 4, since done is four words past the instruction after the branch. Counting instructions is the first step toward the performance equations of Measuring Performance: the same loop of five instructions executed five times accounts for most of the 31.

When an assembly program misbehaves, check the three usual suspects: an off-by-one in a loop condition, a label pointing at the wrong line, and a value that does not fit its immediate field. The error messages above are the assembler's way of catching the last one early.

Macros, assembling and linking

Real assemblers offer more than a one-to-one translation. A macro is a named template: wherever the name appears, the assembler pastes the body and substitutes the arguments before translating, so a macro call costs no CALL or RET at run time (unlike a subroutine, it is copied every time it is used). In NASM-style syntax a macro is written between %macro and %endmacro, and its operands are called %1, %2 and so on.

Python Expanding macros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

To run an assembly program on a real machine you go through three steps. The assembler translates each source file into an object file with machine code, a symbol table and notes on addresses still to be fixed. The linker combines object files and libraries, resolves the references between them and assigns final addresses. The operating system's loader then copies the executable into memory and starts it at the entry point.

Assembly language also has a history that mirrors the machines. Programmers in the 1940s entered machine code in binary, directly (first generation). In the 1950s assemblers introduced mnemonics and labels so programs could be written symbolically (second generation: assembly language). High-level languages such as Fortran and COBOL followed in the 1960s (third), and the 1970s to 1980s added structured and database-oriented languages (fourth). Languages that describe goals or constraints, and modern tools that generate code, are loosely called fifth generation. Assembly remains the closest layer to the hardware; its drawbacks are that it is tied to one processor family, long, error-prone and hard to maintain.

Why learn assembly at all?

  • Understand costs. You see that an array access needs an address calculation and a load, and that a loop has a branch on every iteration.
  • Read compiler output. Tools like compiler explorers and debuggers show assembly, and performance work often means checking what the compiler did.
  • Debugging and security. Crash dumps, reverse engineering and exploit analysis all happen at this level.
  • Embedded and systems work. Boot code, interrupt handlers and tiny microcontrollers still use it.

Assembly stays close to the machine, but it is no longer how most software is written. The branch, loop and function-call patterns you will meet in Assembly: Branches, Loops and Functions are the same ones compilers generate for if statements, loops and calls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an assembler do?

    Each assembly line corresponds to (usually) one machine instruction, and the assembler produces the binary patterns for them.
  2. 2. Why does an assembler need two passes?

    Pass 1 collects the address of every label into a symbol table, and pass 2 encodes instructions using those addresses.
  3. 3. Which of these is a directive rather than an instruction?

    A directive such as .word tells the assembler what to place in memory. The CPU does not execute it.
  4. 4. What does the pseudo-instruction li r2, 7 become in TC16?

    Register r0 always holds zero, so adding 7 to it loads the constant 7 into r2.
  5. 5. A TC16 branch at address 3 targets the label done at address 8. What offset does the assembler store?

    The offset is relative to the next instruction: 8 - (3 + 1) = 4.

Summary

  • Assembly language is a readable form of machine code: mnemonics for operations, names for registers, labels for addresses, and comments.
  • An assembler translates it, mostly one line to one instruction. Pseudo-instructions like li, mov and nop expand to real instructions; directives like .org and .word control placement and data.
  • A two-pass design resolves labels: pass 1 builds the symbol table, pass 2 encodes instructions, computing PC-relative branch offsets.
  • TC16 programs use r0 as a constant zero, base-plus-offset loads for arrays, and compare-and-branch for loops.
  • Assembly shows exactly what the machine does, which helps with performance, debugging and understanding compilers.

Continue with Assembly: Branches, Loops and Functions.