Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions docs/mlir/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ quantum output, and so on; use counts alone do not establish that relation.

When writing IR or a transformation, observe these requirements:

- A program with an entry point may allocate scratch qubits in a helper or a
nested block. Release them in the block that allocates them. Allocations in
the entry block of the entry point may live until the program ends. Mapping
and QIR lowering require all dynamic allocations in that entry block.
- Quantum operands of a gate or helper call denote disjoint resources. A
register and one of its elements cannot be separate operands of the same call.
Multiple references to a qubit are allowed when used sequentially.
Expand All @@ -64,16 +68,16 @@ When writing IR or a transformation, observe these requirements:
without changing the identities stored in the register. QC register stores may
initialize a slot in a reference buffer or write the same reference back to
its slot.
- A register passed to a helper, carried through a structured region boundary,
returned, or dynamically deallocated must be complete: every extracted qubit
has been restored. A scalar helper may use an extracted qubit while the
remaining tensor stays in its caller.
- Restore every extracted qubit before passing a register to a helper, carrying
it through a structured region, or returning it. QCO allows a tensor and its
extracted qubits to be released separately. Conversion to QC requires a
complete tensor at deallocation.
- Quantum results of helpers and structured control flow correspond to quantum
inputs in the same order. Updated quantum arguments form a suffix after the
ordinary function results. Quantum values in QCO have exactly one use.
`qco::verifyLinearity` checks both use counts and positional correspondence
after ordinary MLIR verification. Public QCO program APIs run this check;
parsing MLIR alone does not establish it.
ordinary function results. Quantum values in QCO have exactly one use. Public
QCO program APIs run `qco::verifyLinearity` after ordinary MLIR verification
to check use counts, positional correspondence, and complete registers at
function and region boundaries.

