MQT Compiler Collection

The MQT Compiler Collection translates and optimizes quantum programs for simulators, hardware, and other compilers. It handles quantum operations together with classical calculations, branches, and loops, including feedback from measurements.

The compiler uses MLIR and LLVM internally. You can work with it through any of three interfaces; all use the same program representations and transformations:

Interface

Entry point

Command line

mqt-core compile, with examples below

Python

mqt.core.mlir

C++

Source-tree compiler API

For a guided explanation of the representations and transformations, start with the getting-started tutorial. This guide documents the interfaces and options for applying those concepts.

The Python examples below accept source strings, .qasm, .mlir, and .jeff files, Qiskit QuantumCircuit objects, and typed compiler programs. Select an output format to choose where compilation stops and which program type is returned, or use the default selection rules. When compilation takes a typed MLIR program, it transfers ownership of that program to the compiler: the original object becomes invalid, even if compilation fails. Set copy=True to keep it available for another use. The same rule applies to conversions between typed MLIR programs. Strings, paths, Qiskit circuits, and OpenQASM text programs remain reusable.

Install MQT Core and import the compiler interface:

1from mqt.core.mlir import OutputFormat, QCProgram, QIRProfile, compile_program

To compile for a configured QDMI device, see target compilation.

Compile an OpenQASM program

