19. Processor Architecture, MIPS Assembly, and Performance Optimization

Memory Architecture and the Stored-Program Concept

  • Memory Agnosticism:

    • Computer memory is fundamentally agnostic to the semantics of its stored contents.

    • Memory hardware makes no operational distinction between program instructions and data; all information is stored uniformly as arbitrary sequences of binary digits (bits: 00 and 11) organized into bytes.

  • The von Neumann Model and the Stored-Program Concept:

    • Under the von Neumann architecture, both executing programs and the data operated upon reside concurrently within the same physical memory space.

    • This structural paradigm is formally termed the stored-program concept.

  • Memory Layout and Content Varieties:

    • Machine Code (Binaries): Encoded as pure binary sequences (00s and 11s). This encompasses system tools and application binaries such as accounting software, text editors, and compilers.

    • Compilers: Translators such as GCC or g++ exist in memory purely as machine code binaries.

    • Application Data: Stored alongside code, such as payroll database records utilized by accounting programs or manuscript text manipulated by an editor.

    • Source Code: High-level source code (such as C programs) is initially stored as ASCII text files. Each character is mapped to an 8-bit8\text{-bit} (1-byte1\text{-byte}) binary pattern before eventual compilation into machine binary.

  • Programs Operating on Programs:

    • Programs can take other programs as their direct data inputs.

    • A compiler takes a high-level source code file as its input data and outputs a machine-readable binary file.

  • Linkers and Executable Generation:

    • Linkers are operating system utilities that integrate multiple distinct binary object files into a single, cohesive executable binary file (e.g., an .exe file).

    • In standard C programming, routines such as mathematical functions (sin⁡(x)\sin(x), cos⁡(x)\cos(x)) are not written from scratch; rather, header files like math.h are declared at the beginning of the source file.

    • The compiler translates the source file (e.g., myprogram.c) into a user binary, after which the linker merges that user binary with the pre-compiled binary code of the included standard runtime libraries.

Binary Compatibility and Instruction Set Architecture (ISA) Standardization

  • Definition of Binary Compatibility:

    • Binary compatibility is the property of an architecture that permits an executable binary program compiled for an earlier processor implementation to execute without modification or recompilation on subsequent processor models within the same architectural genre.

  • Examples across Processor Families:

    • Processors such as the MIPS architecture or Apple Silicon M-series chips (Apple M2, M3, M4, and M5) implement this principle.

    • A program compiled for an Apple M2 processor will execute directly on an Apple M5 processor, exhibiting backward compatibility.

  • Economic and Practical Rationales:

    • Customer Base Retention: Forcing users to repurchase or manually recompile software applications whenever hardware is upgraded risks alienating users.

    • Proprietary and Closed-Source Software: Commercial vendors (e.g., Microsoft with its Office suite) do not distribute source code to end users. If backward compatibility were broken, end users would be unable to recompile their software and would be forced to purchase vendor upgrades.

  • Architectural Trade-Offs and Performance Penalties:

    • Suboptimal Execution: Successive processor generations introduce architectural enhancements, optimized execution pipelines, expanded instruction sets, and superior hardware accelerators (e.g., improved graphics engines).

    • Because a binary compiled for an older architecture (e.g., Apple M2) lacks instructions that target newer architectural features, running that binary on a newer processor (e.g., Apple M5) results in suboptimal execution that fails to exploit modern hardware features.

    • Application Divergence: While everyday productivity tasks (like word processing) suffer negligibly from missing new graphics features, performance-sensitive workloads (such as modern gaming) run noticeably slower or experience performance bottlenecks unless recompiled or upgraded.

  • Standardization via Instruction Set Supersets:

    • Binary compatibility requires backward-compatible ISA standardization, wherein each successive architecture implements an instruction set that is a mathematical superset of its predecessor:         ISAM2⊆ISAM3⊆ISAM4⊆ISAM5\text{ISA}_{\text{M2}} \subseteq \text{ISA}_{\text{M3}} \subseteq \text{ISA}_{\text{M4}} \subseteq \text{ISA}_{\text{M5}}

    • The newer generation architecture supports every instruction present in the legacy architecture, while incorporating supplementary instructions and capabilities.

    • Intel employs the same superset standardization strategy across its x86 processor lines.

