Skip to content

Circuit Intermediate Representations

A circuit intermediate representation, or circuit IR, is a machine-checkable representation of a quantum–classical program used between source-level intent and a target executable. It specifies not only a syntax, but also operations, types, control and data dependencies, validity rules, capability assumptions, and enough semantics to decide whether a compiler transformation preserves the declared behavior.

An IR may be a textual interchange language, an in-memory graph, a static-single-assignment data structure, a hierarchy of regions and dialects, or a timed instruction stream. A file format is not automatically an IR, and an IR is not automatically a portable interchange standard.

This page is the canonical home for representation contracts: IR levels, quantum and classical value models, gate-set and capability declarations, lowering invariants, and portability. Quantum Software Stack owns the complete application-to-evidence path. Circuit Model owns circuit semantics and resource conventions, while Universal Gate Sets owns universality and approximation by gate alphabets. Gate Decomposition owns exact and approximate synthesis algorithms and their cost certificates. Circuit Optimization owns behavior-preserving circuit rewrites and abstract depth reduction. Later pages own mapping, routing, error-aware compilation, and pulse control.

Why a Compiler Needs Several Representations

Section titled “Why a Compiler Needs Several Representations”

Source programs and controller executables serve incompatible purposes. Source-level structure should retain functions, loops, symbolic parameters, data types, approximation intent, and named outputs. A controller needs concrete resources, supported instructions, resolved durations, legal parallelism, and bounded-latency branches. Lowering all structure immediately makes analysis and optimization harder; retaining all abstraction until dispatch makes deterministic execution impossible.

A useful abstract description of an IR is

R=(O, T, C, M, W),\mathsf R = \bigl( \mathcal O,\, \mathcal T,\, \mathcal C,\, \mathcal M,\, \mathcal W \bigr),

where:

  • O\mathcal O is the operation vocabulary and its semantics;
  • T\mathcal T is the type and value system;
  • C\mathcal C describes control flow, data flow, timing, and concurrency;
  • M\mathcal M is semantic and provenance metadata;
  • W\mathcal W is the set of well-formedness and verification rules.

A compiler judgment should be read schematically as

R;Π;Θ⊢P:τout,\mathsf R;\Pi;\Theta \vdash P:\tau_{\mathrm{out}},

where PP is the program, Π\Pi is a capability profile, Θ\Theta is a versioned target contract, and τout\tau_{\mathrm{out}} is the output schema. Leaving Π\Pi, Θ\Theta, or τout\tau_{\mathrm{out}} implicit is a common source of false portability claims.

There is no uniquely best IR for every stage. A compiler usually benefits from a family of forms:

  1. a structured quantum–classical form near the source language;
  2. a circuit, graph, or SSA form for analysis and transformation;
  3. an encoded or logical form when error correction is introduced;
  4. a target-native circuit with placement and instruction constraints;
  5. a timed form for controller code generation;
  6. an executable package with an explicit input and output contract.

Not every pipeline contains all six, and one multi-level language can cover several of them. The levels are semantic responsibilities, not required file extensions.

Progressive lowering from structured quantum–classical intent to a timed executable while semantic checks and provenance accompany every IR boundary

Lowering specializes a program toward a target. Each boundary must state what is preserved, what becomes concrete, and what information is intentionally discarded. Version, profile, units, output order, source maps, pass history, and target epoch remain part of the artifact contract.

A successful parse proves only that a byte sequence matches a grammar. It does not prove that names resolve, types agree, quantum resources are used legally, the program belongs to a supported profile, or a target can execute it. The validation chain is closer to

b→parseA→verifyPtyped,Ptyped→profilePΠ→legalizePΘ→codegenE.\begin{aligned} b &\xrightarrow{\mathrm{parse}} A \xrightarrow{\mathrm{verify}} P_{\mathrm{typed}},\\ P_{\mathrm{typed}} &\xrightarrow{\mathrm{profile}} P_{\Pi} \xrightarrow{\mathrm{legalize}} P_{\Theta} \xrightarrow{\mathrm{codegen}} E. \end{aligned}

Here bb is serialized input, AA is an abstract syntax tree, PΠP_\Pi is profile-conformant IR, PΘP_\Theta is target-legal IR, and EE is an executable artifact. Each arrow can fail for a different reason and should produce a different diagnostic.

The distinction is operational:

CheckQuestion answeredExample failure
lexical and syntacticCan the text be parsed?missing delimiter or malformed literal
name and typeAre symbols, arities, widths, and units consistent?two-qubit gate given one operand
structuralDo dominance, lifetime, region, and resource rules hold?quantum value consumed twice
semanticDoes every operation have defined behavior?gate name has no imported definition
profileDoes the program use an allowed feature subset?adaptive branch in a terminal-measurement profile
targetCan this target realize the operations and constraints?disabled coupler or unsupported reset
executableCan the controller load and run the package?instruction-memory or deadline violation
resultCan outputs be decoded as declared?missing bit order or incompatible result schema

An interchange claim should therefore identify which checks are normative. The official OpenQASM grammar, for example, explicitly distinguishes syntactic validity from semantic correctness. The QIR specification similarly uses profiles and module metadata to constrain which LLVM-level programs a backend is expected to accept.

A mature circuit IR should make the following information representable or attach it through a normative companion contract.

ConcernRequired informationFailure if omitted
quantum dataresource identity or value, type, lifetime, alias rulesaccidental reuse, aliasing, or wrong subsystem
classical databit width, signedness, precision, mutability, lifetimecontroller-dependent arithmetic
operationsname, arity, parameter domains, semantics, side effectssame spelling with different behavior
measurementbasis or instrument, result type, state-update conventionambiguous branches and outputs
reset and releasepostcondition and failure behaviorstale state reused as fresh state
control flowbranches, loops, calls, termination assumptionscompile-time loop mistaken for real-time control
data flowdefinitions, uses, dependencies, memory effectsillegal reordering
gate conventionstensor order, angle units, global phase policysilently different unitaries
timingduration units, alignment, barriers, concurrency intentinvalid or physically different schedule
input and outputnames, shapes, ordering, accepted trials, schemacorrect execution decoded incorrectly
approximationmetric, tolerance, allocation of error budgetunqualified synthesis change
provenancelanguage version, includes, passes, target epoch, source mapirreproducible or unauditable result

Some metadata is advisory, such as a display label. Other metadata changes meaning: a radians-versus-degrees tag, endianness declaration, calibration epoch, or measurement-output permutation cannot be dropped as decoration. An IR specification should distinguish the two classes.

The visible gate diagram is only one possible data structure. Different forms expose different compiler facts.

A static circuit can be represented as an ordered list or as a dependency graph

D=(V, Eq∪Ec∪Et).D = \bigl( V,\, E_q\cup E_c\cup E_t \bigr).

The vertices VV are operations. Quantum-resource edges EqE_q order uses of the same subsystem, classical edges EcE_c carry computed values, and timing or conflict edges EtE_t impose additional order. A schedule s(v)s(v) with duration d(v)d(v) must satisfy

s(v)+d(v)≤s(w),s(v)+d(v)\leq s(w),

for every required edge (v,w)(v,w).

A directed acyclic graph exposes commuting or independent regions and is natural for a statically expanded circuit. It is not by itself enough for a repeat-until-success loop, a measurement-conditioned branch, recursion, or an operation whose duration is unresolved.

A control-flow graph consists of basic blocks and directed transfers:

Gcfg=(B,EB).G_{\mathrm{cfg}}=(B,E_B).

Each block contains operations with one entry; a terminator chooses successor blocks. Measurement outcomes can therefore control later quantum operations. Structured regions retain higher-level constructs such as if, for, or a calibration block without immediately flattening them into jumps.

The distinction between compile-time and run-time control is essential. A loop whose trip count is known can be unrolled before dispatch. A loop whose exit condition depends on a measurement requires controller support, a termination policy, and often a latency bound while quantum data remain coherent.

In static single assignment form, each SSA value has exactly one definition. Classical SSA makes definitions, uses, and merges explicit. Quantum IRs use two broad models:

  • opaque mutable handles: a qubit identifier refers to a runtime resource, while operation side effects and memory-effect rules enforce ordering;
  • functional quantum values: an operation consumes input quantum values and returns new SSA values representing the same evolving resources.

In the second model, a two-qubit operation has the schematic form

(q1′,q2′)=CX(q1,q2),(q_1',q_2') = \mathsf{CX}(q_1,q_2),

and later operations use q1′q_1' and q2′q_2', not the consumed inputs. A simple linearity condition is

Nconsume(qi)≤1N_{\mathrm{consume}}(q_i)\leq 1

