Past exam of the computer science course of the University of Oxford 2015 Compilers 3 b Solution 2026-10-31
The useful repeated program expressions, nested inside one another, are the memory address of
a[i], its value, and the memory address of a[a[i]]. Materialize each maximal reusable tree at the level at which it is shared, using fresh temporary variables u, v, and w:MOVE(R(u), ADD(C(A),SHL(M(ADD(R(fp),C(I))),2)))
MOVE(R(v), M(R(u)))
MOVE(R(w), ADD(C(A),SHL(R(v),2)))
MOVE(R(t), M(R(w)))
MOVE(M(R(w)), R(v))
MOVE(M(R(u)), R(t))Thus
u is a saved memory address, v the old integer value of a[i], w the second saved memory address, and t the old value at that second location. The two large address trees occur both in loads and as store destinations. After extracting them, the repeated load of a[i] inside the second address and as the middle assignment's source becomes v. Extracting every smaller nested tree again would add no benefit.The relevant alias analysis facts are that local
i does not occupy any location written through global a, that frame pointer fp and base stay fixed, and that t,u,v,w are distinct processor registers or otherwise nonoverlapping temporary variables. There are no intervening calls, volatile memory accesses, or concurrent changes. Under these assumptions, loading i once remains valid even across the array stores. Before the middle store, no array location has yet changed, so both its target memory address and its source value can be computed and saved earlier.No assumption that the two array locations are distinct is required. The middle store may change
a[i] when its target coincides with it, but v is not loaded again afterwards: only the saved address u is needed for the final store. It would be unsound to retain an arbitrary array load across an aliasing store and then treat it as the new contents; that is not what these trees do.For a language with a true global array, a distinct local variable, and no arbitrary means of fabricating pointers to unrelated storage, these facts follow simply from declarations and the stack frame layout. Accesses must denote valid array elements. In an unrestricted low-level language with overlapping storage, arbitrary pointer arithmetic or unchecked out-of-range accesses, that conclusion requires extra guarantees. Omitting emitted array bounds checks does not itself prove that all memory addresses are valid. If denotes a word load, the saved quantities are
Past exam of the computer science course of the University of Oxford 2015 Compilers 3 c Solution 2026-10-31
Here is a literal instruction selection for the trees in part (b), with the temporary variables allocated to processor registers.
MOV r,#k loads an arbitrary constant in one instruction. LD and ST load and store one four-byte word; [r] denotes zero-offset access. LSL is a left shift. We use conventional base-plus-immediate access for the fixed local offset I.MOV rb, #A
LD ri, [fp + I]
LSL ru, ri, #2
ADD ru, rb, ru
LD rv, [ru]
LSL rw, rv, #2
ADD rw, rb, rw
LD rt, [rw]
ST rv, [rw]
ST rt, [ru]The first four instructions construct
u, the fifth obtains v, the next two construct w, and the last three perform the remaining load and the two stores. Each destructive update of ru or rw reuses a processor register whose previous value is no longer needed. We assume enough processor registers to avoid a register spill.If the target offers only the explicitly mentioned two-register register-offset addressing and lacks base-plus-immediate access, replace the one local load by
MOV rk,#I; LD ri,[fp+rk]; all other conclusions are unchanged. A zero processor register or a zero-offset load supplies the notation [ru] and [rw] as usual. This direct translation takes ten instructions with immediate local addressing, or eleven with the stated replacement. Thus These are instruction counts for the specified abstract target, not measured execution times. Past exam of the computer science course of the University of Oxford 2015 Compilers 3 d Solution 2026-10-31
The target's register-offset addressing already performs the addition of the array base and a scaled index as part of each load or store. Materializing a maximal common address expression into a processor register introduces an explicit
ADD that this addressing mode could have supplied. Here the extra address temporary variables save no arithmetic that the memory instructions need to perform separately.Instead keep the scaled indices, share the loaded old value of
a[i], and fold the base addition into each memory operand:MOV rb, #A
LD ri, [fp + I]
LSL rj, ri, #2
LD rv, [rb + rj]
LSL rk, rv, #2
LD rt, [rb + rk]
ST rv, [rb + rk]
ST rt, [rb + rj]rj remains the original index's byte offset, rv is its old element, and rk remains the second element's byte offset. Both stores use those saved offsets. Folding address additions into the memory instructions removes two instructions, reducing ten to eight, or eleven to nine if the local load requires the alternative sequence described in part (c). ThereforeThis illustrates why common subexpression elimination must interact with instruction selection: a larger repeated tree is not automatically a better value to materialize. A useful refinement retains common scaled-index trees, or propagates the address addition trees back into their memory uses. The calculation establishes an instruction-count improvement under the stated instruction set architecture; scheduling and actual timing depend on further machine details.
Past exam of the computer science course of the University of Oxford 2015 Compilers 3 e Solution 2026-10-31
The source rewrite already saves the old
a[i] in register-allocated t. Denote the original integer index by , its original element by , and the original element there by . The second fragment first sets t=j, then writes to a[i0], and finally writes to a[j]. Thus it performs the same intended swap without needing to recompute the second memory address from a possibly modified array element.For completeness, the first fragment is also correct when the two locations might alias. If , its middle store changes only
a[j], so the final a[i] still denotes the first location. If , then , and the supposed swap is a no-op in both fragments. There is no need to assume distinct locations.For the second fragment, common subexpression elimination of maximal addresses gives, using
z for the second address:MOVE(R(u), ADD(C(A),SHL(M(ADD(R(fp),C(I))),2)))
MOVE(R(t), M(R(u)))
MOVE(R(z), ADD(C(A),SHL(R(t),2)))
MOVE(M(R(u)), M(R(z)))
MOVE(M(R(z)), R(t))The nested memory-to-memory assignment requires an additional scratch processor register
rv on a reduced instruction set computer. A direct translation is therefore:MOV rb, #A
LD ri, [fp + I]
LSL ru, ri, #2
ADD ru, rb, ru
LD rt, [ru]
LSL rz, rt, #2
ADD rz, rb, rz
LD rv, [rz]
ST rv, [ru]
ST rt, [rz]The same compiler need not produce any better code: this has the same ten-instruction count as part (c). It still performs two element loads, two element stores, two shifts and two separately materialized address additions, plus the base and local-index setup. The processor register roles and store order differ, but the work is the same. The corresponding folding of register-offset addressing removes both
ADD instructions here too, yielding the same eight-instruction count as part (d).The key alias analysis advantage available in both fragments is that
i remains unchanged by the array stores. In the second fragment, t is also unchanged after its first assignment because it lives in a processor register. Its name alone does not produce a further saving beyond what the first fragment's common subexpression elimination already achieves. Exact instruction selection is not uniquely prescribed by the paper; these explicit translations demonstrate why the claimed source-level efficiency advantage does not follow:Register forwarding supplies a later instruction with a computed value before that value has reached the register file. It removes some read-after-write hazards without changing the program's meaning. Consider these symbolic machine instructions, with the destination first:In the five-stage in-order pipeline, the addition produces its result at the end of EX. In the next cycle the subtraction is in EX, although the addition has not yet reached WB. A bypass from the addition's EX/MEM pipeline register to the subtraction's arithmetic logic unit input supplies the new
ADD r1, r2, r3
SUB r4, r1, r5r1; the old value read in ID must be overridden.The bypass control compares source and destination processor register identifiers and selects the youngest applicable older producer. It must also check that the producer actually writes that processor register. Forward the newest available result instead of waiting for its writeback. A load instruction is different: its value is normally available only at the end of MEM, so an immediately following dependent instruction still needs a pipeline stall in this five-stage arrangement.
In IF, fetch
PREFETCH normally. In ID, recognize its opcode, read the base processor register and immediate offset, and set controls selecting a prefetch request rather than a load instruction or store instruction. Ordinary register forwarding and data hazard interlocks still apply to that base processor register. In EX, use the arithmetic logic unit to form the effective memory address.Latch that memory address and a prefetch-valid control into EX/MEM. In MEM, put the memory address and any hint information on the dedicated request computer bus, or enqueue them in a small prefetch-request queue. The cache prefetching engine handles lookup, allocation and the later cache line return independently. Do not wait for the fill or select the returned data as a register file input. In WB, disable architectural processor register and processor condition flag writes; the instruction simply leaves the in-order pipeline.
If the request path is busy, dropping the hint is compatible with the contract in part (ii), and preserves its nonblocking purpose. A design that instead stalls until queue space exists can still be correct but reduces the performance benefit. A memory management unit must not turn a speculative hint into an ordinary protection fault: discard an invalid target, or use an appropriately checked nonfaulting translation path. Suppress device transactions for memory-mapped input-output and avoid speculative writes. Use the existing address-generation datapath, add a prefetch request/control path, and disable demand-load waiting and writeback.
Define
PREFETCH [a] as a software prefetch hint: initiate a request for the cache line containing memory address a, then continue without waiting for that cache line to arrive. It produces no value in a destination processor register, changes no program data and creates no data-result dependence for later instructions. It may be ignored if resources are unavailable. A useful hint is nonfaulting for an inaccessible or untranslated target: a later real load instruction must still perform its ordinary access checks. This is a proposed contract for the instruction, rather than a guarantee that the patent abstract alone fixes every detail of its semantics.For example, after reading the next pointer of a linked list node, prefetch that next linked list node while processing the current one. Replacing the hint by an otherwise unused ordinary load instruction on this in-order pipeline would wait in MEM on a cache miss before the current computation could start. It would also consume a destination processor register and might raise a synchronous processor exception. A harmless hint can be scheduled earlier, even on a path where the data will never be demanded. The crucial semantic difference is that cache filling may continue after the prefetch instruction itself has finished.
A software prefetch is not a memory barrier and does not establish acquire-release synchronization or promise that later accesses will hit. Its purpose is performance; correctness must survive the hint being ignored.
A reorder buffer records instructions in program order, including those with no destination processor register. Each entry needs a completion state before instruction retirement can pass it. Thus a store instruction must report that its memory address and data are ready and whether execution detected a fault, even though it has no ordinary register file result.
Suppose an older division occupies the head of the reorder buffer, followed by a store instruction and an addition. The latter two can finish first. The store instruction's completion message identifies its reorder buffer entry, carries or identifies the buffered memory address and data, and supplies its status. The entry is then ready, but its write remains private until it is the oldest instruction allowed to commit. When the division retires successfully, the store instruction can commit to the store buffer or memory system, and the addition can subsequently retire. If the division faults, the younger store instruction is discarded without changing visible computer memory.
If the store instruction never reported completion, its reorder buffer entry would remain unready and block instruction retirement indefinitely. Conversely, treating it as completed at issue could commit missing data or suppress its later fault. The common data bus carries tagged completion information as well as register values. A false-predicated instruction also needs a completion indication even when it changes no data.
This answer uses the diagram's shared result/completion path. An architecture can instead provide a dedicated store queue completion path to the reorder buffer; there is no universal requirement to send store data over the same physical wires as arithmetic results. What is essential is delivery of the tagged completion and exception status before instruction retirement.
Use two different shared locations
x and y, initially zero, and two CPU cores. The following are architectural memory operations, with each result kept in its own processor register:| Core 0 | Core 1 |
|---|---|
STORE [x], 1 | STORE [y], 1 |
LOAD r0, [y] | LOAD r1, [x] |
Each CPU core can retire its write into its own store buffer. Before either write drains, Core 0's load instruction misses its own store buffer because it asks for
y, while Core 1's asks for x. Both can read the old shared values. Afterwards the buffers drain and both locations become one. ThusThere is no contradiction with cache coherence: each location still has an agreed write order. The unusual observation concerns ordering across two different locations. This is the standard store-buffering example, also permitted by total store order.[ref]On a single CPU core executing the two logical participants in an ordinary thread interleaving, the same pair of zero observations is impossible under the usual shared-buffer and own-write-forwarding behavior. To read
y=0, Core-0's logical read must precede the other participant's write of y; to read x=0, the other read must precede the write of x. Combining these requirements with each participant's program order gives the impossible cycleIf a write is still buffered across a context switch on that single CPU core, a later read of the same address sees it through store-to-load forwarding rather than returning an older value. Hence separate store buffers on different CPU cores enable the observation; the comparison assumes ordinary coherent cacheable computer memory and no device accesses or additional writes. A locally completed store need not yet be visible to another core.With O1, even readers must acquire and release the same mutex. Acquiring it normally uses an atomic read-modify-write on the lock's cache line; releasing writes that cache line again. As different CPU cores repeatedly read the data, ownership of the lock's cache line moves among them, causing cache coherence traffic and serializing the protected operations. If the lock shares a cache line with otherwise stable data, false sharing can also invalidate useful reader data. The actual data need not change for this lock traffic to occur.
With O2 and correctly ordered publication, readers perform only load instructions: copy
p once into a processor register, then read that version of the data. Multiple CPU cores can keep read-only shared copies of its cache lines. No per-reader exclusive ownership transfer is needed. During an update, a writer fills newly allocated computer memory privately; the old version's cache lines remain unchanged for readers already using it. Publishing the new pointer writes p and invalidates cached copies of that pointer's cache line, but this occurs only on updates.For many reads and rare updates, O2 avoids lock-line contention and permits concurrent readers, so it can be substantially faster. The costs are heap allocation, construction or copying of a whole replacement, first accesses to its newly populated cache lines, and deferred memory reclamation. Frequent updates or very large replacements can reverse the comparison. O1 can modify a small field in place and may then save copying and computer memory. These are workload-dependent comparisons, not a claim that removing every mutex always accelerates an operation.
Use the MIPS zero register as a write-suppression destination: encode . There are only 31 stored processor registers, and address zero denotes the constant-zero source rather than a writable storage cell. Its writes are discarded, soThis permits a
store to write memory while its unavoidable register file write has no effect. It also implements a no-operation by selecting no memory write and destination zero. The statement that reads of register zero return zero is realized consistently by this standard constant-zero, discard-writes implementation.Decompose the 32-bit pattern of into bytes:Let be its ten-bit encoding, so . The following custom-ISA assembly language sequence implements the requested sum:
addi t,s,x0
addi t,t,x1
addi t,t,x2
addi t,t,x3The symbols
x0 through x3 stand for the encoded ten-bit fields, not for the expanded 32-bit values. After line , the destination contains modulo . HenceIf , each instruction correctly uses the preceding partial sum. Zero-byte additions can be omitted except that, when , an initial instruction must still copy the original source if all earlier omitted bytes are zero. An assembler can initialize t with add t,s,0 instead and then emit only nonzero lanes. If , the intended register effect is discarded.For a MIPS instruction
lw t,k(s), first construct in a scratch processor register , using the four-lane sequence above with destination , and then issueload t,(u)For
sw t,k(s), construct the same address in and issuestore t,(u)Choose , or preserve a live scratch processor register according to the calling convention. In particular the store sequence must retain the original data in , even when . Both expansions need at most five custom instructions and have the same address and memory-word effects as the corresponding MIPS instructions, assuming aligned valid memory and 32-bit modular address arithmetic. When , the memory instruction alone suffices. These are listings for the examination's custom instruction set architecture, not native MIPS encodings; exact exception and pipeline behavior is outside the specified datapath.
A MIPS R-type instruction has the 32-bit instruction encodingFor
add $x,$y,$z, the processor register indices are , and , while . The main opcode selects the R-type family and the function field selects addition. The register file reads its two operands from instruction bits 25:21 and 20:16. In the original datapath, RegDst=1 selects bits 15:11 as the destination, ALUSrc=0 selects the second register file output, and ALUFunc=ADD makes the arithmetic logic unit add its inputs. The result returns to wdata; RegWrite=1 writes it to at the active clock edge. The zero output is irrelevant here.[ref]Digital systems, linear algebra, introduction to formal proof examination paper by the University of Oxford (2014). Question 1 datapath, printed page 2: the input-0 and input-1 multiplexer labels determine these control polarities
A MIPS I-type instruction instead has the instruction encodingFor
addi $x,$y,n, , , and the low sixteen bits contain the immediate operand. The register file supplies to the first arithmetic logic unit input. Set RegDst=0 to select bits 20:16 for the destination, and ALUSrc=1 to select the extended immediate operand for the second input. The opcode directly requests addition, so ALUFunc=ADD and RegWrite=1. The second register file read is unused. The returned result is written into .The sign extension circuit retains the low sixteen bits and copies bit 15 into all sixteen new high positions:Thus sign extension preserves the signed two's complement value:
0x7fff becomes 0x00007fff, whereas 0x8000 becomes 0xffff8000. For both instructions, the architectural result above assumes no signed overflow; the full MIPS architecture specifies an overflow exception, which is outside this simplified datapath.Make the code a leaf procedure called
array_diff, copy the four argument processor registers into the temporaries used above, and replace the final label by a return. The copies are real addu instructions, avoiding an unexplained move pseudo-instruction:array_diff:
addu $t0,$a0,$zero
addu $t1,$a1,$zero
addu $t2,$a2,$zero
addu $t3,$a3,$zero
# insert the code of (i), including its initial zero-count test
# use the local label array_diff_done in place of done
array_diff_done:
jr $ra
sll $zero,$zero,0In the literal insertion, the
done: line from (i) is the array_diff_done: line displayed here; it is not a second return block. Under the usual calling convention, temporary processor registers are caller-saved. This procedure calls no other procedure and changes no saved processor registers, so it needs no stack frame or saved return address.For a 32-bit constant , define and using its unsigned binary representation. Load it with
lui followed by ori; both are single MIPS instructions. For base addresses and count , the main program is:main:
lui $a0,H_A
ori $a0,$a0,L_A
lui $a1,H_B
ori $a1,$a1,L_B
lui $a2,H_C
ori $a2,$a2,L_C
lui $a3,H_N
ori $a3,$a3,L_N
jal array_diff
sll $zero,$zero,0
main_after_call:
# c now contains the differences; continue the main program hereHere each
H_... and L_... is an assembler-time numeric constant, not an executed operation. lui places the high half and clears the low half; ori inserts the low half without sign extension. ThusThe jal instruction saves the return address after its branch delay slot in $ra; jr $ra resumes at main_after_call. A main routine that itself needs to return to a caller must save its incoming $ra before jal and restore it afterwards.A zero-address instruction has no explicit operand addresses, so its operands and result location must be implicit in the instruction set architecture. A stack machine supplies these naturally: operations remove their inputs from the top of an operand stack and push the result. A fixed-processor register design is logically possible, so “almost certainly” is appropriately weaker than a proof that only a stack machine could work.
Write the stack from bottom to top, with its top on the right. Let stand for any unchanged prefix. Suitable effects areThus
add pops two operands and pushes one sum, reducing stack occupancy by one. The special const c instruction pushes its immediate constant and increases occupancy by one. Only const needs an explicit value in its encoding.In the pictured single-cycle MIPS architecture,
RegDst selects the write address of the register file: zero selects instruction bits , the rt field used by a load; one selects bits , the rd field used by an MIPS R-type instruction. RegWrite enables the clocked write to the selected processor register.ALUSrc selects the second ALU input: zero uses the second register file read output, while one uses the sign-extended 16-bit immediate field. The zero signal is produced by the ALU, rather than being an opcode-decoder output: it is one exactly when the ALU result is zero. During beq, the ALU subtracts its operands, so zero tests equality. The diagram combines it with Branch to select the branch target instead of .Run the following two MIPS instruction tests separately from externally prepared states, and inspect the register file after the indicated instruction. External preparation is useful in a manufacturing test: code that initializes processor registers through the very control line being tested need not work. Assume the one potentially faulty line is
RegDst; all other lines work normally.For the first test, preset The encoded
$t0=7, $t1=5, $t2=99, and executeadd $t2, $t0, $t1rt is $t1, while rd is $t2. A healthy line or a line stuck at one writes 12 into $t2. A line stuck at zero instead writes 12 into $t1, leaving $t2=99.For the second test, preset The zero immediate makes instruction bits zero. A healthy line or a line stuck at zero writes 37 into
$t3=4, $s0=L, and the aligned memory word at to 37, then executelw $t3, 0($s0)$t3; a line stuck at one attempts to write the MIPS zero register, leaving $t3=4. The MIPS zero register ignores attempted writes. Thus, recording the first test's $t2 and the second test's $t3,The register file in this datapath supplies both read ports combinationally for whatever read addresses the instruction fields present. Reading a processor register is harmless, and a result that the current MIPS instruction does not need can simply be ignored. Only writes require an explicit enable because writes change architectural state. There is consequently no functional need for
RegRead in this design.The data-memory read interface has an explicit
MemRead enable. Non-load MIPS instructions can present irrelevant or invalid addresses at the memory address input; an external memory transaction should not be initiated merely because those bits happen to be present. An explicit enable also permits interfaces with memory-mapped input-output, where a read can have a side effect. It can reduce unnecessary activity even for ordinary memory.This is a distinction in the supplied datapath, rather than a universal physical prohibition: other register files can have read enables, and an ideal side-effect-free memory can be modeled with continuous reads.The calling convention passes the integer argument in
$a0, returns the result in $v0, and uses jal with $ra for a call and its return address. The callee returns using jr $ra. Its stack frame grows downwards from $sp and must be removed before returning, restoring the caller's stack pointer.The
$s processor registers are callee-saved registers: a callee that uses $s0 or $s1 must restore their incoming values. The $a, $v, and $t processor registers are caller-saved registers; a caller must preserve any of their values that it needs after a call. Consequently foo keeps its own argument in $s0 and the first call's result in $s1, where nested calls preserve them. Because a nested jal overwrites $ra, foo also saves its incoming return address. Every recursive activation has its own stack frame.The supplied MIPS instructions use the paper's simplified convention: pseudoinstructions such as
subi are accepted, and control transfers have no branch delay slot. The completed code below follows that convention. A hardware implementation with delayed control transfers requires suitable scheduling or nop instructions throughout the supplied code as well.The entry sequence creates one 12-byte stack frame, then preserves the return address and both used callee-saved registers:The closing sequence reverses these effects:Loads must precede deallocation because their offsets refer to the current stack frame. The return value in
subi $sp, $sp, 12 # allocate three four-byte words
sw $ra, 0($sp) # save return address of this activation
sw $s0, 4($sp) # save caller's s0
sw $s1, 8($sp) # save caller's s1lw $ra, 0($sp) # recover return address of this activation
lw $s0, 4($sp) # restore caller's s0
lw $s1, 8($sp) # restore caller's s1
addi $sp, $sp, 12 # deallocate the frame
jr $ra # return to the caller$v0 is deliberately retained. Saving $ra is essential even though it is not an $s processor register: otherwise the second nested call would destroy the address to which this activation must return.