Bitwise Logical Operations in MIPS

  • Purpose of Bitwise Instructions:

    • MIPS provides specific instructions to manipulate individual bits or arbitrary bitfields within a standard 32-bit32\text{-bit} register word.

  • Shift Operations:

    • Shift Left Logical (sll):

      • Shifts all bits within a source register to the left by a specified shift amount (shamt), filling the vacated low-order bit positions on the right with zeros.

      • The shift amount ranges from 00 to 3131 bits.

      • Shifting left by ii bit positions multiplies the original unsigned numerical value by a factor of 2i2^i.

    • Shift Right Logical (srl):

      • Shifts all bits within a source register to the right by a specified shift amount, filling the vacated high-order bit positions on the left with zeros while discarding the lowest bits.

      • Shifting right by ii bit positions performs integer division of the value by a factor of 2i2^i.

  • Bitwise AND (and):

    • Primary Function: Bit masking (applying an AND mask) to isolate and preserve a targeted subset of bits while clearing all remaining bits to 00.

    • Masking Logic: The mask register contains 11s in bit positions designated for preservation and 00s in bit positions designated for clearing.

    • Extraction Example: To extract the four most significant bits of register t2t_2 into register t0t_0, a mask register t1t_1 is populated with 111121111_2 in the four highest-order bit positions and 00s across the remaining 2828 bits. Computing the bitwise AND between t1t_1 and t2t_2 isolates the target bits in t0t_0.

    • Image Processing Analogy: Cropping a digital image uses a two-dimensional bitmask where pixels inside the crop boundary are retained and outer pixels are forced to zero.

  • Bitwise OR (or):

    • Primary Function: Bit insertion and bit setting, forcing targeted bits within a register to 11 while leaving all remaining bits entirely unaltered.

    • Masking Logic: The mask register contains 11s in bit positions that must be set to 11, and 00s in bit positions where existing values must be preserved.

  • Bitwise Inversion and the MIPS NOR Instruction:

    • Inversion Logic: A logical NOT operation flips every individual bit (0→10 \rightarrow 1 and 1→01 \rightarrow 0), producing a bitwise complement.

    • Hardware Minimization: MIPS omits a dedicated hardware not instruction to reduce instruction set and datapath complexity, providing the nor (NOT OR) instruction instead.

    • Implementing Inversion using nor:

      • Self-NOR: Performing a NOR on a register with itself computes its complement, based on the Boolean equivalence ¬(A∨A)=¬A\neg (A \lor A) = \neg A.

      • Zero-Register NOR: Performing a NOR between the source register and the constant zero register (register 0\text{register } 0) also computes its complement, based on the Boolean equivalence ¬(A∨0)=¬A\neg (A \lor 0) = \neg A.

      • MIPS Syntax: nor $t0, $t1, $t1 or nor $t0, $t1, $zero.

  • Applications in Digital Media, Entertainment, and Gaming:

    • Modern computing cycles are predominantly consumed by multimedia editing, audio engineering, video streaming, and gaming rather than simple numerical calculations.

    • Digital Image Processing: Inverting black-and-white bitmap pixels via bitwise NOT operations generates photographic negative images (dark pixels become light, and light pixels become dark).

    • Audio and Video Production: Computerized splicing, track mixing, and graphic layer masking depend directly on underlying bitwise logic and masking instructions.

Conditional Operations and Control Flow Implementation

  • Control Flow Instructions:

    • Branch if Equal (beq):

      • Syntax: beq rs, rt, L1

      • Operational semantics: Evaluates whether the contents of register rs\text{rs} equal the contents of register rt\text{rt}. If rs=rt\text{rs} = \text{rt}, program control branches to the instruction labeled L1; otherwise, execution proceeds sequentially to the immediate next instruction.

    • Branch if Not Equal (bne):

      • Syntax: bne rs, rt, L1

      • Operational semantics: Evaluates whether the contents of register rs\text{rs} do not equal the contents of register rt\text{rt}. If rs≠rt\text{rs} \neq \text{rt}, control branches to the instruction labeled L1; otherwise, execution proceeds sequentially.

    • Unconditional Jump (j):

      • Syntax: j L1

      • Operational semantics: Immediately transfers control unconditionally to the instruction at L1, functionally equivalent to a goto statement in high-level C.

  • Symbolic Labels:

    • Labels (such as L1, Else, or Exit) act as human-readable alphanumeric placeholders representing physical instruction addresses in memory.

    • The assembler subsequently resolves and translates these symbolic labels into concrete binary memory addresses.

  • Compiling High-Level If-Else Statements:

    • High-Level Code Example:

      • if (i == j) f = g + h; else f = g - h;

    • Register Allocations:

      • Variable ff mapped to register s0s_0

      • Variable gg mapped to register s1s_1

      • Variable hh mapped to register s2s_2

      • Variable ii mapped to register s3s_3

      • Variable jj mapped to register s4s_4

    • Formulation 1: Inverted Condition using bne:

      • Instruction 1: bne $s3, $s4, Else (if i≠ji \neq j, branch directly to the Else label).

      • Instruction 2: add $s0, $s1, $s2 (executes the true path: f=g+hf = g + h).

      • Instruction 3: j Exit (unconditional jump over the false path to preserve mutual exclusivity).

      • Instruction 4: Else: sub $s0, $s1, $s2 (executes the false path: f=g−hf = g - h).

      • Instruction 5: Exit: (subsequent sequential code).

    • Formulation 2: Direct Condition using beq:

      • Instruction 1: beq $s3, $s4, If_Block (if i=ji = j, branch to the If_Block label).

      • Instruction 2: sub $s0, $s1, $s2 (executes the false path: f=g−hf = g - h).

      • Instruction 3: j Exit (skips the true path).

      • Instruction 4: If_Block: add $s0, $s1, $s2 (executes the true path: f=g+hf = g + h).

      • Instruction 5: Exit: (subsequent sequential code).

  • Generalized Block Structures and Nesting:

    • Conditional branches scale to arbitrary statement blocks (if-block and else-block).

    • Branch statements can be nested hierarchically within other branch blocks, directly mapping to nested conditional structures in high-level programming.