for each live quantum SSA value, with branch and region rules handling mutually exclusive uses. This is a static ownership rule, not a claim that a physical qubit is destroyed and recreated by every gate.

The no-cloning theorem does not select one syntax. It does rule out treating an unknown quantum value like an ordinary copyable SSA integer. A verifier must prevent illegal duplication through def-use chains, aliases, block arguments, arrays, and function calls. Linear and affine type systems, as well as quantum-specific SSA designs such as QSSA and QIRO, provide different ways to make this discipline checkable.

Multi-level frameworks retain several abstraction-specific operation sets in one infrastructure. In MLIR terminology, operations produce typed values and are organized into blocks and regions; dialects define operation families, traits, interfaces, and verification rules. A quantum dialect can coexist with arithmetic, control-flow, tensor, and target dialects.

The benefit is controlled progressive lowering. The risk is assuming that a shared container supplies shared quantum semantics. An MLIR module is only as portable as the dialect definitions, versions, conversion contracts, and registered verifiers it depends on.

For a closed unitary fragment PP, its denotation is

⟦P⟧(ρ)=UPρUP†.\llbracket P\rrbracket(\rho) = U_P\rho U_P^\dagger.

If no surrounding construct can observe global phase, exact circuit equivalence permits

UQ=eiϕUP.U_Q=e^{i\phi}U_P.

Approximate synthesis may instead require

min⁡ϕ∥UQ−eiϕUP∥≤ϵsynth,\min_{\phi} \left\| U_Q-e^{i\phi}U_P \right\| \leq \epsilon_{\mathrm{synth}},

with a declared norm and error budget. This criterion is not enough for a dynamic program with measurement, reset, classical output, or measurement-conditioned control.

A dynamic program can be described by a quantum instrument {IyP}y\{\mathcal I_y^P\}_y, where each IyP\mathcal I_y^P is completely positive and trace-nonincreasing, and

∑yIyP\sum_y \mathcal I_y^P

is trace preserving on valid inputs. The corresponding classical–quantum output channel is

EP(ρ)=∑y∣y⟩⟨y∣C⊗IyP(ρ).\mathcal E_P(\rho) = \sum_y |y\rangle\langle y|_C \otimes \mathcal I_y^P(\rho).

A lowering LL may add ancillas, physical measurements, frame updates, or internal records. Correctness is therefore observational:

dist⁡(ΠoutEL(P),EP)≤ϵdecl,\operatorname{dist} \left( \Pi_{\mathrm{out}}\mathcal E_{L(P)}, \mathcal E_P \right) \leq \epsilon_{\mathrm{decl}},

where Πout\Pi_{\mathrm{out}} discards or decodes internal artifacts and ϵdecl\epsilon_{\mathrm{decl}} separates intentional approximation from physical noise. Quantum Instruments owns the instrument formalism. Noise in Quantum Information owns the distinction between compiler models and implemented noisy channels.

Compiler correctness consequently has several layers:

  1. well-formedness preservation: the output IR passes its verifier;
  2. semantic preservation: declared outputs agree exactly or within a stated metric;
  3. resource refinement: newly introduced ancillas, operations, and timing are valid for the target;
  4. contract preservation: input, output, failure, and acceptance conditions remain explicit;
  5. provenance preservation: the lowered artifact can be traced to source, pass configuration, specification version, and target state.

Testing only unitary matrices can miss bit-order errors, dropped measurement records, altered postselection, or branch-dependent state updates.

A gate set is not a list of attractive names. An operation needs a signature and semantics, schematically

g:(τq,1,…,τq,k;τα,1,…,τα,r)⟶(τq,1′,…,τq,k′),\begin{aligned} g:\quad &\bigl( \tau_{q,1},\ldots,\tau_{q,k}; \\[-2pt] &\qquad \tau_{\alpha,1},\ldots,\tau_{\alpha,r} \bigr) \\ &\longrightarrow \bigl( \tau_{q,1}',\ldots,\tau_{q,k}' \bigr), \end{aligned}

together with ⟦g⟧\llbracket g\rrbracket, parameter domains, units, side effects, and legality conditions. The same identifier can denote different matrices, tensor-order conventions, phase conventions, or calibrated implementations in different ecosystems.

Five related objects should remain distinct:

ObjectWhat it fixesWhat it leaves open
gate alphabetnamed unitary operations and parameter semanticsmeasurement, reset, control flow, target availability
quantum instruction setcallable quantum operations, possibly including irreversible actionswhich program structures a backend accepts
capability profileallowed types, control flow, allocation, outputs, and optional featurestarget topology and current resource state
target modelactive resources, connectivity, native instruction instances, timing, conflictscalibrated waveform implementation unless included
calibration librarybinding from operations to pulses, frames, acquisitions, or microcodehigher-level program intent

Universality answers whether a family can approximate desired unitaries. It does not imply that a backend accepts mid-circuit measurement, dynamic allocation, arbitrary loops, real-time floating-point arithmetic, or a particular output schema. Conversely, a profile can permit adaptive control without prescribing one universal gate alphabet.

A defensible gate entry records at least:

  • operation identity and namespace;
  • arity and operand type;
  • parameter type, unit, range, and precision;
  • matrix or channel convention when target independent;
  • control, inverse, and power semantics;
  • virtual-versus-physical operand status;
  • edge, zone, or module availability;
  • duration and concurrency constraints when target bound;
  • calibration and specification version.

Single-Qubit Gates develops rotation and phase conventions. Multi-Qubit Gates develops operand order, entangling capability, measured primitives, and native-versus-compiled contracts.

Let PiP_i be a program in representation Ri\mathsf R_i, and let Σi\Sigma_i carry proofs, semantic metadata, and provenance. A lowering pass has the form

(Pi,Σi)⇒Θ,viLi(Pi+1,Σi+1),Ri⟶Ri+1.\begin{aligned} (P_i,\Sigma_i) &\xRightarrow[\Theta,v_i]{L_i} (P_{i+1},\Sigma_{i+1}),\\ \mathsf R_i &\longrightarrow \mathsf R_{i+1}. \end{aligned}

The pass version viv_i and target contract Θ\Theta are part of the result. Each pass should declare:

  • input and output dialects or schemas;
  • preconditions and required analyses;
  • invariants and approximation metric;
  • features introduced, resolved, or removed;
  • target assumptions;
  • diagnostics for unsupported cases;
  • source-map and provenance behavior.

Typical changes include:

Earlier representationLowering decisionInformation no longer freely changeable
structured loops and callsinline, specialize, or unrolloriginal hierarchy and compactness
symbolic gate operationschoose decomposition and basishigh-level gate identity
virtual qubitsplace on target resourcestarget independence
unconstrained interactionsinsert routing operationsoriginal depth and error ledger
commuting operationschoose a schedulemuch of the reordering freedom
symbolic durationsresolve target time unitsdevice-independent timing
logical operationschoose code gadgets and factoriescode independence
named measurementsassign acquisition channels and result slotsabstract output location

Information should be erased only after every pass that needs it has run. Conversely, preserving a stale high-level annotation after a transformation can be worse than removing it: metadata that claims an operation is logical or unitary after it has been replaced by measurement and feedforward is misleading.

Lowering need not be one-way in tooling. A disassembler can reconstruct a higher-level view, and a serializer can round-trip equivalent structures. Neither operation generally recovers discarded intent. Reconstructed loops, gate names, or source variables are hypotheses unless provenance retained them.

“Portable” should always be qualified.

LevelClaimWhat can still fail
syntactic portabilityanother tool parses the artifactname, type, and semantic checks
semantic portabilityoperations and outputs have shared meaningunsupported profile features
profile portabilitybackend advertises every required capabilitytarget topology, limits, and timing
target portabilitycompiler can legalize the programcontroller memory, deadlines, and calibration
operational portabilityexecution produces the declared recordsnoise, drift, acceptance, and schema handling
behavioral portabilitydeclared output behavior agrees within toleranceunequal resources or statistical uncertainty
reproducible portabilityresult can be regenerated and auditedunavailable versions, targets, or calibration state

Let Cap⁡(P)\operatorname{Cap}(P) be the capabilities required by a program and Cap⁡(B)\operatorname{Cap}(B) those advertised by a backend. A necessary profile condition is

Cap⁡(P)⊆Cap⁡(B).\operatorname{Cap}(P) \subseteq \operatorname{Cap}(B).

Target execution additionally requires

WellTyped⁡(P)∧Legal⁡(P,ΘB)∧Fits⁡(P,ΘB).\begin{aligned} &\operatorname{WellTyped}(P) \\ {}\land{}& \operatorname{Legal}(P,\Theta_B) \\ {}\land{}& \operatorname{Fits}(P,\Theta_B). \end{aligned}