A QC reference buffer can group qubits that already exist. Its QCO counterpart
is `qtensor.from_elements`. After placement, the buffer holds references to
Expand Down
8 changes: 4 additions & 4 deletions mlir/include/mqt/Compiler/Programs.h
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ class QCProgram final : public Program {
/// remain the module's context. The factory verifies the module and rejects
/// QCO and QTensor operations. QC operations are not required. The module
/// must define an `mqt.entry_point` function; all other functions must be
/// private. Dynamic quantum allocations must appear directly in its entry
/// block.
/// private. Release dynamic allocations outside its entry block in the block
/// that allocates them.
[[nodiscard]] static FailureOr<QCProgram>
fromModule(std::shared_ptr<MLIRContext> context,
OwningOpRef<ModuleOp> moduleOp);
Expand Down Expand Up @@ -395,8 +395,8 @@ class QCOProgram final : public Program {
/// remain the module's context. The factory verifies the module and QCO
/// linearity and rejects QC operations. QCO operations are not required.
/// The module must define an `mqt.entry_point` function; all other functions
/// must be private. Dynamic quantum allocations must appear directly in its
/// entry block.
/// must be private. Release dynamic allocations outside its entry block in
/// the block that allocates them.
[[nodiscard]] static FailureOr<QCOProgram>
fromModule(std::shared_ptr<MLIRContext> context,
OwningOpRef<ModuleOp> moduleOp);
Expand Down
9 changes: 5 additions & 4 deletions mlir/include/mqt/Conversion/QCToQCO/QCToQCO.td
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ def QCToQCO : Pass<"qc-to-qco", "mlir::ModuleOp"> {

let description = [{
Convert QC references to linear QCO values and thread their current state
through gates, functions and structured control flow. A program allocates
qubits in the entry block of its `mqt.entry_point` function. Helpers can group existing
qubits in local reference buffers. Nested regions can use qubits through
supported SCF operations. Control flow with block successors is unsupported.
through gates, functions and structured control flow. Helpers and SCF
regions can allocate scratch qubits and registers and release them in the
same block. Allocations in the program entry block can live until the
program ends. Reference buffers that group existing qubits must be in a
function's entry block. Control flow with block successors is unsupported.

Private helpers may borrow fixed-size rank-one qubit memrefs with identity
layout and default memory space. These become qubit tensors. Each updated
Expand Down
18 changes: 15 additions & 3 deletions mlir/include/mqt/Dialect/MQT/IR/MQTDialect.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,21 @@ void setUnitaryFunction(Operation* operation);
/// Check that the entry function returns no quantum values.
[[nodiscard]] LogicalResult verifyEntryPointResults(func::FuncOp function);

/// Check that dynamic quantum allocations belong to the program entry block.
/// Check dynamic quantum allocation placement.
///
/// Modules without an entry point must not contain dynamic quantum allocations.
/// Nested modules have separate program scopes.
/// An allocation in the entry block of the program entry point may live until
/// the program ends. Any other allocation must be released in the block that
/// allocates it. Modules without an entry point must not contain dynamic
/// quantum allocations. Nested modules have separate program scopes.
[[nodiscard]] LogicalResult verifyQuantumAllocations(ModuleOp moduleOp);

/// Check that every dynamic quantum allocation is in the entry block of the
/// program entry point.
///
/// This is stricter than `verifyQuantumAllocations` and serves consumers that
/// need all qubits allocated up front, such as mapping and QIR conversion.
/// Modules without an entry point must not contain dynamic quantum allocations.
[[nodiscard]] LogicalResult
verifyEntryBlockQuantumAllocations(ModuleOp moduleOp);

} // namespace mlir::mqt
23 changes: 14 additions & 9 deletions mlir/include/mqt/Dialect/MQT/IR/MQTDialect.td
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,21 @@ def MQTDialect : Dialect {
needed for those behaviors in the explicit attributes above.

`mqt.entry_point` marks the single public, defined `func.func` program entry
in a module. Every other `func.func` in that module is private. QC/QCO entries cannot return quantum values. Their classical
results are program data; an entry with no outputs returns no values. QIR conversion records supported bit outputs and generates
in a module. Every other function in the module is private. QC/QCO entries
return classical program data or no values. QIR conversion records
supported bit outputs and generates
an `i64` zero execution status. It rejects other scalar program outputs.
Dynamic quantum allocations (`qc.alloc`, `qco.alloc`,
qubit `memref.alloc`, and `qtensor.alloc`) must appear directly in its
entry block. Other functions receive quantum resources as arguments;
they cannot allocate them. Classical allocations and static device-site
references are not subject to this restriction. A program cannot mix
static device-site references with quantum allocation operations. A fixed
register size does not make an allocation a static device-site reference.
A dynamic quantum allocation (`qc.alloc`, `qco.alloc`,
qubit `memref.alloc`, or `qtensor.alloc`) directly in its entry block may
live until the program ends. Any other dynamic quantum allocation must be
released in the block that allocates it: by `qc.dealloc` or
`memref.dealloc`, or by following the QCO value to `qco.sink` or
`qtensor.dealloc`. Mapping and QIR conversion accept only entry-block
allocations. Classical allocations and static device-site references are
not subject to these restrictions. A program cannot mix static device-site
references with quantum allocations. A fixed register size does not make
an allocation a static device-site reference.

`mqt.unitary` marks a private function that defines a unitary operation.
Its body admits unitary operations and memory-effect-free, region-free
classical computation. Statically bounded `scf.for` loops may contain these
Expand Down
21 changes: 12 additions & 9 deletions mlir/include/mqt/Dialect/QC/Builder/QCProgramBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ void emitGateWithModifiers(OpBuilder& builder, Location loc,
/// dynamic allocation
/// (`allocQubit` / `allocQubitRegister`), never both. The builder terminates
/// with a usage error if the modes are mixed.
/// Dynamic allocation is only allowed directly in the entry block of the
/// `mqt.entry_point` function. Helpers receive allocated qubits as arguments.
/// Allocate dynamic qubits in the entry block of a non-unitary function.
/// The builder releases a helper's local qubits when the helper returns.
///
/// @par Example Usage:
/// ```c++
Expand Down Expand Up @@ -124,7 +124,7 @@ class QCProgramBuilder final : public ImplicitLocOpBuilder {
/// Create a complete private function and infer its result types.
///
/// Borrowed qubit arguments are updated in place and must not be returned.
/// The body must not dynamically allocate qubits or qubit registers.
/// Qubits the body allocates and leaves live are released at its end.
func::FuncOp
createFunction(StringRef name, TypeRange argumentTypes,
function_ref<SmallVector<Value>(ValueRange)> body);
Expand Down Expand Up @@ -177,7 +177,7 @@ class QCProgramBuilder final : public ImplicitLocOpBuilder {

/// Allocate a single qubit initialized to |0⟩.
///
/// Requires an insertion point in the entry block of `mqt.entry_point`.
/// Requires the entry block of a non-unitary function.
///
/// @return A qubit reference
///
Expand Down Expand Up @@ -207,7 +207,7 @@ class QCProgramBuilder final : public ImplicitLocOpBuilder {
/// Allocate a qubit register and eagerly load every element.
///
/// Every allocated qubit is initialized to |0⟩.
/// Requires an insertion point in the entry block of `mqt.entry_point`.
/// Requires the entry block of a non-unitary function.
///
/// \param size Number of qubits; must be positive.
/// \param name Optional source-level register name.
Expand All @@ -229,7 +229,7 @@ class QCProgramBuilder final : public ImplicitLocOpBuilder {
/// Every allocated qubit is initialized to |0⟩. The builder tracks the
/// register for automatic deallocation. Use `loadQubit` to obtain references
/// at their points of use.
/// Requires an insertion point in the entry block of `mqt.entry_point`.
/// Requires the entry block of a non-unitary function.
///
/// \param size Number of qubits; must be positive.
/// \param name Optional source-level register name.
Expand Down Expand Up @@ -1372,10 +1372,13 @@ class QCProgramBuilder final : public ImplicitLocOpBuilder {
/// Track whether static or dynamic qubit allocation is used.
AllocationMode allocationMode = AllocationMode::Unset;

/// Ensure static and dynamic qubit allocation modes are not mixed.
///
/// Dynamic allocation also requires the entry-point entry block.
/// Check allocation mode and placement.
void ensureAllocationMode(AllocationMode requestedMode);

/// Build a private function under the requested unitary restrictions.
func::FuncOp buildFunction(StringRef name, TypeRange argumentTypes,
function_ref<SmallVector<Value>(ValueRange)> body,
bool unitary);
};
} // namespace qc
} // namespace mlir
10 changes: 10 additions & 0 deletions mlir/include/mqt/Dialect/QC/IR/QCDialect.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include "mlir/IR/OpDefinition.h"
#include "mlir/Interfaces/SideEffectInterfaces.h"
#include "mlir/Support/LogicalResult.h"

#include "llvm/ADT/StringRef.h"

Expand All @@ -36,6 +37,15 @@

namespace mlir::qc {

/// Return whether a QC allocation has a direct release in its defining block.
[[nodiscard]] bool hasLocalRelease(Operation* allocation);

/// Verify uses of explicitly released qubits and qubit registers.
/// Requires verified MLIR. Checks direct uses, control-flow forwarding, views,
/// static sites, and known slots of immutable reference buffers. A release
/// needs an identifiable owner. The caller resolves dynamic slot aliases.
[[nodiscard]] LogicalResult verifyQuantumReleaseOrder(Operation* root);

/// Quantum state accessed by QC reference operations.
///
/// Effects conservatively overlap SideEffects::DefaultResource effects.
Expand Down
6 changes: 3 additions & 3 deletions mlir/include/mqt/Dialect/QC/IR/QCDialect.td
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ def QCDialect : Dialect {
qc.swap %q0, %q1
```

Allocation operations for qubits and registers must appear in the entry block of the
`mqt.entry_point` function. Helper functions receive their qubits as
arguments; the entry-point verifier checks this allocation rule.
Quantum allocations outside the entry block of `mqt.entry_point` must be
released in their allocating block. The entry-point verifier checks this
rule; see the [MQT dialect](MQT.md) for allocation and lowering restrictions.

Each register slot continues to refer to the same qubit. A gate or call
must receive distinct qubits, even when its operands include registers or
Expand Down
21 changes: 12 additions & 9 deletions mlir/include/mqt/Dialect/QCO/Builder/QCOProgramBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ namespace qco {
/// dynamic allocation
/// (`allocQubit`, `allocQubitRegister`, or `qtensorAlloc`), never both. The
/// builder terminates with a usage error if the modes are mixed.
/// Dynamic allocation is only allowed directly in the entry block of the
/// `mqt.entry_point` function. Helpers receive allocated qubits as arguments.
/// Allocate dynamic qubits in the entry block of a non-unitary function.
/// The builder releases a helper's local qubits when the helper returns.
///
/// @par Structured control flow:
/// Quantum values must enter regions through explicit arguments; classical
Expand Down Expand Up @@ -107,7 +107,7 @@ class QCOProgramBuilder final : public ImplicitLocOpBuilder {
///
/// The callback must return one trailing value for every scalar qubit or
/// complete quantum register argument, in argument order.
/// The body must not dynamically allocate qubits or qubit tensors.
/// Qubits the body allocates and leaves live are released at its end.
func::FuncOp
createFunction(StringRef name, TypeRange argumentTypes,
function_ref<SmallVector<Value>(ValueRange)> body);
Expand Down Expand Up @@ -244,7 +244,7 @@ class QCOProgramBuilder final : public ImplicitLocOpBuilder {

/// Allocate a single qubit initialized to |0⟩.
///
/// Requires an insertion point in the entry block of `mqt.entry_point`.
/// Requires the entry block of a non-unitary function.
///
/// @return A tracked qubit handle (convertible to `Value`)
///
Expand Down Expand Up @@ -273,7 +273,7 @@ class QCOProgramBuilder final : public ImplicitLocOpBuilder {

/// Allocate a qubit tensor and eagerly extract every element.
///
/// Requires an insertion point in the entry block of `mqt.entry_point`.
/// Requires the entry block of a non-unitary function.
///
/// @param size Number of qubits (must be positive)
/// @param name Optional source-level register name
Expand Down Expand Up @@ -332,7 +332,7 @@ class QCOProgramBuilder final : public ImplicitLocOpBuilder {
/// `!qco.qubit` values. No elements are extracted. If the size is a constant,
/// the tensor has static size; otherwise it has dynamic size. Its qubits are
/// initialized in the |0⟩ state, and the tensor is tracked automatically.
/// Requires an insertion point in the entry block of `mqt.entry_point`.
/// Requires the entry block of a non-unitary function.
///
/// @param size Number of qubits (must be positive)
/// @return The allocated tensor
Expand Down Expand Up @@ -1899,10 +1899,13 @@ class QCOProgramBuilder final : public ImplicitLocOpBuilder {
/// Track whether static or dynamic qubit allocation is used.
AllocationMode allocationMode = AllocationMode::Unset;

/// Ensure static and dynamic qubit allocation modes are not mixed.
///
/// Dynamic allocation also requires the entry-point entry block.
/// Check allocation mode and placement.
void ensureAllocationMode(AllocationMode requestedMode);

/// Build a private function under the requested unitary restrictions.
func::FuncOp buildFunction(StringRef name, TypeRange argumentTypes,
function_ref<SmallVector<Value>(ValueRange)> body,
bool unitary);
};
} // namespace qco
} // namespace mlir
8 changes: 4 additions & 4 deletions mlir/include/mqt/Dialect/QCO/IR/QCODialect.td
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ def QCODialect : Dialect {
```

Each quantum SSA value has exactly one use. It represents a qubit's state
at that point, but does not contain a simulated statevector. Allocation
operations for qubits and qubit tensors must appear in the entry block of the
`mqt.entry_point` function. Helper functions receive their qubits as
arguments; the entry-point verifier checks this allocation rule.
at that point, but does not contain a simulated statevector. Quantum
allocations outside the entry block of `mqt.entry_point` must be released
in their allocating block. See the [MQT dialect](MQT.md) for allocation
and lowering restrictions.

The exactly-one-use rule does not determine which output continues which
input wire. MQT Core's `WireOpInterface` specifies that correspondence
Expand Down
20 changes: 17 additions & 3 deletions mlir/include/mqt/Dialect/QCO/Utils/LinearityUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,26 @@

#pragma once

#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Value.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"

#include "llvm/ADT/DenseMap.h"

#include <vector>

namespace mlir::qco {
/// Verify linear uses, static roots, and positional quantum state flow.
///
/// Requires ordinary MLIR verification first. Every linear QCO value has
/// exactly one use, static indices are unique in the entry block, and function
/// and structured-control-flow results continue quantum arguments in order.
/// In SSA regions, an extracted slot stays unavailable until reinsertion.
/// Checks compare constant indices and dynamic SSA identity; disjointness of
/// other index values is a program precondition.
/// Registers crossing function or structured region boundaries must be
/// complete. Checks compare constant indices and dynamic SSA identity;
/// disjointness of other index values is a program precondition.
[[nodiscard]] LogicalResult verifyLinearity(Operation* root);

/// Verify linearity and retain the wire origins used for positional checks.
Expand All @@ -40,13 +44,23 @@ namespace mlir::qco {
[[nodiscard]] LogicalResult collectWireOrigins(Operation* root,
DenseMap<Value, Value>& origins);

/// Check that QCO allocations are released in their defining block.
///
/// Allocations in @p programEntry are exempt. Can run before the function
/// body has been structurally verified.
[[nodiscard]] LogicalResult
verifyScopedAllocations(func::FuncOp function, Block* programEntry = nullptr);

/// Check tensor lifetimes while the IR remains unchanged.
class TensorLifetimeAnalysis {
public:
/// Check that extracted slots are restored at calls and region exits.
[[nodiscard]] bool isComplete(Value tensor, unsigned depth = 0);

private:
DenseMap<Value, Value> callResults_;
// Store the result and each region argument in operand order.
ArrayRef<Value> getContinuations(OpOperand& use);

DenseMap<Operation*, std::vector<Value>> continuations_;
};
} // namespace mlir::qco
4 changes: 2 additions & 2 deletions mlir/lib/Compiler/Programs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ bool containsProgramOperations(ModuleOp moduleOp,
/// Check that @p moduleOp can become a program of @p dialect in @p context.
///
/// Verify the module and reject operations of the other dialect. QCO programs
/// must also be linear.
/// must also be linear. QC programs must use live references.
[[nodiscard]] static LogicalResult
verifyProgramModule(const std::shared_ptr<MLIRContext>& context,
ModuleOp moduleOp, const ProgramDialect dialect) {
Expand Down Expand Up @@ -200,7 +200,7 @@ verifyProgramModule(const std::shared_ptr<MLIRContext>& context,
return moduleOp->emitError(
"QC programs must not contain QCO or QTensor operations");
}
return success();
return qc::verifyQuantumReleaseOrder(moduleOp);
}
if (containsProgramOperations(moduleOp, ProgramDialect::QC)) {
return moduleOp->emitError("QCO programs must not contain QC operations");
Expand Down
Loading
Loading