Array Indexing and Loop Translation in Assembly

  • High-Level While Loop Construct:

    • Target Statement: while (save[i] == k) i += 1;

    • Program Intent: Traverses consecutive elements of integer array save starting at index ii, incrementing ii until encountering an element whose value does not equal kk.

  • Register Mappings:

    • Array index variable ii mapped to register s3s_3

    • Comparison variable kk mapped to register s5s_5

    • Base address of array save mapped to register s6s_6

  • Array Addressing Arithmetic in Byte-Addressable Memory:

    • MIPS architecture uses byte addressing.

    • Standard integer elements occupy 4 bytes4\,\text{bytes} (32 bits32\,\text{bits}) each.

    • Element Offsets:

      • Element save[0] resides at base memory address xx

      • Element save[1] resides at address x+4x + 4

      • Element save[2] resides at address x+8x + 8

      • In general, element save[i] resides at byte address x+(4×i)x + (4 \times i)

  • Optimization of Index Scaling via Bit Shifting:

    • Multiplying index ii by the 4-byte4\text{-byte} word size using standard integer multiplication instructions requires multiple processor clock cycles.

    • Because 4=224 = 2^2, shifting index register s3s_3 left by 22 bit positions performs multiplication by 44 in a single clock cycle.

  • Step-by-Step Loop Assembly Implementation:

    • Label: Loop:

    • sll $t1, $s3, 2 (computes byte offset: t1=i×4t_1 = i \times 4)

    • add $t1, $t1, $s6 (computes effective physical memory address: t1=base+(i×4)t_1 = \text{base} + (i \times 4)

    • lw t0,0(t0, 0(t1) (loads the array element save[i] from memory address t1t_1 into temporary register t0t_0 using an offset of 00)

    • bne $t0, $s5, Exit (evaluates condition: if save[i] != k, branches out of the loop to Exit)

    • addi $s3, $s3, 1 (increments index variable: i=i+1i = i + 1)

    • j Loop (unconditionally jumps back to Loop to process the next iteration)

    • Label: Exit: (points to the subsequent instruction following loop termination)

Basic Blocks and Cache Preloading Optimization

  • Strict Definition of a Basic Block:

    • A basic block is a contiguous sequence of program instructions that satisfies two structural invariants:

      • It contains no embedded branch instructions anywhere within its body, except potentially at the very last instruction.

      • It contains no branch targets (entry labels) anywhere within its body, except at the very first instruction.

  • Execution Invariant:

    • Whenever program execution enters the initial instruction of a basic block (either sequentially or via a branch), every subsequent instruction within that block is guaranteed to execute sequentially to completion.

  • Compiler Detection and Cache Preloading:

    • Optimizing compilers analyze control flow graphs to partition code into basic blocks.

    • Instruction Cache Preloading: When the initial instruction of an identified basic block is fetched from memory, the memory hierarchy preloads (prefetches) the entire set of instructions comprising that basic block into the high-speed L1 instruction cache.

    • Latency Reduction: Memory access latency represents a significant fraction of total instruction execution time. Prefetching an entire basic block prevents repeated main memory fetch penalties for subsequent instructions, maximizing system throughput.

  • Illustrative Analogies:

    • Nightstand Book Reading Analogy: An individual reading a multi-volume book series with a nightstand that holds three books will place the current book, its direct sequel, and the third volume on the nightstand simultaneously. Once the first book is finished, the sequel is accessed immediately without walking to the primary bookshelf.

    • Web Page Hyperlink Analogy: A primary web page is an HTML document. Its basic block analog corresponds to all web pages hyperlinked directly from that initial page. Prefetching those linked pages into local cache before the user clicks on them eliminates network latency.

  • Cache Capacity Constraints:

    • If a basic block exceeds available cache line capacity, compilers and memory controllers preload as many instructions of the block as the cache can accommodate.

Set on Less Than (SLT) and Hardware Design Trade-Offs

  • The Set on Less Than (slt) Instruction:

    • Syntax: slt rd, rs, rt

    • Operational Semantics: Evaluates whether the signed value in register rs\text{rs} is strictly less than the signed value in register rt\text{rt}.

      • If rs<rt\text{rs} < \text{rt}, destination register rd\text{rd} is set to 11.

      • If rs≥rt\text{rs} \ge \text{rt}, destination register rd\text{rd} is cleared to 00.

  • Synthesizing Relational Branch Operations:

    • To compile relational conditions such as if (s1 < s2) goto L;, MIPS pairs slt with an equality branch instruction:

      • Step 1: slt $t0, $s1, $s2 (evaluates comparison; sets t0=1t_0 = 1 if true, t0=0t_0 = 0 if false).

      • Step 2: bne $t0, $zero, L (branches to label L if register t0≠0t_0 \neq 0).

  • Hardware Architectural Trade-Offs:

    • Absence of Complex Branch Instructions: MIPS deliberately omits dedicated instructions such as blt (branch on less than) or bge (branch on greater than or equal to).

    • Circuit Complexity and Propagation Delays: Testing for equality or inequality (beq, bne) requires fast, shallow XOR/XNOR logic gates. In contrast, checking relational inequalities (<< or ≥\ge) requires arithmetic subtraction and sign/overflow bit evaluation, which incurs substantially greater gate delay.

    • Clock Period Determination: The global processor clock period is constrained by the critical path of the slowest instruction in the execution pipeline. Introducing complex, slow branch instructions would force hardware designers to lengthen the global clock cycle, penalizing the execution speed of all instructions.

    • Execution Frequency Realities: Statistical profiling reveals that equality and inequality branches (beq, bne) are overwhelmingly the most common branch conditions encountered in real-world software.

    • Architectural Decision: MIPS preserves a fast system clock by restricting branch instructions to simple equality checks, synthesizing less frequent relational tests using a two-instruction combination (slt paired with bne or beq).

Questions and Discussion

  • Bitmask Formulation for High-Order Bit Extraction:

    • Query: How is an AND mask configured to extract exclusively the four most significant bits of register t2t_2 into register t0t_0 while clearing all other bits?

    • Response: The mask register t1t_1 must be populated with binary 11s across the target bit positions (the four most significant bits) and binary 00s across all remaining bit positions. Performing and $t0, $t1, $t2 isolates the target bits while clearing all others to zero.

  • Video Production Facilities:

    • Query: Has anyone visited the movie production facilities, such as the digital studios located at the University of Georgia (UGA)?

    • Response: Student Trevor confirmed familiarity. Digital studios illustrate how modern computing is centered around digital media, track splicing, audio mixing, and graphical manipulation.

  • Video Game Creation and Cognitive Skills:

    • Query: Do students actively build their own video games or primarily play existing games?

    • Response: A student reported engaging exclusively as a player. Game development is highly recommended because it exercises both halves of the brain simultaneously: the analytical programming side and the creative, artistic design side.

  • Branch Condition Inversion and Block Association:

    • Query: Can an if-block or else-block be targeted interchangeably using either beq or bne, or is a programmer constrained to use an if-block exclusively with beq and an else-block with bne?

    • Response: A programmer is not restricted. The choice depends entirely on the formulation of the high-level conditional expression. If the original high-level condition is if (i != j), then bne branches directly to the if-block. Either instruction can target either block by adjusting the branch condition.

  • Nesting Capabilities of Branch Instructions:

    • Query: Can conditional branch operations such as beq and bne be nested inside one another?

    • Response: Yes, branch instructions can be nested hierarchically. Just as high-level languages permit nested if statements, assembly routines can place branch instructions within code blocks governed by preceding branches.

  • Index Multiplier Bit Shift Discrepancy:

    • Query: When calculating array byte offsets for word-sized elements (4 bytes4\,\text{bytes}), why is the index shifted left by 22 bit positions rather than by 44 bit positions?

    • Response: A shift left by ii bits scales a value by 2i2^i. Because the word size is 4 bytes4\,\text{bytes}, and 4=224 = 2^2, the required power of two is 22. Shifting by 22 multiplies the index by 44. Shifting by 44 bits would erroneously multiply the value by 24=162^4 = 16.

  • Basic Block Size and Cache Capacity Constraints:

    • Query: Are all basic blocks preloaded into the cache in their entirety, or only a subset?

    • Response: Preloading depends on the size of the basic block relative to available cache space. If a basic block is exceptionally large, it will not fit entirely in the cache. In such instances, the system preloads as many sequential instructions of the basic block as cache capacity permits.

  • Web Caching Analog to Basic Blocks:

    • Query: In web caching technologies, what constitutes the structural equivalent of a basic block for a given HTML web page?

    • Response: The equivalent consists of all the pages that are directly linked on that primary web page. Preloading those linked pages anticipates user navigation and eliminates network latency, just as prefetching a basic block eliminates memory latency.