Capability inclusion is not a performance guarantee. Two backends can execute the same semantic program while implementing different noisy channels, latencies, shot policies, or result acceptance rules.

A portable package should pin or declare:

  1. language and serialization version;
  2. capability profile and optional features;
  3. imported libraries and gate definitions;
  4. parameter units, numeric widths, and rounding;
  5. qubit, tensor-factor, and classical-bit order;
  6. input, output, failure, and postselection schemas;
  7. target assumptions and any target-specific operations;
  8. pass pipeline and approximation tolerances;
  9. conformance tests, checksums, and provenance records.

The package can still be source portable without being binary portable. That is normal; it should not be described as “run anywhere” without the missing qualification.

The following are representative, not a mandatory pipeline. Version statements are current at the page review date and should be rechecked against the linked specifications.

Representation or substratePrincipal roleImportant boundary
OpenQASM 3.1standalone, multi-level language for extended circuits, classical control, timing, and calibration constructsparsing the language does not imply support for every construct or calibration grammar
QIR 2.0LLVM-based representation using quantum instruction-set and runtime interfacesa profile, QIS, output schema, and backend define the executable subset
QIR Base and Adaptive profilescoherent capability subsets, from terminal measurement to measurement-conditioned control and optional richer featuresprofile support is separate from the chosen gate or quantum instruction set
Quilinstruction language for a quantum abstract machine with quantum and classical memoryabstract-machine portability does not bind one controller or calibration state
LLVM IR and MLIRestablished SSA and multi-level compiler substratesthe substrate supplies structure and tooling, not quantum semantics by itself
QSSA and QIROresearch IRs using quantum-aware SSA and MLIR-based verification or optimizationtheir design results do not make every SSA encoding interchangeable
eQASMexecutable quantum ISA with timing and controller concernsa concrete architecture study is not a universal interchange standard

OpenQASM and QIR illustrate different choices. OpenQASM defines a quantum-focused language with its own types and circuit constructs. QIR defines how quantum programs are represented within LLVM IR and deliberately does not require every target to implement every runtime function or one universal gate set. Its Base Profile supports unitary sequences followed by terminal measurement and declared output; its Adaptive Profile adds mid-circuit measurement and forward branching, with further capabilities advertised separately.

These differences are useful. They prevent a format name from concealing the actual capability contract.

Worked Example: A Measurement-Conditioned Correction

Section titled “Worked Example: A Measurement-Conditioned Correction”

Consider two qubits initialized in ∣00⟩|00\rangle. Apply HH to q0q_0, then CNOT from q0q_0 to q1q_1, measure q0q_0 in the computational basis, and apply XX to q1q_1 when the result mm is one.

A language-neutral, functional SSA sketch is

