Inspect why a compiler transformation is valid
This code optimizer shows local TAC transformations, conservative loop-invariant motion and a small assembly peephole pass. Each mode loads an example and updates the result while you edit. The output is accompanied by recorded changes with their original instruction line, rule, previous instruction and replacement. It is an educational optimiser for a declared integer model, not a service that accepts arbitrary C, C++, JavaScript or processor assembly and promises equivalent output.
Basic-block mode combines constant folding, constant propagation, copy propagation, common-subexpression elimination, selected algebraic identities and dead-code elimination. Loop mode uses the same basic-block, reachability, dominator and natural-loop analysis as the flow-graph tool. Peephole mode has a separate abstract register-machine language. Keep the selected language in mind when moving between examples.
State the arithmetic and observable outputs
The TAC model uses integers with truncating division and ordinary nonvolatile arrays. External scalar inputs must already be initialized. Decimal integer literals are supported; floating-point literals are rejected instead of applying integer identities to a different numerical model. Division by zero and invalid integer exponentiation remain errors. The reference interpreter used in regression tests has execution limits to stop runaway examples; it is not a production runtime or a language-standard implementation.
For dead-code elimination, declare which scalar values are needed after the block. Other final scalar values may be removed because you have declared them unobservable. Leaving the field blank is conservative: every assigned scalar is treated as live on exit. Array stores are always retained. Do not list only the displayed answer if another variable is consumed later in your real program; that would give the optimiser an incorrect contract.
A worked basic-block example
The loaded example assigns constants, adds them, copies simplified expressions, computes the same sum twice and contains unused assignments. With out as the live-out variable, the library produces:
t4 = x + y
out = t4 + t4
Running both versions through the integer interpreter with x = 3 and y = 5 gives out = 16 before and out = 16 after. The calculation and transformations come from the same libraries used here. The unused constant addition is still shown in the trace before dead-code elimination removes its result, so you can distinguish folding a value from deciding that the value is not needed.
Propagation follows the current value facts, not the spelling of a name forever. If a copied source is subsequently reassigned, facts depending on that source are invalidated. Common-subexpression elimination tracks operand versions and the variable holding an available expression. Reassigning a carrier or changing an operand prevents reuse of an obsolete value. Commutativity is used only for integer addition and multiplication, not subtraction, division or remainder.
Read the local optimisation rules
Constant folding evaluates an operation only when its operands are known integer constants and evaluation succeeds within the demonstration limits. A division by zero is left in the program rather than turned into a fabricated number. Constant and copy propagation then substitute known values where the current facts permit it. Algebraic simplification includes identities such as adding zero, multiplying by one and dividing by one under this integer model.
The backward liveness pass starts from the declared live-out set. A dead scalar assignment can be removed when the operation is nontrapping in the model. Potentially trapping division, remainder, exponentiation and array loads stay when their results are dead; deleting their destination alone would not justify deleting an error. Stores and their operand dependencies stay observable. This deliberately conservative behaviour may retain more instructions than a compiler with stronger proofs.
Move loop invariants without creating a zero-trip bug
Loop mode accepts whole TAC and lets you select a natural-loop header. It needs an existing preheader outside the loop that leads only to that header. The tool does not split critical edges or invent a preheader. For headers with multiple latches, it considers their combined loop region before checking motion conditions.
A candidate must have a single scalar definition, invariant operands and a safe operation. Its block must dominate the relevant uses, latches and loop exits; same-block uses must occur after the definition. Loads and potentially trapping operations are not speculated. These conditions prevent a statement inside a possibly zero-trip body from being executed earlier merely because its formula looks unchanged.
The loaded loop example moves 2 instructions into its preheader. Its generated result is:
i = 0
t = a + b
u = t * 2
L1:
sum = sum + u
i = i + 1
if i < n goto L1
Notice that the loop label stays after the moved instructions. Copying the label onto a hoisted instruction would make the back edge execute it repeatedly and would fail to perform the intended motion. If no candidate meets the conditions, the original program remains with an explanation.
Peephole rules use a simple register-machine model
The assembly mode accepts LD, ST, MOV, ADD, SUB, MUL, DIV, MOD, SHL, JMP, JZ, JNZ and HALT. Registers have R-prefixed numeric names; integer immediate operands use a number sign. This abstract machine has no status flags, volatile memory, device I/O, interrupts or aliasing between its named memory cells. The rules are not an assurance that equivalent-looking edits preserve a real CPU's flags or memory-mapped side effects.
Adjacent redundant loads and stores can be removed when no labelled entry point invalidates the assumption. Jump chains can be redirected when they terminate without cycling. Instructions after an unconditional transfer are removed up to the next labelled entry. Multiplication by a positive power of two can become a left shift. Signed division is deliberately not replaced by a right shift, because truncation and negative-value shift behaviour can differ.
Verify the assumptions before using the result
Regression tests run original and optimised TAC on randomized initialized integer inputs and compare live outputs, memory effects and errors. Separate tests cover reassignment, repeated expressions, dead divisions, labelled assembly entry points, negative values and zero-trip loop paths. Tests support the stated model; they do not establish compatibility with every source language or instruction set.
Use the three-address code generator to study translation before optimisation, and the compiler lab to follow the broader workflow. Copy optimized code saves the currently displayed result. Keep your live-out declaration and model assumptions with that result when checking an exam solution.