The following OpenQASM program prepares a Bell state and records the outcome of measuring both qubits.

 1bell_qasm = """OPENQASM 3.0;
 2include "stdgates.inc";
 3
 4qubit[2] q;
 5bit[2] result;
 6
 7h q[0];
 8cx q[0], q[1];
 9result = measure q;
10"""
11
12compiled = compile_program(bell_qasm, output=OutputFormat.QC)
13print(compiled.ir)
module {
  func.func @main() -> !cbit.reg<2> attributes {mqt.entry_point} {
    %c1 = arith.constant 1 : index
    %c0 = arith.constant 0 : index
    %c2 = arith.constant 2 : index
    %alloc = memref.alloc() {mqt.register_name = "q"} : memref<2x!qc.qubit>
    %result = cbit.alloc(#cbit.init<undefined>) {mqt.register_name = "result"} : !cbit.reg<2>
    %q = memref.load %alloc[%c0] : memref<2x!qc.qubit>
    qc.h %q : !qc.qubit
    %q_0 = memref.load %alloc[%c1] : memref<2x!qc.qubit>
    qc.ctrl(%q) targets (%q_2 = %q_0) {
      qc.x %q_2 : !qc.qubit
      qc.yield
    } : {!qc.qubit}, {!qc.qubit}
    %b = qc.measure %q : !qc.qubit -> i1
    cbit.store %b, %result[%c0] : !cbit.reg<2>
    %b_1 = qc.measure %q_0 : !qc.qubit -> i1
    cbit.store %b_1, %result[%c1] : !cbit.reg<2>
    memref.dealloc %alloc : memref<2x!qc.qubit>
    return %result : !cbit.reg<2>
  }
}

OutputFormat.QC runs the standard optimization pipeline and returns a QCProgram. Its ir property exposes the textual MLIR representation for inspection and debugging. Programs do not need to be written in MLIR to use the compiler.

For versionless OpenQASM text, use compile_program(QCProgram.from_openqasm_str(source)). Automatic source-string detection uses the OPENQASM header; see OpenQASM input and output for supported input syntax.

Inspect a quantum program

Use inspect() on a QCProgram or QCOProgram to obtain a snapshot of resource information and static operation counts:

 1info = compiled.inspect()
 2print("Qubits:", info.num_qubits)
 3print("Control flow:", info.has_control_flow)
 4print("Static device sites:", info.static_qubits)
 5print("Gates:", info.num_gates)
 6print("Single-qubit gates:", info.num_single_qubit_gates)
 7print("Two-qubit gates:", info.num_two_qubit_gates)
 8print("Gates by operation:", info.gate_counts)
 9print("Entry-point control flow:", info.control_flow_counts)
10print("All MLIR operations:", info.operation_counts)
11
12qco = compiled.to_qco()
13print("QCO two-qubit gates:", qco.inspect().num_two_qubit_gates)
Qubits: 2
Control flow: False
Static device sites: []
Gates: 4
Single-qubit gates: 3
Two-qubit gates: 1
Gates by operation: {'cx': 1, 'h': 1, 'measure': 2}
Entry-point control flow: {}
All MLIR operations: {'arith.constant': 3, 'builtin.module': 1, 'cbit.alloc': 1, 'cbit.store': 2, 'func.func': 1, 'func.return': 1, 'memref.alloc': 1, 'memref.dealloc': 1, 'memref.load': 2, 'qc.ctrl': 1, 'qc.h': 1, 'qc.measure': 2, 'qc.x': 1, 'qc.yield': 1}
QCO two-qubit gates: 1

For an individual count, use num_gates(), num_single_qubit_gates(), num_two_qubit_gates(), gate_counts(), control_flow_counts(), or operation_counts() directly on the program. These methods compute only the requested count. operation_counts() is available on every MLIR program type.

Core’s static gate count describes the entry-point IR. Each gate in a structured control-flow region counts once, regardless of runtime paths or loop iterations. This metric counts unitary operations, measurements, and resets. Measurements and resets count as single-qubit gates. Barriers are excluded from gate counts and appear in operation_counts. Each modifier or unitary call counts as one gate. Controls on a single primitive gate add a c per control: cx, cz, crx, cswap, or ccx. Other single-gate modifiers retain their structure: inv(h), pow(rx), ctrl(inv(x)), or ctrl(2,inv(x)) for two controls. Parameters, including power exponents, do not split histogram buckets. Modifiers with multiple body gates or unused target operands use ctrl, inv, or pow. Calls use the callee name. Explicit global-phase operations count under gphase.

control_flow_counts counts entry-point branch and region-control operations by their full MLIR names, such as scf.for, scf.while, scf.if, or qco.if. Every region counts once; callees are not expanded and region terminators such as scf.yield are excluded.

operation_counts gives a full structural overview by MLIR operation name. It includes the root module, helper functions, modifier bodies, terminators, and nested modules. A controlled X therefore contributes both qc.ctrl and qc.x to this histogram, while contributing one cx to gate_counts. Its scope matches MLIR’s print-op-stats pass.

num_qubits counts allocated qubits, or distinct static device site IDs. It is None when there is no entry point, the width is unknown, or a size calculation overflows. Runtime-sized allocations and quantum entry-point inputs have unknown width. Site IDs need not be contiguous: a program using only site 5 has one qubit and static_qubits == [5]. Resource inspection and has_control_flow include helper functions and exclude nested modules. These resource counts describe declared capacity rather than peak live width or the original layout width.

C++ API

In C++ module passes, use getAnalysis<mlir::QuantumProgramAnalysis>().info() from mqt/Compiler/Programs.h to share inspection results. MLIR manages the cache between passes. Read-only passes can preserve this cache; passes that change the reported information must not preserve it. Direct IR edits require explicit invalidation. Calling inspect() always computes fresh results.

For gate dependencies, MLIR provides getForwardSlice and getBackwardSlice in mlir/Analysis/SliceAnalysis.h.

Bind program parameters

QC and QCO programs expose named f64 scalar and fixed-length, one-dimensional array inputs through parameters. Use bind_parameters to bind all or some inputs in place, or use copy=True to return an independent bound program:

 1from qiskit import QuantumCircuit
 2from qiskit.circuit import Parameter
 3
 4circuit = QuantumCircuit(1)
 5circuit.ry(Parameter("theta"), 0)
 6parameterized = QCProgram.from_qiskit(circuit)
 7assert parameterized.parameters == ["theta"]
 8bound = parameterized.bind_parameters({"theta": 0.5}, copy=True)
 9assert bound.parameters == []
10assert parameterized.parameters == ["theta"]

OpenQASM 3 input float and input float[64] declarations use the same named input API. Both frontends can retain symbolic f64 parameters through QC and QCO transformations. Partial binding preserves unbound inputs and their source identities. For an array input, pass a sequence or NumPy array, for example program.bind_parameters({"angles": [0.1, 0.2]}). Each array must have the expected length and contain only finite values.

Input validation leaves the program unchanged on failure. Binding folds expressions using the supplied values and preserves remaining inputs, including unused ones. Folding failures may leave the program modified; bind a copy to preserve the original. Bind array inputs before OpenQASM export; QIR requires all parameters to be bound.

Select an output format

With no target or an explicit CompilerTarget, omitting output preserves the input’s program family:

Input

Default result

Qiskit QuantumCircuit

QuantumCircuit

QCProgram, QC MLIR text, or .mlir file

QCProgram

QCOProgram

Optimized QCOProgram

JeffProgram or .jeff file

JeffProgram

OpenQASMProgram, OpenQASM text, or .qasm file

OpenQASMProgram

A QDMI backend, device, registered device ID or TargetEnvironment defaults to a CompiledProgram containing the serialized program and its execution format. Other Qiskit backends and targets default to a QuantumCircuit.

An explicit output selects the representation independently of the input family and target:

Purpose

Output format

Result type

Inspect frontend translation

OutputFormat.QC_IMPORT

QCProgram

Inspect QCO immediately after conversion

OutputFormat.QCO

QCOProgram

Inspect QCO after optimization

OutputFormat.QCO_OPTIMIZED

QCOProgram

Obtain the optimized circuit

OutputFormat.QC

QCProgram

Obtain a Qiskit circuit

OutputFormat.QISKIT

QuantumCircuit

Serialize a Qiskit-compatible binary circuit

OutputFormat.QPY

bytes

Emit an optimized OpenQASM program

OutputFormat.OPENQASM3

OpenQASMProgram

Emit IQM JSON for a target

OutputFormat.IQM_JSON

IQMJSONProgram

Convert to the jeff dialect

OutputFormat.JEFF

JeffProgram

Generate QIR

OutputFormat.QIR_BASE or OutputFormat.QIR_ADAPTIVE

QIRProgram

The raw QC_IMPORT and QCO checkpoints stop before target compilation and cannot be combined with target. A QDMI target with no explicit output returns a CompiledProgram in an automatically selected native format. To select an exact execution format, use TargetEnvironment.from_device. See Compile for a QDMI device for execution-format selection and submission.

For example, select optimized QCO to inspect the representation after the default QCO pass pipeline:

1optimized = compile_program(bell_qasm, output=OutputFormat.QCO_OPTIMIZED)
2print(optimized.ir)
module {
  func.func @main() -> !cbit.reg<2> attributes {mqt.entry_point} {
    %c1 = arith.constant 1 : index
    %c0 = arith.constant 0 : index
    %c2 = arith.constant 2 : index
    %q = qtensor.alloc(%c2) {mqt.register_name = "q"} : tensor<2x!qco.qubit>
    %result = cbit.alloc(#cbit.init<undefined>) {mqt.register_name = "result"} : !cbit.reg<2>
    %qs, %q_0 = qtensor.extract %q[%c0] : tensor<2x!qco.qubit>
    %q_1 = qco.h %q_0 : !qco.qubit
    %qs_2, %q_3 = qtensor.extract %qs[%c1] : tensor<2x!qco.qubit>
    %controls_out, %targets_out = qco.ctrl(%q_1) targets (%q_9 = %q_3) {
      %q_10 = qco.x %q_9 : !qco.qubit
      qco.yield %q_10 : !qco.qubit
    } : ({!qco.qubit}, {!qco.qubit})
    %q_4, %b = qco.measure %controls_out : !qco.qubit
    cbit.store %b, %result[%c0] : !cbit.reg<2>
    %q_5, %b_6 = qco.measure %targets_out : !qco.qubit
    cbit.store %b_6, %result[%c1] : !cbit.reg<2>
    %qs_7 = qtensor.insert %q_4 into %qs_2[%c0] : tensor<2x!qco.qubit>
    %qs_8 = qtensor.insert %q_5 into %qs_7[%c1] : tensor<2x!qco.qubit>
    qtensor.dealloc %qs_8 : tensor<2x!qco.qubit>
    return %result : !cbit.reg<2>
  }
}

Emit OpenQASM

Request OPENQASM3 to emit the program after the normal QCO optimization and conversion back to QC:

1openqasm = compile_program(bell_qasm, output=OutputFormat.OPENQASM3)
2print(openqasm.source)
OPENQASM 3;
include "stdgates.inc";

bit[2] result;
qubit[2] q;

h q[0];
cx q[0], q[1];
result[0] = measure q[0];
result[1] = measure q[1];

The returned OpenQASMProgram owns its source and can write it directly:

1from pathlib import Path
2from tempfile import TemporaryDirectory
3
4with TemporaryDirectory() as directory:
5    path = Path(directory) / "bell.qasm"
6    openqasm.write(path)
7    reparsed = QCProgram.from_openqasm_file(path)
8
9assert reparsed.is_valid

Use to_openqasm3() to clean up and export the current QC program without QCO optimization. It consumes the program even on failure; set copy=True to preserve it. The resulting OpenQASMProgram can be passed directly to compile_program():

1recompiled = compile_program(openqasm, output=OutputFormat.QC_IMPORT)
2assert isinstance(recompiled, QCProgram)

The exporter supports structured control flow and runtime indices for program qubits and classical bits. Mapped physical qubits must have fixed indices. Export fails if the program still contains runtime safety assertions or undefined values that are still used. See OpenQASM input and output for the complete support table.

Use Qiskit circuits directly

Install mqt-core[qiskit] with a supported version listed in Qiskit compatibility. Compiling a QuantumCircuit for a Qiskit backend returns a circuit by default:

 1from qiskit import QuantumCircuit
 2from qiskit.providers.fake_provider import GenericBackendV2
 3
 4qiskit_bell = QuantumCircuit(2, 2)
 5qiskit_bell.h(0)
 6qiskit_bell.cx(0, 1)
 7qiskit_bell.measure(range(2), range(2))
 8
 9backend = GenericBackendV2(3, basis_gates=["sx", "x", "rz", "cx"])
10compiled_qiskit = compile_program(qiskit_bell, target=backend)
11assert isinstance(compiled_qiskit, QuantumCircuit)
12assert compiled_qiskit.num_qubits == backend.num_qubits
13assert compiled_qiskit.layout is not None

Omit target for target-independent optimization. Use from_qiskit() to work with the typed compiler programs directly. to_qiskit() and to_qiskit() export the current program and consume it by default, including when export fails. Pass copy=True to preserve it, and target=target to map compiler site IDs to physical qubits:

1direct = QCProgram.from_qiskit(qiskit_bell)
2restored = direct.to_qiskit(copy=True)
3assert direct.is_valid
4assert restored.count_ops() == qiskit_bell.count_ops()

See Qiskit compatibility for supported circuit features and translation limitations.

Run passes explicitly

QCProgram, QCOProgram, JeffProgram, and QIRProgram own their MLIR modules. Conversions between these MLIR-backed program objects consume their source by default, avoiding an implicit copy of a potentially large module. Pass copy=True when the source must remain available. OpenQASMProgram instead owns immutable source text and remains reusable when passed to compile_program.

cleanup() folds classical expressions, removes structural scaffolding and normalizes global phases. To cancel, combine or specialize quantum gates, use simplify-quantum or an optimization method such as merge_single_qubit_rotation_gates().

The following example keeps the imported QC program, applies transformations to QCO, and converts the result back to QC:

 1qc = QCProgram.from_openqasm_str(bell_qasm)
 2qco = qc.to_qco(copy=True)
 3qco.cleanup()
 4qco.merge_single_qubit_rotation_gates()
 5qco.lift_hadamards()
 6final_qc = qco.to_qc()
 7
 8assert qc.is_valid
 9assert not qco.is_valid
10print(final_qc.ir)
module {
  func.func @main() -> !cbit.reg<2> attributes {mqt.entry_point} {
    %c1 = arith.constant 1 : index
    %c0 = arith.constant 0 : index
    %c2 = arith.constant 2 : index
    %alloc = memref.alloc() {mqt.register_name = "q"} : memref<2x!qc.qubit>
    %result = cbit.alloc(#cbit.init<undefined>) {mqt.register_name = "result"} : !cbit.reg<2>
    %q = memref.load %alloc[%c0] : memref<2x!qc.qubit>
    qc.h %q : !qc.qubit
    %q_0 = memref.load %alloc[%c1] : memref<2x!qc.qubit>
    qc.ctrl(%q) targets (%q_2 = %q_0) {
      qc.x %q_2 : !qc.qubit
      qc.yield
    } : {!qc.qubit}, {!qc.qubit}
    %b = qc.measure %q : !qc.qubit -> i1
    cbit.store %b, %result[%c0] : !cbit.reg<2>
    %b_1 = qc.measure %q_0 : !qc.qubit -> i1
    cbit.store %b_1, %result[%c1] : !cbit.reg<2>
    memref.dealloc %alloc : memref<2x!qc.qubit>
    return %result : !cbit.reg<2>
  }
}

Architecture-independent QCO transformations can also be composed with MLIR’s textual pass-pipeline syntax. The same pass names and options are accepted by mqt-core compile:

1custom = compile_program(
2    bell_qasm,
3    output=OutputFormat.QCO_OPTIMIZED,
4    qco_pipeline="hadamard-lifting,merge-single-qubit-rotation-gates",
5)
6assert custom.is_valid
7print(custom.ir)
module {
  func.func @main() -> !cbit.reg<2> attributes {mqt.entry_point} {
    %c1 = arith.constant 1 : index
    %c0 = arith.constant 0 : index
    %c2 = arith.constant 2 : index
    %q = qtensor.alloc(%c2) {mqt.register_name = "q"} : tensor<2x!qco.qubit>
    %result = cbit.alloc(#cbit.init<undefined>) {mqt.register_name = "result"} : !cbit.reg<2>
    %qs, %q_0 = qtensor.extract %q[%c0] : tensor<2x!qco.qubit>
    %q_1 = qco.h %q_0 : !qco.qubit
    %qs_2, %q_3 = qtensor.extract %qs[%c1] : tensor<2x!qco.qubit>
    %controls_out, %targets_out = qco.ctrl(%q_1) targets (%q_9 = %q_3) {
      %q_10 = qco.x %q_9 : !qco.qubit
      qco.yield %q_10 : !qco.qubit
    } : ({!qco.qubit}, {!qco.qubit})
    %q_4, %b = qco.measure %controls_out : !qco.qubit
    cbit.store %b, %result[%c0] : !cbit.reg<2>
    %q_5, %b_6 = qco.measure %targets_out : !qco.qubit
    cbit.store %b_6, %result[%c1] : !cbit.reg<2>
    %qs_7 = qtensor.insert %q_4 into %qs_2[%c0] : tensor<2x!qco.qubit>
    %qs_8 = qtensor.insert %q_5 into %qs_7[%c1] : tensor<2x!qco.qubit>
    qtensor.dealloc %qs_8 : tensor<2x!qco.qubit>
    return %result : !cbit.reg<2>
  }
}

After rotation merging, the default pipeline groups controlled gates with the same ordered controls and targets. Canonicalization cancels named inverses and combines constant rotations inside each group, retaining controlled phase. Runtime bodies remain grouped for later binding or explicit fusion. Grouping follows the same linear wires within one block, across independent operations and scalar parameter computations. It preserves loop structure and does not combine across iterations. The standalone pass is combine-controlled-gates.

Pauli twirling is available as an opt-in textual pass. It supports CX, CZ, ECR, and iSWAP gates, keeps every inserted Pauli operation (including identities) explicit, and preserves the exact global phase. The seed defaults to 42:

1twirled = compile_program(bell_qasm, output=OutputFormat.QCO)
2twirled.run_pass_pipeline("pauli-twirl-2q-gates{seed=42}")
3print(twirled.ir)
module {
  func.func @main() -> !cbit.reg<2> attributes {mqt.entry_point} {
    %c2 = arith.constant 2 : index
    %q = qtensor.alloc(%c2) {mqt.register_name = "q"} : tensor<2x!qco.qubit>
    %result = cbit.alloc(#cbit.init<undefined>) {mqt.register_name = "result"} : !cbit.reg<2>
    %c0 = arith.constant 0 : index
    %qs, %q_0 = qtensor.extract %q[%c0] : tensor<2x!qco.qubit>
    %q_1 = qco.h %q_0 : !qco.qubit
    %c1 = arith.constant 1 : index
    %qs_2, %q_3 = qtensor.extract %qs[%c1] : tensor<2x!qco.qubit>
    %q_4 = qco.x %q_1 : !qco.qubit
    %q_5 = qco.y %q_3 : !qco.qubit
    %controls_out, %targets_out = qco.ctrl(%q_4) targets (%q_13 = %q_5) {
      %q_14 = qco.x %q_13 : !qco.qubit
      qco.yield %q_14 : !qco.qubit
    } : ({!qco.qubit}, {!qco.qubit})
    %q_6 = qco.y %controls_out : !qco.qubit
    %q_7 = qco.z %targets_out : !qco.qubit
    %q_8, %b = qco.measure %q_6 : !qco.qubit
    cbit.store %b, %result[%c0] : !cbit.reg<2>
    %q_9, %b_10 = qco.measure %q_7 : !qco.qubit
    cbit.store %b_10, %result[%c1] : !cbit.reg<2>
    %qs_11 = qtensor.insert %q_8 into %qs_2[%c0] : tensor<2x!qco.qubit>
    %qs_12 = qtensor.insert %q_9 into %qs_11[%c1] : tensor<2x!qco.qubit>
    qtensor.dealloc %qs_12 : tensor<2x!qco.qubit>
    return %result : !cbit.reg<2>
  }
}

Each invocation produces one deterministic realization; omitting the seed reproduces the realization selected by seed=42. To construct an ensemble for noise tailoring, transform copies with different seeds, execute them, and aggregate their measurement results. Different seeds are not guaranteed to produce distinct realizations.

This is a raw-QCO transformation. It does not place twirling relative to target mapping or synthesis and does not guarantee that the result uses a target’s native gate set. Target-aware twirling is not currently available through the target compilation pipeline.

Qubit reuse reduces the number of physical qubits needed by scheduling independent parts of a circuit in sequence. Two independent measured qubits can share a physical qubit if it is reset between uses. Use reuse_qubits() to apply this transformation directly, or run_qubit_reuse_pipeline() to prepare the program first.

The example below uses individual QCO qubit values. Register operations and intervening classical stores can prevent reuse_qubits() from establishing that reuse is safe:

 1from mqt.core.mlir import QCOProgram
 2
 3independent_qubits = """module {
 4  func.func @main() -> (i1, i1) attributes {mqt.entry_point} {
 5    %q0 = qco.alloc : !qco.qubit
 6    %q1 = qco.alloc : !qco.qubit
 7    %h0 = qco.h %q0 : !qco.qubit
 8    %h1 = qco.h %q1 : !qco.qubit
 9    %m0, %c0 = qco.measure %h0 : !qco.qubit
10    %m1, %c1 = qco.measure %h1 : !qco.qubit
11    qco.sink %m0 : !qco.qubit
12    qco.sink %m1 : !qco.qubit
13    return %c0, %c1 : i1, i1
14  }
15}
16"""
17raw_reuse = QCOProgram.from_mlir_str(independent_qubits)
18before = raw_reuse.ir.count("qco.alloc")
19raw_reuse.reuse_qubits()
20
21composite_reuse = QCOProgram.from_mlir_str(independent_qubits)
22composite_reuse.run_qubit_reuse_pipeline()
23assert raw_reuse.is_valid and composite_reuse.is_valid
24after = raw_reuse.ir.count("qco.alloc")
25assert before == 2 and after == 1
26print(f"Qubit allocations: {before} → {after}")
27print(raw_reuse.ir)
Qubit allocations: 2 → 1
module {
  func.func @main() -> (i1, i1) attributes {mqt.entry_point} {
    %q = qco.alloc : !qco.qubit
    %q_0 = qco.h %q : !qco.qubit
    %q_1, %b = qco.measure %q_0 : !qco.qubit
    %q_2 = qco.reset %q_1 : !qco.qubit
    %q_3 = qco.h %q_2 : !qco.qubit
    %q_4, %b_5 = qco.measure %q_3 : !qco.qubit
    qco.sink %q_4 : !qco.qubit
    return %b, %b_5 : i1, i1
  }
}

The same flows can be composed with the default optimization pipeline in the compiler driver:

mqt-core compile input.qasm --emit=qco-optimized \
  --pass-pipeline='builtin.module(reuse-qubits,mqt-qco-default)'
mqt-core compile input.qasm --emit=qco-optimized \
  --pass-pipeline='builtin.module(mqt-qubit-reuse,mqt-qco-default)'

The mqt-qubit-reuse pipeline moves measurements and replaces classical controls with quantum controls before applying reuse-qubits. It also runs remove-dead-gates, which can remove gates whose results are unused, including operations on unmeasured qubits. Use these passes only when those results may be discarded.

The qco_pipeline argument replaces the default QCO optimization pipeline. It is applied when compilation proceeds beyond the raw OutputFormat.QCO checkpoint.

Serialize programs and generate QIR

JeffProgram holds MLIR in the jeff dialect. Use to_bytes() or write() to serialize it. The bytes or file can be loaded and compiled again in a later process.

The jeff guide describes buffer and file interfaces and the supported conversion. The exchange tutorial checks phase and structured control flow across a serialization handoff.

 1from pathlib import Path
 2from tempfile import TemporaryDirectory
 3
 4with TemporaryDirectory() as directory:
 5    path = Path(directory) / "bell.jeff"
 6    jeff = compile_program(bell_qasm, output=OutputFormat.JEFF)
 7    jeff.write(path)
 8    restored = compile_program(path, output=OutputFormat.QC)
 9
10assert restored.is_valid

For an already compiled QC program, use to_iqm_json() with its target to serialize PRX/CZ gates and terminal readout without routing or synthesis. The exporter normalizes and discards entry-point global phase, uses target site names, and requires one terminal measurement for each output bit.

To generate QIR, select a target profile. QIRProgram provides the QIR MLIR through ir and the translated LLVM IR through to_llvm_ir(). Compilation to Base unrolls counted loops whose bounds and steps fold to constants and folds their classical expressions, with a limit of one billion cloned loop-body operations. Use Adaptive QIR for runtime-dependent loops or to retain structured iteration.

1qir = compile_program(bell_qasm, output=OutputFormat.QIR_BASE)
2assert qir.profile is QIRProfile.BASE
3print(qir.to_llvm_ir())
; ModuleID = 'LLVMDialectModule'
source_filename = "LLVMDialectModule"

@qir.result_label_result_1 = internal constant [9 x i8] c"result_1\00"
@qir.result_label_result_0 = internal constant [9 x i8] c"result_0\00"
@qir.result_label_result = internal constant [7 x i8] c"result\00"

define i64 @main() #0 {
  call void @__quantum__rt__initialize(ptr null)
  br label %1

1:                                                ; preds = %0
  call void @__quantum__qis__h__body(ptr null)
  call void @__quantum__qis__cx__body(ptr null, ptr inttoptr (i64 1 to ptr))
  br label %2

2:                                                ; preds = %1
  call void @__quantum__qis__mz__body(ptr null, ptr null)
  call void @__quantum__qis__mz__body(ptr inttoptr (i64 1 to ptr), ptr inttoptr (i64 1 to ptr))
  br label %3

3:                                                ; preds = %2
  call void @__quantum__rt__array_record_output(i64 2, ptr @qir.result_label_result)
  call void @__quantum__rt__result_record_output(ptr null, ptr @qir.result_label_result_0)
  call void @__quantum__rt__result_record_output(ptr inttoptr (i64 1 to ptr), ptr @qir.result_label_result_1)
  ret i64 0
}

declare void @__quantum__rt__initialize(ptr)

declare void @__quantum__qis__h__body(ptr)

declare void @__quantum__qis__cx__body(ptr, ptr)

declare void @__quantum__qis__mz__body(ptr, ptr writeonly) #1

declare void @__quantum__rt__array_record_output(i64, ptr)

declare void @__quantum__rt__result_record_output(ptr, ptr)

attributes #0 = { "entry_point" "output_labeling_schema"="labeled" "qir_profiles"="base_profile" "required_num_qubits"="2" "required_num_results"="2" }
attributes #1 = { "irreversible" }

!llvm.module.flags = !{!0, !1, !2, !3, !4}

!0 = !{i32 1, !"qir_major_version", i32 2}
!1 = !{i32 7, !"qir_minor_version", i32 0}
!2 = !{i32 1, !"dynamic_qubit_management", i1 false}
!3 = !{i32 1, !"dynamic_result_management", i1 false}
!4 = !{i32 2, !"Debug Info Version", i32 3}

Use to_bitcode() to obtain LLVM bitcode as bytes, or write_bitcode() to write a .bc file directly. These exports consume the program; set copy=True when another export or inspection must follow. The QIR guide compiles both profiles, inspects capability flags, and executes the generated bytes with DDSIM through QDMI.

MQT Core selects the QIR serialization from the output filename. Use .ll for textual LLVM IR and .bc for LLVM bitcode:

mqt-core compile input.qasm --emit=qir-base -o output.ll
mqt-core compile input.qasm --emit=qir-adaptive -o output.bc

Writing QIR to standard output also produces textual LLVM IR. All other output filenames, including filenames without an extension, produce bitcode.

The QC, QCO, and QTensor references describe the underlying operations. See Conversions for conversions between dialects.