func @prepare_and_correct(%q0: qubit, %q1: qubit)
-> (bit, qubit) {
%q0a = q.h %q0
%q0b, %q1a = q.cx %q0a, %q1
%m = q.measure_z %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 syntax from a named standard. Its consume-and-return convention exposes the quantum def-use chain. A side-effectful IR could instead retain the identifiers q0 and q1 and model the operations as ordered effects.

Before measurement,

∣Φ+⟩=∣00⟩+∣11⟩2.|\Phi^+\rangle = \frac{|00\rangle+|11\rangle}{\sqrt2}.

The measurement result is uniform. Conditioned on mm, the second qubit is ∣m⟩|m\rangle; the correction XmX^m maps it to ∣0⟩|0\rangle. The declared output is therefore

ρout=12 ∣0⟩⟨0∣m⊗∣0⟩⟨0∣q1+12 ∣1⟩⟨1∣m⊗∣0⟩⟨0∣q1.\begin{aligned} \rho_{\mathrm{out}} =\frac12\, |0\rangle\langle0|_m &\otimes |0\rangle\langle0|_{q_1}\\ +\frac12\, |1\rangle\langle1|_m &\otimes |0\rangle\langle0|_{q_1}. \end{aligned}

The IR and its verifier must preserve:

  • that %m is a measurement result, not an arbitrary host Boolean;
  • that the two branches are mutually exclusive;
  • that each branch yields exactly one live version of q1q_1;
  • that the merge value dominates later uses;
  • that the output record labels and orders mm correctly;
  • that the selected profile permits mid-circuit measurement and feedforward;
  • that the target can make the decision before the next coherence-sensitive operation.

Suppose the only final use of q1q_1 is a computational-basis measurement nn. Then one implementation may omit the physical correction and report

ncorr=n⊕m=0n_{\mathrm{corr}} = n\oplus m =0

in the ideal circuit. This is observationally equivalent for that declared classical output. It is not equivalent when q1q_1 is returned as quantum data or enters a later operation that does not commute with the frame update. An IR that retains output intent permits the optimization; a gate list with no output contract does not.

An IR toolchain should reject unsupported programs before execution and detect miscompilation independently of a friendly visualization. A practical validation pipeline includes:

  1. version and dependency resolution for the core schema, dialects, includes, and gate libraries;
  2. parsing and deserialization with stable diagnostics;
  3. name, type, width, and unit checking;
  4. structural verification of dominance, regions, block arguments, lifetimes, aliasing, and quantum ownership;
  5. profile conformance with explicit optional capabilities;
  6. target legalization against active topology, instructions, timing, memory, and controller limits;
  7. pass verification using proofs, translation validation, equivalence checking, or differential simulation appropriate to the semantics;
  8. canonical serialization and hashing for artifact identity;
  9. result-schema validation before scientific postprocessing.

Full compiler verification is valuable but difficult. Translation validation checks a particular input-output pair for a pass or pipeline. For unitary fragments this may use symbolic rewriting, decision diagrams, or matrix comparison at small scale. Dynamic circuits require tests of outcome distributions and conditional states, not merely a unitary equivalence tool.

Round-trip tests should compare semantic IR, not byte-for-byte formatting, unless the format specifies canonical serialization. Unknown mandatory operations or metadata should cause a hard failure. Silently dropping them turns forward compatibility into semantic corruption.

A reproducible executable identity can be modeled as

id⁡(E)=H(bytes⁡(E),vspec,Π,L,P,Θepoch,τout),\begin{aligned} \operatorname{id}(E) =H\bigl(& \operatorname{bytes}(E), v_{\mathrm{spec}}, \Pi, \mathcal L,\\ &\mathcal P, \Theta_{\mathrm{epoch}}, \tau_{\mathrm{out}} \bigr), \end{aligned}

where L\mathcal L is the imported library set and P\mathcal P is the versioned pass pipeline. A source hash alone does not identify what ran.

  • Treating successful parsing as proof of semantic or target compatibility.
  • Calling every circuit file an IR without specifying operations, types, and validity rules.
  • Assuming that equal gate names imply equal matrices, parameter units, or operand order.
  • Confusing a universal gate set with a complete instruction or capability profile.
  • Treating virtual qubit indices as physical resource identities.
  • Applying unitary equivalence tests to programs with measurement, reset, postselection, or classical output.
  • Copying an SSA quantum value into two consuming uses because ordinary integers are copyable.
  • Lowering loops, symbolic gates, or output names before analyses that need them have run.
  • Retaining metadata after a pass has invalidated its meaning.
  • Dropping unknown mandatory metadata to make a newer artifact appear compatible.
  • Expressing dt, angle, or integer literals without a unit and width contract.
  • Reordering measurement records while preserving only a histogram shape.
  • Advertising “cross-platform” execution without pinning profile, libraries, target assumptions, and result schema.
  • Hashing source code but not the compiler, pass configuration, executable, or target epoch.

When evaluating a format or compiler IR, ask:

  1. What is the semantic level: algorithmic, logical, native, timed, pulse, or executable?
  2. Is it an internal data structure, a serialized interchange format, or both?
  3. Which quantum and classical types exist, and which are copyable?
  4. How are measurement, reset, release, and postselection represented?
  5. Is control flow structured, graph based, statically unrolled, or dynamic?
  6. What defines gate meanings, parameter units, tensor order, and global phase?
  7. Which profile or optional capabilities does the program require?
  8. How are target resources, timing, concurrency, and calibration attached?
  9. What exact or approximate equivalence must each lowering pass preserve?
  10. How are outputs named, ordered, validated, and connected to provenance?
  11. What happens when a consumer encounters an unknown operation or metadata field?
  12. Can the emitted artifact and result be reproduced from pinned inputs?

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 result contract: 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.

For a closed one-qubit program, let V=eiϕUV=e^{i\phi}U. Show that UU and VV produce the same density-operator channel. Then explain why replacing UU by VV inside a controlled operation is not generally harmless.

Solution

For any density operator ρ\rho,

VρV†=eiϕUρU†e−iϕ=UρU†.V\rho V^\dagger = e^{i\phi}U\rho U^\dagger e^{-i\phi} = U\rho U^\dagger.

The phase is global only when the operation acts unconditionally on the whole branch. A controlled version is

C(V)=∣0⟩⟨0∣⊗I+eiϕ∣1⟩⟨1∣⊗U.C(V) = |0\rangle\langle0|\otimes I + e^{i\phi}|1\rangle\langle1|\otimes U.

The factor eiϕe^{i\phi} 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.

Derive the output state of the worked measurement-conditioned correction from ∣00⟩|00\rangle. Verify both measurement probabilities and the conditional state of q1q_1.

Solution

After HH and CNOT,

∣Φ+⟩=∣00⟩+∣11⟩2.|\Phi^+\rangle = \frac{|00\rangle+|11\rangle}{\sqrt2}.

Computational-basis measurement of q0q_0 gives m=0m=0 or m=1m=1, each with probability 1/21/2. The corresponding state of q1q_1 is ∣0⟩|0\rangle or ∣1⟩|1\rangle. Applying XmX^m gives ∣0⟩|0\rangle in either branch. Retaining the classical record yields

ρout=12∑m=01∣m⟩⟨m∣⊗∣0⟩⟨0∣.\rho_{\mathrm{out}} = \frac12\sum_{m=0}^1 |m\rangle\langle m| \otimes |0\rangle\langle0|.

Discarding mm leaves ∣0⟩⟨0∣|0\rangle\langle0| on q1q_1, but that reduced state does not preserve the declared classical output.

Consider the functional quantum SSA fragment

%qa = q.h %q
%u = q.x %qa
%v = q.z %qa

Why 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 %u

which implements ZXHZXH. A conditional repair places the two uses in mutually exclusive branches and merges one yielded quantum value afterward. That implements either XHXH or ZHZH according to the branch condition. The two repairs are not semantically equivalent.

A program requires mid-circuit measurement, forward branching, reset, and 32-bit integer arithmetic. Backend AA supports all but reset. Backend BB 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

Cap⁡(P)={measure, branch,reset, int32},\operatorname{Cap}(P) = \left\{ \begin{array}{c} \mathrm{measure},\ \mathrm{branch}, \\ \mathrm{reset},\ \mathrm{int32} \end{array} \right\},

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 AA. It may also constant-fold, narrow, or move the integer computation to a near-time host if doing so preserves timing and semantics on backend BB. Those are compiler transformations with proof obligations, not permission to ignore the missing capabilities.

Two backends accept an instruction delay 20dt. Their controller sample periods are 0.5 ns0.5\,\mathrm{ns} and 2 ns2\,\mathrm{ns}. Compare the physical delays. What contract would be needed to preserve a 10 ns10\,\mathrm{ns} intent?

Solution

The physical durations are

20(0.5 ns)=10 ns,20(2 ns)=40 ns.\begin{aligned} 20(0.5\,\mathrm{ns})&=10\,\mathrm{ns},\\ 20(2\,\mathrm{ns})&=40\,\mathrm{ns}. \end{aligned}

The syntax is portable but the timing is target dependent. A portable source contract can express 10 ns10\,\mathrm{ns} 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.

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 source output contract.

In the worked example, suppose q1q_1 is immediately measured in the computational basis and no later quantum operation acts on it. Show that omitting the conditional XX and reporting n⊕mn\oplus m preserves the ideal classical output. Give one change to the program that invalidates the rewrite.

Solution

Without the physical correction, the Bell correlations give n=mn=m. Therefore

n⊕m=0,n\oplus m=0,

which matches the computational-basis measurement after applying XmX^m.

The rewrite fails if q1q_1 is returned as quantum data, if a later operation uses it coherently, or if the declared output includes the physical post-correction state rather than only the corrected classical bit. A later Hadamard followed by measurement is one concrete case where frame handling must be propagated rather than discarded.

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 owns the code-cycle and logical interpretation; the IR profile owns how those requirements are represented and checked.

The need for typed operations, explicit control and data flow, verifier contracts, target legalization, and provenance is durable compiler engineering. The best quantum value model, dialect boundaries, profile granularity, and cross-ecosystem interchange strategy remain active design questions.

At the August 2026 review date, the OpenQASM project identifies version 3.1 as current. The QIR specification describes QIR 2.0 and separates its Base and Adaptive profiles from the backend’s quantum instruction set. These are versioned projects, not timeless facts or proof of universal adoption. Compare specific pinned versions and conformance tests rather than format names alone.

  • Quantum Software Stack places IRs between application semantics, compilation, runtime control, hardware response, and evidence.
  • Circuit Model defines the ideal and dynamic circuit semantics an IR must preserve.
  • Quantum Circuit Simulation consumes those semantics and makes wire order, gate definitions, measurements, classical state, output type, precision, and approximation part of an executable backend contract.
  • Resource Estimation Tools consumes versioned logical artifacts and preserves call graphs, gate levels, liveness, schedules, model assumptions, and qualified physical outputs.
  • Universal Gate Sets separates exact and approximate universality from backend capability.
  • Gate Decomposition turns structured or dense unitary operations into verified circuits over a declared alphabet.
  • Circuit Optimization uses typed dependencies, semantic fences, parameter domains, and provenance to simplify circuits without changing their declared behavior.
  • Qubit Mapping and Routing consumes topology, direction, resource, timing, and output-map data from a target-aware IR.
  • Error-Aware Compilation consumes calibration provenance, uncertainty, context, and validity intervals carried by target-aware IRs.
  • Pulse-Level Control lowers target-bound operations into ports, frames, waveform plays, acquisitions, timing constraints, and versioned pulse certificates.
  • Calibration Loops defines how parent versions, staleness, candidate snapshots, acceptance evidence, and atomic publication govern those target records.
  • Hardware Overview defines the versioned target information consumed during legalization.
  • Control, Readout, and Calibration owns waveform delivery, acquisition inference, physical tune-up dependencies, and feedback deadlines.
  • Claims, Hype, and Evidence Standards explains why source, executable, target epoch, result schema, and postprocessing support different scientific claims.
  1. A. W. Cross et al., “OpenQASM 3: A broader and deeper quantum assembly language,” ACM Transactions on Quantum Computing 3, 12 (2022), doi:10.1145/3505636.
  2. OpenQASM contributors, OpenQASM Language Specification, current and versioned specifications, official repository.
  3. QIR Alliance, Quantum Intermediate Representation Specification, including QIR version compatibility, quantum instruction-set interfaces, runtime contracts, and output schemas, official specification.
  4. QIR Alliance, Base Profile and Adaptive Profile, official profile specifications.
  5. R. S. Smith, M. J. Curtis, and W. J. Zeng, “A Practical Quantum Instruction Set Architecture,” arXiv:1608.03355 (2016), arXiv:1608.03355.
  6. LLVM Project, LLVM Language Reference Manual, official documentation.
  7. C. Lattner et al., “MLIR: Scaling Compiler Infrastructure for Domain Specific Computation,” 2021 IEEE/ACM International Symposium on Code Generation and Optimization, 2–14 (2021), doi:10.1109/CGO51591.2021.9370308.
  8. MLIR Project, MLIR Language Reference, official documentation.
  9. A. Peduri and S. Bhat, “QSSA: An SSA-Based IR for Quantum Computing,” Proceedings of the 31st ACM SIGPLAN International Conference on Compiler Construction, 2–14 (2022), doi:10.1145/3497776.3517772.
  10. 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, 14 (2022), doi:10.1145/3491247.
  11. 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.
  12. J. Paykin, R. Rand, and S. Zdancewic, “QWIRE: A Core Language for Quantum Circuits,” Proceedings of POPL 2017, 846–858 (2017), doi:10.1145/3009837.3009894.
  13. X. Fu et al., “eQASM: An Executable Quantum Instruction Set Architecture,” 2019 IEEE International Symposium on High Performance Computer Architecture, 224–237 (2019), doi:10.1109/HPCA.2019.00040.
  14. A. JavadiAbhari et al., “ScaffCC: Scalable Compilation and Analysis of Quantum Programs,” Parallel Computing 45, 2–17 (2015), doi:10.1016/j.parco.2014.12.001.
  15. T. Häner et al., “A software methodology for compiling quantum programs,” Quantum Science and Technology 3, 020501 (2018), doi:10.1088/2058-9565/aaa5cc.
  16. F. T. Chong, D. Franklin, and M. Martonosi, “Programming languages and compiler design for realistic quantum hardware,” Nature 549, 180–187 (2017), doi:10.1038/nature23459.