An instruction-set architecture (ISA) is the stable contract presented by a processor to software. It specifies the programmer-visible state, instruction semantics, encodings, addressing rules, memory-access behavior, privilege boundaries, and exceptional events.
A microarchitecture may execute instructions in one cycle, in a deep pipeline, out of order, or through translation into internal operations; as long as it preserves the ISA’s specified observations, it remains a valid implementation. This abstraction is what lets one binary run across generations of hardware and lets compilers target a machine without knowing its transistor-level organization.
The contract is narrower than “what the hardware happens to do.” Timing, cache size, branch-predictor state, and speculative execution are usually not architectural state, although they affect performance and can create side channels.
Conversely, the exact behavior of an unaligned access, an overflow flag, a memory ordering operation, or an illegal instruction is architectural if software can observe it. A rigorous ISA specification therefore separates functional semantics from implementation accidents and states what is guaranteed, permitted, or undefined.
Programmer-visible state
The architectural state commonly includes a program counter (PC), a register file, memory, status/control registers, and privileged state. A register file has a finite set of named registers with a defined width. Some ISAs reserve a register whose reads always produce zero; others expose a stack pointer, link register, condition-code register, or vector register bank. The PC identifies the next instruction according to the ISA’s fetch convention. It may advance by a fixed instruction width, by an instruction-length decoder, or by a branch/jump target.
An instruction is a state transition. If architectural state before execution is instruction bytes decode to operation and the memory system supplies the required values, then execution defines The notation hides important partiality: an access may be misaligned, a privilege check may fail, a page may be absent, or a divide may have an invalid operand. In those cases, the ISA specifies an exception transition rather than an ordinary result.
Worked example: load/store semantics. A RISC-style load word lw r1, 12(r2) computes an effective address checks alignment and access permission, reads four bytes according to the memory endianness, sign- or zero-extends the word as specified, writes it to r1, and advances the PC. A store computes the same kind of address but writes register data to memory and does not update a general-purpose destination. The assembler syntax is short; the architectural transition includes address arithmetic, width, alignment, permission, and exception behavior.
Locate the abstraction
Evaluate which elements belong strictly to the Instruction-Set Architecture (ISA) interface contract rather than a specific microarchitectural implementation:
Classify each option as correct or incorrect, or leave uncertain options unanswered (“I don't know”) and verify at any time.
RISC and CISC as design families
A load/store ISA restricts memory access to explicit load and store operations; arithmetic instructions operate on registers. This regularity simplifies decode, register allocation, pipeline staging, and formal reasoning. It may increase instruction count for operations that could be expressed as memory-to-memory work. A more instruction-rich ISA can encode complex addressing modes or multi-step operations, reducing code size at the cost of decoding and implementation complexity.
The labels RISC and CISC describe tendencies, not a complete classification. Modern “complex” ISAs may translate instructions into simple internal operations, while a RISC ISA can contain vector, atomic, compressed, or privileged instructions with substantial semantics. The useful question is what software-visible contract is exposed and what implementation freedom it preserves.
Instruction length presents a trade-off. Fixed-width encodings simplify fetch alignment and parallel decode but may waste bits for small operations. Variable-length encodings improve code density but make instruction boundaries and branch targets harder to locate. Compressed encodings add a second width while preserving a common register or operation subset. Code density affects instruction-cache pressure, so encoding is a performance design choice as well as a compiler-interface choice.
Architectural state defines the instruction
Two implementations execute an ADD instruction differently internally. Both read the same operands, update the destination register, advance the PC, and raise identical exceptions.
Evaluate what establishes these two different processor designs as valid implementations of the same ISA operation:
Encoding and decoding
An instruction encoding partitions bits into fields: opcode, register identifiers, immediate values, function modifiers, and sometimes mode or rounding controls. Field widths constrain the number of registers and immediate range. If a register file has entries, a register identifier needs bits. An immediate may be sign-extended from a compact field; its range and alignment may be more important than its raw width.
Worked example: PC-relative branch. Suppose a branch encodes a signed -bit displacement in instruction units of four bytes. The signed displacement range is units, and the byte target is if the architecture defines the PC as the current instruction address. A compiler cannot assume that every label is reachable; the assembler or linker must synthesize a longer branch sequence when the displacement does not fit. Misunderstanding whether the base is current PC or next PC creates an off-by-one-instruction error that passes short tests and fails at range boundaries.
Immediate encoding also interacts with sign extension. An instruction that adds a signed 12-bit immediate must interpret 0xFFF as -1, not 4095. A separate unsigned-immediate instruction or zero-extension rule is needed when the latter is intended. The opcode’s semantic definition, not the bit pattern alone, determines the result.
Pause & Predict: The 12-Bit Immediate Sign-Extension Trap. Suppose you execute
addi a0, zero, 0x800on a 32-bit RISC-V processor whereaddiaccepts a 12-bit immediate fieldimm[11:0]. What 32-bit hexadecimal value is stored ina0? Is it0x00000800or0xFFFFF800Commit your reasoning before opening the analysis below.
Show hintExpandCollapse
Check bit 11 of 0x800 (0b1000_0000_0000). If the most significant bit of the 12-bit immediate is 1, what does arithmetic sign extension do to bits 31..12?
Reveal analysisExpandCollapse
Analysis:
The value stored is 0xFFFFF800
In standard RISC-V I-type instructions, the 12-bit immediate is strictly sign-extended to 32 bits.
The hex value 0x800 has bit 11 equal to 1 (0b1000_0000_0000).
The sign bit imm[11] is copied into all upper 20 bits:
imm[31:12] = 0b1111_1111_1111_1111_1111 (0xFFFFF).
Thus, the machine sign-extends 0x800 to 0xFFFFF800.
To load an unsigned or construct larger 32-bit values, one must use lui (Load Upper Immediate) combined with addi, carefully adjusting for the negative sign bit.
For a hypothetical 32-bit, fixed-width register-add ISA with modular arithmetic and no flags, the decoded fields select a precise state transition. This is a semantic map, not a claim about execution stages; the source operands are read from the pre-state even when a destination aliases a source.
Transfer check. Set rs1=5, rs2=6, rd=5, with initial R[5]=0xffffffff and R[6]=2. Determine the post-state and explain why destination/source aliasing does not change the operands.
Addressing modes and memory consistency
An addressing mode defines how an instruction derives an effective address: base plus offset, base plus index times scale, PC-relative, absolute, or indirect through a register. Addressing modes are conveniences expressed in the ISA; a microarchitecture may compute them in one adder or several internal steps. The mode must specify overflow behavior, alignment, privilege checks, and whether an address is computed before or after an update.
Worked example: effective address and instruction count. A RISC-V load lw x5, 12(x6) computes If x6 = 0x1000, then EA = 0x100c; alignment and permission are checked on that address before the four bytes are read. An indexed access to element i of an 8-byte array is not a single RISC-V addressing mode: with the index in a1 and the base in a0, a compiler emits slli t0, a1, 3, add t0, a0, t0, then ld x5, 0(t0). An x86-64 mov rax, [rbx + rcx*8] encodes the same base-plus-index arithmetic in one instruction. The trade is visible: the complex mode reduces instruction count but adds address-generation work and encoding constraints; the load/store ISA keeps the arithmetic explicit.
Memory is not an array of independent locations on a modern multiprocessor. The ISA specifies an ordering model for loads and stores. A sequentially consistent model places operations from all cores into one order consistent with each core’s program order. Weaker models permit certain reorderings and require explicit fences or atomic operations when synchronization depends on visibility order. A compiler and processor must jointly preserve the language-level memory model; a lock implemented with ordinary unordered loads and stores is not automatically a lock.
Falsifiable trace: store buffering. Two cores execute the following program, with x and y initially zero:
Core 0: Core 1:
store 1 -> x store 1 -> y
r0 <- load y r1 <- load x
Under sequential consistency, at least one load must observe 1: the alternative requires a cycle in the single total order, because each core’s store precedes its own load. Under x86-TSO and RISC-V’s weak ordering, the outcome r0 = 0 and r1 = 0 is permitted: each store may remain buffered while its core loads the other location. Observing (0,0) therefore falsifies a claim that the implementation is sequentially consistent, but it does not falsify x86-TSO or RVWMO. Adding mfence between the store and load on x86, fence rw, rw on RISC-V, or sequentially consistent atomics forbids the outcome. Release/acquire ordering forbids the message-passing variant—store data, release-store a flag, acquire-load the flag, load data—but it does not order a store followed by a load on the same core, so it does not by itself forbid this store-buffering outcome. A lock built from plain loads and stores without these constraints has no such guarantee.
An atomic read-modify-write instruction can guarantee that no competing core observes an intermediate state. Compare-and-swap typically reads a location, compares it with an expected value, and writes a replacement only if equal, returning success or failure. Its semantics must specify memory order, spurious failure if permitted, alignment, and exception behavior. Atomicity is about indivisibility at the specified granularity; it does not by itself prevent starvation, ABA problems, or incorrect higher-level invariants.
Procedure calls and ABI boundaries
The ISA supplies call, jump, and return primitives, but a usable software ecosystem also needs an application binary interface (ABI). The ABI assigns arguments and return values to registers or stack locations, classifies caller- and callee-saved registers, defines stack alignment, lays out aggregate values, and specifies symbol naming and object formats. A compiler-generated function and hand-written assembly interoperate only if both obey these conventions.
A call often saves a return address in a link register or stack, transfers control to a target, establishes a frame if needed, and returns through the saved address. Leaf functions may avoid a frame; recursive or reentrant functions cannot assume a single global copy of locals. The ABI’s preservation rule is an invariant across the call boundary: after the callee returns, every callee-saved register has the value the caller expects, while caller-saved registers may have changed.
Worked example: summing an array. Suppose arguments are a pointer p and length n, and the result is returned in r0. A correct loop needs a pointer, remaining count, and accumulator. Each iteration loads a word, adds it to the accumulator, advances the pointer by the element size, decrements the count, and branches while nonzero. The proof invariant is: after iterations, the accumulator is the sum of the first elements and p points to element The machine sequence is correct only if the load width, pointer increment, signedness of the loop comparison, and return convention all match the source-level contract.
Exceptions, traps, and privilege
An exception transfers control from ordinary instruction execution to a handler with architectural state saved according to the ISA. Synchronous exceptions arise from the current instruction—illegal opcode, page fault, arithmetic fault, or system call. Interrupts are asynchronous events such as a timer or device completion, though the architectural boundary may use a common entry mechanism.
Precise exceptions mean the machine state appears as if all older instructions completed and no younger instruction took effect. In an in-order implementation this is natural; an out-of-order implementation needs a reorder or retirement mechanism to preserve the illusion. The exception record must identify a restart PC or faulting instruction, cause code, privilege transition, and saved status. A handler that cannot determine whether to retry or skip an instruction cannot safely recover.
Worked trace: a load page fault and restart. User code executes lw a0, 0(s0) with PC = 0x4000_1000 and s0 = 0x0000_0000_dead_b000. The page-table walk finds no valid mapping. The hart records a synchronous exception with scause = 13 (load page fault), stval = 0xdead_b000, and sepc = 0x4000_1000; it copies the previous privilege (U) into sstatus.SPP, saves the interrupt-enable state in sstatus.SPIE, disables supervisor interrupts, and enters the handler at stvec. The destination a0 is not written: a precise exception leaves the register file as if the faulting instruction had not executed.
The handler allocates a page, installs a valid PTE, executes sfence.vma to discard stale translations on the handling hart, and executes sret. sret restores privilege from SPP, restores SIE from SPIE, and sets PC = sepc, so the load re-executes at 0x4000_1000 and now succeeds. Other harts that may have cached the old translation require a TLB shootdown. If the handler instead advanced sepc by four bytes, it would skip the load and silently leave a0 undefined; if the hardware partially wrote a0 before the fault was resolved, it would violate precise-exception semantics.
Privilege modes constrain access to memory, control registers, and devices. A system call deliberately enters a more privileged mode through a defined instruction; a page-protection violation enters it because an access violated a rule. The boundary is a security contract: user code should not be able to forge the saved privilege state, redirect the handler to an untrusted address, or retain access to privileged mappings after return.
Instruction semantics and compiler reasoning
Compilers transform programs by proving that the transformed program has equivalent permitted observations. If an ISA defines signed overflow as trapping, the compiler cannot replace a checked addition with modular addition. If overflow is undefined at the language level, the compiler may use that assumption to eliminate impossible branches—but only within the source language’s rules. If an ISA operation wraps but the language operation is checked, the compiler must insert a range check or use a widening instruction.
Worked example: reassociation is not a semantic identity. IEEE 754 addition is not associative, so these two source expressions have different values:
double left = (0.1 + 0.2) + 0.3; /* 0.6000000000000001 */
double right = 0.1 + (0.2 + 0.3); /* 0.6 */
A compiler may reassociate only when the language or an explicit fast-math mode permits it; otherwise the transformation changes the permitted observations. The same distinction separates the language from the ISA. C signed overflow is undefined behavior, so a compiler may fold x + 1 > x to true; with -fwrapv it must preserve wraparound. The ISA’s add instruction may wrap modulo the register width, but the compiler’s obligation comes from the source language. If the language operation is checked, the compiler must insert a range check or use a wider instruction rather than relying on the hardware’s wraparound.
Alias and alignment assumptions also affect legal transformations. A load can be hoisted above another operation only if the ISA and memory model permit the reordering and no aliasing or exception behavior changes. A vectorized load may require alignment or use a defined unaligned instruction. “The hardware usually handles it” is not an architectural proof.
Verification of an ISA implementation
An ISA simulator is an executable reference model, but a simulator bug can repeat the same misunderstanding as the hardware. Differential testing compares an implementation against a trusted model across random and directed programs. Directed tests target sign extension, branch boundaries, register-zero behavior, misalignment, privilege transitions, page faults, atomic races, and precise exception restart.
Worked example: directed tests and a random property. Differential testing is only as strong as the observations it compares. On RV64, the reference transition for addi x5, x0, imm is with x0 hardwired to zero and PC advancing by four. A test set that omits the sign bit passes a zero-extending bug.
| Stimulus | Reference observation | Bug it exposes |
|---|---|---|
addi x5, x0, 0x000 | x5 = 0 | wrong constant path |
addi x5, x0, 0x7ff | x5 = 2047 | truncation or off-by-one |
addi x5, x0, -2048 (immediate bits 0x800) | x5 = 0xffff_ffff_ffff_f800 | zero-extension instead of sign-extension |
addi x5, x0, -1 (immediate bits 0xfff) | x5 = -1 | failure to sign-extend |
addi x0, x0, 1 | x0 remains 0 | register-zero not hardwired |
addi x5, x0, imm for random 12-bit imm | x5 = sext(imm) | any mismatch in the decode path |
Random testing can exercise many additional encodings but does not guarantee all 4,096 cases are covered. Exhaustive enumeration of the 12-bit immediate field does; the directed cases explain why a mismatch matters. A simulator that agrees with the hardware on the same wrong interpretation is not a reference: differential testing needs an independently written model, or formal refinement against the ISA’s transition relation, before agreement is evidence.
Formal instruction proofs typically establish a refinement relation between microarchitectural state and architectural state. Internal pipeline registers, speculative values, and cache metadata are allowed to differ; at retirement, the visible state must match the reference transition. This relation explains why an implementation can execute instructions out of order while still satisfying a sequential ISA.
Counterexample & Failure Mode: The Unaligned Split-Access Trap & Atomicity Breakdown
Does an ISA’s memory access contract guarantee atomicity and fault isolation for arbitrary pointers?
Consider executing a 32-bit load lw x5, 0(x1) where x1 = 0x0FFF_FFFE.
-
Boundary Breakdown:
- The 4-byte word occupies addresses
[0x0FFF_FFFE, 0x0FFF_FFFF, 0x1000_0000, 0x1000_0001]. - These bytes straddle two distinct 4 KB virtual memory pages: Page 0 (
0x0FFF_F000) and Page 1 (0x1000_0000).
- The 4-byte word occupies addresses
-
Split Fault Failure Mode: Suppose Page 0 is resident in RAM with read permissions, but Page 1 is unmapped or paged out to disk.
- A naive microarchitecture that reads bytes 0 and 1 before translating Page 1 will encounter a Page Fault on the second half of the instruction!
- If the core partially wrote the destination register
x5with the first two bytes, the architectural state is corrupted prior to exception entry, violating precise exception semantics.
-
Multicore Atomicity Collapse: Even if both pages are resident, an unaligned access straddling a 64-byte cache line boundary cannot be fulfilled by a single L1 cache tag match. It requires two distinct bus/interconnect transactions.
- If another core executes a concurrent store to either cache line, it can interleave between the two halves.
- The load reads bytes 0-1 from before the store, and bytes 2-3 from after the store, observing a “torn read” word that never existed in memory.
- ISA Contract Guarantee: This is why strict RISC ISAs specify that misaligned accesses either raise an Address-Misaligned Trap or are explicitly non-atomic across cache boundaries.
Deep Practice
Solve these problems to test and consolidate your understanding. Complete worked solutions and diagnostic hints are available for each problem.
Exercise 2.1.1: Signed Load Architectural State Transition Specification
Specify the complete formal architectural state transition for a signed load instruction (e.g. lw rd, offset(rs1)), covering effective address arithmetic, privilege and alignment validation, byte endianness, sign extension into destination register rd, and precise exception handling.
HintExpandCollapse
Trace effective address generation, alignment verification, memory read, and sign extension into destination.
Worked solutionExpandCollapse
Compute effective address Verify user privilege level and that (for 32-bit aligned accesses). If misaligned or access-violating, suppress destination update and trigger an Address-Misaligned or Load-Access-Fault trap saving faulting in exception state. If valid, read 4 bytes starting at according to machine endianness, sign-extend the 32-bit word to register width, write to (if and advance
Exercise 2.1.2: Fixed-Width 32-Bit Instruction Encoding Layout
Design a 32-bit fixed-width encoding scheme supporting: (1) 16 three-register R-type operations; (2) 8 two-register I-type operations with a 12-bit signed immediate; and (3) 8 two-register B-type word-aligned conditional branches with a 12-bit signed displacement. Allocate explicit bitfields for opcode, registers, and immediates.
HintExpandCollapse
Allocate explicit bitfields for opcode, destination register, source registers, and immediate constants.
Worked solutionExpandCollapse
Use a 7-bit primary opcode field inst[6:0] to distinguish instruction classes. For R-type: rd[11:7] (5 bits), funct3[14:12] (3 bits), rs1[19:15] (5 bits), rs2[24:20] (5 bits), funct7[31:25] (7 bits). For I-type: rd[11:7], funct3[14:12], rs1[19:15], imm[31:20] (12 bits signed For B-type: funct3[14:12], rs1[19:15], rs2[24:20], with displacement bits split across inst[31], inst[7], inst[30:25], and inst[11:8] to encode a word-aligned branch offset.
Exercise 2.1.3: Assembly Loop Invariant Inductive Proof
Prove the partial correctness of an assembly array-sum loop using mathematical induction over loop iterations demonstrating that the accumulator satisfies at the loop header for arrays up to length
HintExpandCollapse
Induct on array index , showing that the accumulator equals at the loop header, and discuss modular integer overflow.
Worked solutionExpandCollapse
Base case Before entering the loop, the accumulator is cleared to 0 and the base pointer references the empty sum is 0, satisfying the invariant.
Inductive step: Assume at the start of iteration The loop body executes lw t0, 0(ptr), add acc, acc, t0, and addi ptr, ptr, 4. At the end of the iteration, When the branch condition terminates the loop, the accumulator contains under two’s-complement modular arithmetic
Exercise 2.1.4: Memory Consistency and Litmus Test Synchronization
In a multiprocessor system, thread 1 executes data = 42; flag = 1; while thread 2 executes while (flag == 0); r1 = data;. Verify why a weak memory model allows thread 2 to observe and insert the necessary ISA memory barrier instructions to guarantee sequentially consistent message passing.
HintExpandCollapse
Write a classic 2-thread message passing pattern (data write, flag set vs flag check, data read) and insert memory fences or acquire/release operations.
Worked solutionExpandCollapse
Under weak memory architectures (e.g. RISC-V or ARM), the hardware memory controller or out-of-order execution engine may reorder independent stores and or independent loads and If reaches cache before thread 2 sees but reads stale Inserting a release store (s-fence or fence w,w) on thread 1 and an acquire load (l-fence or fence r,r) on thread 2 forces visibility order.
Exercise 2.1.5: Precise Exception Constraints on Speculative Store Commits
Explain why an out-of-order processor cannot write speculative store results directly to the L1 data cache before an older floating-point divide instruction has completed without faulting.
HintExpandCollapse
Explain how committing a younger store to cache or memory before an older instruction's fault status is determined violates precise state.
Worked solutionExpandCollapse
Precise architectural exceptions require that when an exception occurs at instruction all instructions prior to have completely retired their state, and no instruction at or subsequent to has modified architectural registers or memory. If a younger store modifies cache before an older divide raises a divide-by-zero trap, persistent memory reflects side effects of instructions that should have been cancelled, destroying restartability and violating the ISA contract.
Exercise 2.1.6: Procedure Calling Convention and ABI Stack Frame Design
Specify an ABI calling convention for an 8-register processor architecture that must support recursive function calls and 16-byte stack alignment. Partition registers and draw the resulting stack frame layout.
HintExpandCollapse
Partition registers into argument, temporary (caller-saved), and preserved (callee-saved) sets, and allocate stack slots for spilled return addresses and frames.
Worked solutionExpandCollapse
Register allocation:
r0: Constant zero.r1: Return addressra(caller-saved by leaf, callee-saved across calls).r2: Stack pointersp.r3, r4: Arguments and return valuesa0, a1(caller-saved).r5: Temporaryt0(caller-saved).r6, r7: Saved registerss0, s1(callee-saved). Stack frame: Prologue decrementsspby 16 bytes, storingraat8(sp)ands0at0(sp). Epilogue restores both and incrementsspby 16 beforeret.
Exercise 2.1.7: Differential Testing of 12-Bit Immediate Sign Extension
Design a property-based differential test suite to verify that a hardware decoder and software emulator decode 12-bit signed immediates identically. Specify the boundary vectors and mathematical invariant property.
HintExpandCollapse
Construct test vectors covering positive maximum (), negative minimum (), zero, , and property-based mathematical equivalence.
Worked solutionExpandCollapse
Test vectors:
- Boundary values: (
0xFFF), (0x7FF, maximum positive), (0x800, minimum negative). - Bit-pattern isolates: single bit set at each position Property invariant: For all if decoded value must equal if decoded value must equal Assert that hardware RTL simulation and software instruction emulator yield identical extended 64-bit integers across all 4096 inputs.
References & Further Reading
- Patterson, D. A., & Hennessy, J. L. (2020). Computer Organization and Design: The Hardware/Software Interface (RISC-V Edition) (2nd ed.), Chapter 2 (“Instructions: Language of the Computer”). Morgan Kaufmann.
- Waterman, A., & Asanović, K. (Eds.). (2019). The RISC-V Instruction Set Manual, Volume I: User-Level ISA (Document Version 20191213). RISC-V International.
- Waterman, A., & Asanović, K. (Eds.). The RISC-V Instruction Set Manual, Volume II: Privileged Architecture. RISC-V International. https://github.com/riscv/riscv-isa-manual
- Weaver, D. L., & Germond, T. (1994). The SPARC Architecture Manual (Version 9). Prentice Hall.