Circuit Intermediate Representations
A circuit intermediate representation (IR) describes a quantum–classical program inside a compiler or between tools. Its operation meanings, types, dependencies, and validity rules make transformations possible to analyze. An IR may be text, a graph, or a structured in-memory object. A shared file extension alone does not establish shared behavior or backend support.
We will follow qubit values and measurement records through several representations, then test a concrete measurement-conditioned rewrite. An IR provides a language for correctness arguments; it does not make arbitrary program equivalence or termination decidable.
Required background. Quantum Software Stack connects compilation to execution; Circuit Model defines the operations being represented; Universal Gate Sets distinguishes exact and approximate synthesis.
Quantum program representations
Section titled “Quantum program representations”A structured program retains calls, loops, symbolic parameters, and named outputs. A circuit graph makes operation dependencies convenient to analyze. A target-specific form identifies physical qubits, native instructions, timing, and resource conflicts. An encoded form may describe logical qubits, syndrome cycles, and resource factories.
Early lowering can erase useful structure: expanding a loop hides its compact iteration pattern, and expanding a gate can hide an algebraic identity. Later binding can be useful, but a decision must be resolved before the dependent instruction needs it. Just-in-time compilation or parameter binding is possible when its timing and target assumptions permit it.
One language may span several levels. OpenQASM 3 represents both abstract circuits and explicit timing/calibration constructs. Multi-level frameworks can mix high-level and target dialects. Neither approach requires every compiler to use the same sequence of intermediate files.
Parsing and meaning are different checks
Section titled “Parsing and meaning are different checks”| Check | What it establishes | Example failure |
|---|---|---|
| Syntax | The input follows the grammar | Missing delimiter |
| Names and types | Operations and operands have valid definitions | Undefined gate or wrong operand count |
| Structure | Values, branches, and effects are used consistently | A consumed quantum value is reused |
| Supported features | The backend accepts this program subset | Measurement-controlled branch unsupported |
| Target constraints | Operations fit the device resources and timing | Required native interaction unavailable |
| Output interpretation | Records correspond to declared results | Swapped or missing result fields |
A parsed program can fail any later check. Even a well-typed, executable program can implement the wrong algorithm. The official specifications define which checks are normative; testing a few accepted examples does not establish complete conformance.
Operations, values, and effects
Section titled “Operations, values, and effects”A gate name needs an operand order, parameter domain, units, and mathematical definition. An instruction set can additionally contain measurement, reset, and classical operations. Those instructions have effects beyond multiplying a state vector by a unitary.
Classical values need widths, signedness, rounding, and overflow behavior where relevant. Quantum values need subsystem identities and rules for allocation, use, measurement, discarding, and reuse. Output names must remain connected to actual result slots and any tracked frame or permutation.
Some annotations affect mathematical meaning: tensor order and angle units are examples. Others identify physical realization: a calibration timestamp does not alter an abstract gate matrix, but it identifies which waveform or model was used. Display labels may be freely changed. A transformation should know which category it is changing instead of treating all metadata alike.
Mutable handles and functional values
Section titled “Mutable handles and functional values”Two common designs represent quantum data differently.
- A mutable handle names a runtime qubit. Operations modify that resource; effect and alias analysis preserve the order of its uses.
- A functional value represents one version of a quantum resource. An operation consumes an input version and returns its successor, for example .
Copying a handle can create two classical names for the same physical qubit; it does not create two independent quantum states. The compiler must recognize their aliasing. In a consuming value model, reusing an old version instead incorrectly suggests two independent evolutions of one state.
Static single assignment (SSA) means each value has one definition. By itself it allows many uses and does not enforce quantum no-cloning. Additional quantum rules are required. In an affine design, each quantum version has at most one consuming use on each execution path; a linear design requires exactly one, possibly an explicit discard. Two syntactic uses can be legal when they occur in mutually exclusive branches and merge correctly.
These rules concern descriptions, not destruction and recreation of a physical qubit at every gate. QSSA and QIRO develop concrete value-based designs; QIRO also describes conversion from a representation with mutable quantum effects. Their precise operations and checking rules need not coincide.
Dependencies and schedules
Section titled “Dependencies and schedules”A static expanded circuit can use a directed acyclic graph (DAG) with quantum, classical, and timing dependencies. In a simple finish-to-start model, an edge requires
where is the operation duration and is any additional result-transfer or readiness latency. A zero-latency resource edge has . More detailed models can represent streaming or earlier result availability explicitly.
The graph can contain symbolic durations to be resolved later. It does not discover gate commutation automatically: semantic analysis decides which dependencies may be removed or changed. Operations on different qubits can still conflict through a shared control channel or crosstalk restriction.
A plain unconditional operation DAG does not express arbitrary dynamic loops. Control-flow graphs and structured regions represent branches and iteration; finite loops can sometimes be unrolled. A measurement-dependent exit condition needs a termination or timeout policy as well as control-flow support.
Blocks, regions, and merges
Section titled “Blocks, regions, and merges”In SSA, a definition must dominate its ordinary uses: every control-flow path to the use passes through the definition. A branch-local value cannot be used outside the branch without a valid merge. Block arguments or phi nodes select the incoming value associated with the path actually taken. This is a classical choice of the live quantum version, not a coherent superposition of two program branches.
MLIR organizes operations into blocks and regions and lets dialects define types and verification rules. The framework supplies infrastructure, not the quantum meaning of a new dialect. It can support different region semantics, so the relevant dominance and effect rules must be those of the chosen dialect.
Specify the observable behavior of a rewrite
Section titled “Specify the observable behavior of a rewrite”For a closed unitary fragment, the density-operator channel is
Multiplying by a global phase leaves this channel unchanged. That phase must nevertheless be retained when the operation is coherently controlled: an isolated channel does not uniquely specify its coherent controlled extension. For example, , so reducing a rotation modulo is harmless for its isolated channel but can alter a controlled gate. Controlled Operations develops this distinction.
For a terminating adaptive program, outcome-resolved maps are completely positive and trace nonincreasing, with a trace-preserving sum. Retaining the classical output gives
If a loop may never terminate, its terminating outcomes can have total trace less than one. A finite cutoff can instead produce an explicit timeout output. Similarly, accepted postselected outcomes alone generally do not sum to a trace-preserving operation. Do not normalize them and then silently call the result a linear channel. See Quantum Instruments.
Added ancillas and output decoding
Section titled “Added ancillas and output decoding”A compiled program may initialize extra qubits, move data, and track classical frames. Specify an input embedding and an output interpretation . Its interpreted behavior is
For full-channel equivalence one can require
The interpretation can include a result permutation, a controlled frame correction, or discarding internal ancillas. It cannot silently change which outputs the caller requested. A weaker task-specific comparison is sometimes sufficient, but then it does not certify the complete channel. The software-stack page explains composition of these distances and the postselection qualification.
A measurement-conditioned correction in SSA
Section titled “A measurement-conditioned correction in SSA”Prepare two qubits in , apply to , then CNOT from to . Measure in the computational basis and apply to when the result is one. This language-neutral sketch uses consuming quantum values:
func @prepare_and_correct() -> (bit, qubit) { %q0 = q.alloc_zero %q1 = q.alloc_zero %q0a = q.h %q0 %q0b, %q1a = q.cx %q0a, %q1 %m = q.measure_z_discard %q0b %q1b = q.if %m -> qubit { %q1x = q.x %q1a q.yield %q1x } else { q.yield %q1a } return %m, %q1b}This is explanatory pseudocode, not a named standard’s syntax. Here
q.alloc_zero explicitly initializes a fresh qubit; q.measure_z_discard
returns its Z-measurement bit and discards that measured subsystem. The two
uses of %q1a are on exclusive paths. Each path yields one live successor,
and the merged %q1b is available at the return.
Before measurement the state is . Each occurs with probability , leaving in . Correction gives , so
The record is random even though the returned qubit is certainly zero. Removing the measurement record preserves the reduced qubit state but changes the declared output pair. Swapping branch labels without changing the conditional operation also changes the computation.
When a physical correction can become postprocessing
Section titled “When a physical correction can become postprocessing”If the only later use of is a Z-basis measurement , omit the physical and report . This preserves the classical output in the ideal model. More generally, exchanges the two Z-measurement effects, which is why relabeling works.
It does not return the same uncorrected quantum state. If quantum operations follow, propagate the frame through them and interpret every affected output. Commutation is not required: converts an X frame to a Z frame. For this Bell example, adding only followed by Z measurement still gives uniform statistics on each branch, so that is not a counterexample. Returning as quantum data, or copying its computational-basis value to an extra output before correcting the record, can expose the difference.
Gate alphabets, capabilities, and physical targets
Section titled “Gate alphabets, capabilities, and physical targets”A gate alphabet specifies named operations and parameter semantics. A capability profile additionally restricts program features such as classical arithmetic, loops, allocation, measurement, and output structure. The target then specifies available resources, connectivity, timing, and implementation.
Universality of a unitary gate set says nothing by itself about real-time branching, reset, instruction memory, or output schema. For direct execution of an already-lowered program, its required capabilities must be supported. An earlier legalization pass may replace an unsupported operation with a supported sequence, provided it preserves the specified behavior and timing.
| Design | What it supplies | What still needs specification |
|---|---|---|
| OpenQASM 3 | Quantum–classical syntax, gate modifiers, timing and calibration constructs | Supported language version/subset and calibration grammar |
| QIR | Quantum instruction/runtime interfaces within LLVM IR | Profile, instruction set, target capabilities and output format |
| LLVM/MLIR | Values, control flow, types and compiler infrastructure | Quantum operation meanings and appropriate effect rules |
| QSSA/QIRO | Concrete quantum-aware value/effect designs | The selected design’s operations and transformation assumptions |
In the QIR Adaptive Profile checked here, mid-circuit measurement and nested forward branching are required. Loops, broader arithmetic, and dynamic allocation are optional capabilities; reset availability depends on the quantum instruction set. A backend claiming adaptive support therefore need not support every dynamic program. The official specification is the authority for a particular version, not the table’s short summary.
Timing units are part of the program
Section titled “Timing units are part of the program”OpenQASM’s dt denotes a backend waveform-sample duration. Thus 20dt can
mean 10 ns on one target and 40 ns on another. Absolute duration types specify
physical intent, but the target must still resolve sample quantization,
alignment, and tolerance. A delay that is the identity in ideal gate algebra
can nevertheless be required for an experiment’s timing; deleting it changes
that experiment.
Do not confuse an ordering barrier with a specified physical waiting time. The OpenQASM timing specification distinguishes these constructs. An IR also needs to preserve result-ready dependencies and shared-resource restrictions when it makes a schedule concrete.
Checking a particular transformation
Section titled “Checking a particular transformation”Translation validation compares a particular input/output pair rather than proving all executions of the compiler correct. Small unitary fragments can use matrices with the appropriate phase policy. Adaptive fragments need outcome-resolved maps or a justified task-specific comparison; checking one prepared state is not a proof for arbitrary inputs.
Complement semantic checks with name/type validation, path-sensitive resource use, branch merges, target legality, timing, and output decoding. Serialization round trips should preserve meaning; byte identity is required only when a canonical encoding is specified. Unknown semantically required operations or fields must not be silently dropped. Explicitly optional annotations may have different rules.
For reproducibility, preserve language/dialect versions, imported definitions, units, mappings, relevant compiler options, target information, and output schemas. These identify what was transformed and executed; a hash alone proves neither semantic equivalence nor physical accuracy. Further compilation methods are developed in Gate Decomposition and Circuit Optimization.
Exercises
Section titled “Exercises”1. Locate four different failures
Section titled “1. Locate four different failures”A file passes its grammar, but it calls an undefined gate entangle; after a
library is added, the program uses a measurement-conditioned branch forbidden
by the selected profile; after selecting an adaptive profile, compilation
finds that the required target coupler is disabled. Classify the three
failures. What fourth check remains before the result can be interpreted?
Solution
The original file is syntactically valid but semantically incomplete because
entangle has no resolved definition. The branch then produces a profile
conformance failure. The disabled coupler is a target-legality failure.
After code generation and execution, the output still has to satisfy its output specification: schema version, field names, bit order, accepted-trial rule, and failure status must be checked before postprocessing. Controller loading and deadline checks can also fail between target legalization and a valid result.
2. Global phase and controlled use
Section titled “2. Global phase and controlled use”For a closed one-qubit program, let . Show that and produce the same density-operator channel. Then explain why replacing by inside a controlled operation is not generally harmless.
Solution
For any density operator ,
The phase is global only when the operation acts unconditionally on the whole branch. A controlled version is
The factor is now a relative phase between control branches. It can
affect interference. An IR that supports automatic control modifiers must
therefore retain enough phase information to define the controlled operation,
even when the uncontrolled channel ignores global phase.
3. Derive the classical–quantum output
Section titled “3. Derive the classical–quantum output”Derive the output state of the worked measurement-conditioned correction from . Verify both measurement probabilities and the conditional state of .
Solution
After and CNOT,
Computational-basis measurement of gives or , each with probability . The corresponding state of is or . Applying gives in either branch. Retaining the classical record yields
Discarding leaves on , but that reduced state does not preserve the declared classical output.
4. Find the illegal SSA use
Section titled “4. Find the illegal SSA use”Consider the functional quantum SSA fragment
%qa = q.h %q%u = q.x %qa%v = q.z %qaWhy is it invalid, and what are two valid repairs with different meanings?
Solution
%qa has two consuming uses. The fragment attempts to evolve the same unknown
quantum value along two simultaneously live paths.
A sequential repair is
%qa = q.h %q%u = q.x %qa%v = q.z %uwhich implements . A conditional repair places the two uses in mutually exclusive branches and merges one yielded quantum value afterward. That implements either or according to the branch condition. The two repairs are not semantically equivalent.
5. Check supported program features
Section titled “5. Check supported program features”A program requires mid-circuit measurement, forward branching, reset, and 32-bit integer arithmetic. Backend supports all but reset. Backend supports measurement, branch, and reset but only Boolean classical computation. Does either backend satisfy the profile directly? How could a legalization pass change the answer?
Solution
With
neither advertised capability set contains all requirements. Direct profile conformance fails for both.
A legalization may replace reset by a supported measurement-and-conditional operation if that sequence has the required reset postcondition on backend . It may also constant-fold, narrow, or move the integer computation to a near-time host if its inputs are available there and doing so preserves timing and semantics on backend . A measurement-dependent integer calculation cannot generally be moved before that measurement. Those are compiler transformations with proof obligations, not permission to ignore the missing capabilities.
6. Explain why 20dt is not time portable
Section titled “6. Explain why 20dt is not time portable”Two backends accept an instruction delay 20dt. Their controller sample
periods are and . Compare the physical
delays. What timing specification would be needed to preserve a intent?
Solution
The physical durations are
The syntax is portable but the timing is target dependent. A portable source can express in an absolute duration type, together with an allowed quantization or rounding rule. Target lowering then converts that duration to sample units and rejects a target that cannot meet the declared tolerance.
7. Preserve output order
Section titled “7. Preserve output order”A two-qubit program declares output (parity, flag), but a backend returns two
unlabeled bits in physical-qubit order. Why can a visually plausible histogram
still be wrong? Give the minimum metadata needed to decode it.
Solution
Swapping the two fields permutes outcome labels while leaving the total number of shots and often the rough histogram shape unchanged. Correlations can also look plausible under a consistent but wrong bit permutation.
The result needs a schema version, mapping from acquisition or result slots to declared output fields, bit significance within aggregates, shot and accepted trial identifiers, and failure or missing-record status. Physical-qubit order is not a substitute for the declared output order.
8. Test an observational rewrite
Section titled “8. Test an observational rewrite”In the worked example, suppose is immediately measured in the computational basis and no later quantum operation acts on it. Show that omitting the conditional and reporting preserves the ideal classical output. Give one change to the program that invalidates the rewrite.
Solution
Without the physical correction, the Bell correlations give . Therefore
which matches the computational-basis measurement after applying .
Returning as quantum data exposes the difference: without correction, branch returns rather than .
For a purely classical counterexample, append CNOT from to a fresh before the final measurements, and return both . Physical correction gives always. Omitting it and correcting only gives , so the joint output differs.
In contrast, adding only before the original Z measurement gives a uniform bit on both branches with or without correction. That special case does not detect the omitted frame; a different output must be checked.
9. Design a real-time error-correction profile
Section titled “9. Design a real-time error-correction profile”List the minimum IR features needed to represent a repeated stabilizer cycle with syndrome measurement, a bounded-latency decoder call, Pauli-frame update, and a fixed maximum number of rounds. Separate profile features from target properties.
Solution
Profile-level features include quantum and classical bit types, repeated or statically unrollable control, mid-circuit measurement, arrays or named collections of syndrome results, a decoder-call interface, conditional or frame-update operations, explicit outputs, and a way to attach deadline constraints. The profile should state whether the round count is compile-time constant and whether decoder arithmetic executes inside the controller or through an external real-time function.
Target properties include the available stabilizer-measurement primitives, active data and ancilla layout, operation durations, simultaneous-measurement capacity, reset support, acquisition routing, decoder and communication latency, instruction memory, and calibration epoch. Surface Code explains the code-cycle interpretation; the IR must express its operations, dependencies, and timing.
10. A loop that need not terminate
Section titled “10. A loop that need not terminate”A program measures a qubit in the Z basis and stops only when the result is 1; after result 0 it repeats the same measurement without changing the state. For input , what is the probability of termination? What changes if there is a fixed maximum number of attempts and a timeout output?
Solution
Termination occurs with probability on the first measurement. After result 0 the state is , so repetition never succeeds. The terminating map is , whose trace can be less than one. With a finite cap of at least one attempt and an explicit timeout, the two outcome maps are and . Their sum is trace preserving. Renormalizing successful runs alone would discard the termination probability and change the question.
References
Section titled “References”- A. W. Cross et al., “OpenQASM 3: A broader and deeper quantum assembly language,” ACM Transactions on Quantum Computing 3, Article 12 (2022), doi:10.1145/3505636.
- D. Ittah, T. Häner, V. Kliuchnikov, and T. Hoefler, “QIRO: A static single assignment-based quantum program representation for optimization,” ACM Transactions on Quantum Computing 3, Article 14 (2022), doi:10.1145/3491247; author’s manuscript.
- C. Lattner et al., “MLIR: Scaling compiler infrastructure for domain specific computation,” in 2021 IEEE/ACM International Symposium on Code Generation and Optimization, 2–14 (2021), doi:10.1109/CGO51591.2021.9370308.
- MLIR Project, MLIR Language Reference, official documentation, accessed 14 October 2026.
- OpenQASM contributors, OpenQASM Language Specification, gates, types, and circuit timing, accessed 14 October 2026. Live documentation may include features beyond a released backend’s supported version.
- A. Peduri and S. Bhat, “QSSA: An SSA-based IR for quantum computing,” in Proceedings of the 31st ACM SIGPLAN International Conference on Compiler Construction, 2–14 (2022), doi:10.1145/3497776.3517772; arXiv:2109.02409.
- QIR Alliance, Quantum Intermediate Representation Specification, official repository and Adaptive Profile, accessed 14 October 2026.
- P. Selinger and B. Valiron, “A lambda calculus for quantum computation with classical control,” Mathematical Structures in Computer Science 16, 527–552 (2006), doi:10.1017/S0960129506005238.