-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathCtrlOp.cpp
More file actions
373 lines (323 loc) · 13.1 KB
/
Copy pathCtrlOp.cpp
File metadata and controls
373 lines (323 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
* Copyright (c) 2023 - 2026 Chair for Design Automation, TUM
* Copyright (c) 2025 - 2026 Munich Quantum Software Company GmbH
* All rights reserved.
*
* SPDX-License-Identifier: MIT
*
* Licensed under the MIT License
*/
#include "mlir/Dialect/QCO/IR/QCODialect.h"
#include "mlir/Dialect/QCO/IR/QCOInterfaces.h"
#include "mlir/Dialect/QCO/IR/QCOOps.h"
#include "mlir/Dialect/QCO/QCOUtils.h"
#include "mlir/Dialect/QCO/Utils/Matrix.h"
#include "mlir/Dialect/Utils/Utils.h"
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/STLFunctionalExtras.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/SmallVectorExtras.h>
#include <llvm/Support/ErrorHandling.h>
#include <mlir/Dialect/QTensor/IR/QTensorOps.h>
#include <mlir/IR/Block.h>
#include <mlir/IR/Builders.h>
#include <mlir/IR/BuiltinAttributes.h>
#include <mlir/IR/MLIRContext.h>
#include <mlir/IR/OperationSupport.h>
#include <mlir/IR/PatternMatch.h>
#include <mlir/IR/Value.h>
#include <mlir/Support/LLVM.h>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <optional>
using namespace mlir;
using namespace mlir::qco;
namespace {
/**
* @brief Merge nested control modifiers into a single one.
*/
struct MergeNestedCtrl final : OpRewritePattern<CtrlOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(CtrlOp op,
PatternRewriter& rewriter) const override {
// Require at least one control
// Trivial case is handled by ReduceCtrl
if (op.getNumControls() == 0) {
return failure();
}
// Only proceed if body contains only one operation besides terminator
if (op.getBody()->getOperations().size() != 2) {
return failure();
}
auto inner = utils::getSoleBodyUnitary<UnitaryOpInterface>(*op.getBody());
if (!inner) {
return failure();
}
auto innerCtrlOp = dyn_cast<CtrlOp>(inner.getOperation());
if (!innerCtrlOp) {
return failure();
}
// The inner control's controls and targets are block arguments of the outer
// body that alias outer targets. Re-resolve them to the outer qubits: inner
// controls join the outer controls, inner targets become the merged
// targets. Inner-target order is kept so the inner body's block arguments
// line up with the merged targets and the body can be reused verbatim.
auto outerTargets = op.getTargetsIn();
auto innerControls = innerCtrlOp.getControlsIn();
auto innerTargets = innerCtrlOp.getTargetsIn();
SmallVector<Value> controls(op.getControlsIn());
for (auto control : innerControls) {
controls.push_back(
utils::getValueFromBlockArgument(control, outerTargets));
}
const auto targets = llvm::map_to_vector(innerTargets, [&](Value t) {
return utils::getValueFromBlockArgument(t, outerTargets);
});
auto merged =
CtrlOp::create(rewriter, op.getLoc(), controls, targets,
[&](ValueRange mergedTargets) -> SmallVector<Value> {
return utils::inlineBodyReturningYields(
*innerCtrlOp.getBody(), mergedTargets, rewriter);
});
// Every qubit output of the original control follows its input qubit to the
// corresponding output of the merged control.
rewriter.replaceOp(op,
llvm::map_to_vector(op.getInputQubits(), [&](Value in) {
return merged.getOutputForInput(in);
}));
return success();
}
};
/**
* @brief Reduce controls for well-known gates.
* @details Removes empty control ops and handles controlled IdOp, GPhaseOp and
* BarrierOp.
*/
struct ReduceCtrl final : OpRewritePattern<CtrlOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(CtrlOp op,
PatternRewriter& rewriter) const override {
auto inner = utils::getSoleBodyUnitary<UnitaryOpInterface>(*op.getBody());
if (!inner) {
return failure();
}
auto* innerOp = inner.getOperation();
// Inline ops from empty control modifiers, IdOp and BarrierOp
if (op.getNumControls() == 0 || isa<IdOp, BarrierOp>(innerOp)) {
auto* body = op.getBody();
auto* terminator = body->getTerminator();
// Controls are pass-through results outside the body yield, so the
// generic inlineModifierBody result mapping does not apply here.
SmallVector<Value> outputs(op.getControlsIn());
llvm::append_range(outputs, terminator->getOperands());
rewriter.inlineBlockBefore(body, op, op.getTargetsIn());
rewriter.eraseOp(terminator);
rewriter.replaceOp(op, outputs);
return success();
}
// The remaining code explicitly handles GPhaseOp and nothing else
auto gPhaseOp = dyn_cast<GPhaseOp>(innerOp);
if (!gPhaseOp) {
return failure();
}
// Only proceed if the GPhaseOp is the only operation besides the terminator
if (op.getBody()->getOperations().size() != 2) {
return failure();
}
// Special case for single control: replace with a single POp
if (op.getNumControls() == 1) {
rewriter.replaceOpWithNewOp<POp>(op, op.getInputControl(0),
gPhaseOp.getTheta());
return success();
}
// Reinterpret the last control as a target qubit and apply a phase gate to
// it inside the (smaller) controlled region
const auto opSegmentsAttrName = CtrlOp::getOperandSegmentSizeAttr();
auto segmentsAttr =
op->getAttrOfType<DenseI32ArrayAttr>(opSegmentsAttrName);
auto newSegments = DenseI32ArrayAttr::get(
rewriter.getContext(), {segmentsAttr[0] - 1, segmentsAttr[1] + 1});
op->setAttr(opSegmentsAttrName, newSegments);
const auto opResultSegmentsAttrName = CtrlOp::getResultSegmentSizeAttr();
op->setAttr(opResultSegmentsAttrName, newSegments);
// Add a block argument for the target qubit
auto arg = op.getBody()->addArgument(QubitType::get(rewriter.getContext()),
op.getLoc());
// Replace the current GPhaseOp with a PhaseOp
const OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPoint(gPhaseOp);
auto pOp =
POp::create(rewriter, gPhaseOp.getLoc(), arg, gPhaseOp.getTheta());
// Add the results of the POp to the yield operation
auto yieldOp = cast<YieldOp>(op.getBody()->back());
yieldOp->setOperands(pOp->getResults());
// Erase the GPhaseOp
rewriter.eraseOp(gPhaseOp);
return success();
}
};
/**
* @brief Erase control modifiers that do not have any body unitaries.
*/
struct EraseEmptyCtrl final : OpRewritePattern<CtrlOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(CtrlOp op,
PatternRewriter& rewriter) const override {
if (op.getNumBodyUnitaries() != 0) {
return failure();
}
rewriter.replaceOp(op, op.getOperands());
return success();
}
};
} // namespace
static void
buildModifierBody(OpBuilder& odsBuilder, OperationState& odsState,
const size_t numBlockArgs,
const function_ref<void(OpBuilder&, Block&)>& emitBody) {
auto& block = odsState.regions.front()->emplaceBlock();
const auto qubitType = QubitType::get(odsBuilder.getContext());
for (size_t i = 0; i < numBlockArgs; ++i) {
block.addArgument(qubitType, odsState.location);
}
const OpBuilder::InsertionGuard guard(odsBuilder);
odsBuilder.setInsertionPointToStart(&block);
emitBody(odsBuilder, block);
}
size_t CtrlOp::getNumBodyUnitaries() {
return utils::getNumBodyUnitaries<UnitaryOpInterface>(*getBody());
}
UnitaryOpInterface CtrlOp::getBodyUnitary(const size_t i) {
return utils::getBodyUnitary<UnitaryOpInterface>(*getBody(), i);
}
Value CtrlOp::getInputForOutput(Value output) {
if (const auto result = dyn_cast<OpResult>(output);
result && result.getOwner() == getOperation()) {
return getInputQubit(result.getResultNumber());
}
llvm::reportFatalUsageError("Given qubit is not an output of the operation");
}
Value CtrlOp::getOutputForInput(Value input) {
for (auto [in, out] : llvm::zip_equal(getInputQubits(), getOutputQubits())) {
if (in == input) {
return out;
}
}
llvm::reportFatalUsageError("Given qubit is not an input of the operation");
}
void CtrlOp::build(OpBuilder& odsBuilder, OperationState& odsState,
ValueRange controls, ValueRange targets,
function_ref<SmallVector<Value>(ValueRange)> bodyBuilder) {
build(odsBuilder, odsState, controls, targets);
buildModifierBody(odsBuilder, odsState, targets.size(),
[&](OpBuilder& builder, Block& block) {
YieldOp::create(builder, odsState.location,
bodyBuilder(block.getArguments()));
});
}
void CtrlOp::build(OpBuilder& odsBuilder, OperationState& odsState,
ValueRange controls, Value target,
function_ref<Value(Value)> bodyBuilder) {
build(odsBuilder, odsState, controls.getTypes(), target.getType(), controls,
target);
buildModifierBody(odsBuilder, odsState, 1,
[&](OpBuilder& builder, Block& block) {
YieldOp::create(builder, odsState.location,
bodyBuilder(block.getArgument(0)));
});
}
void CtrlOp::build(OpBuilder& odsBuilder, OperationState& odsState,
Value control, Value target,
function_ref<Value(Value)> bodyBuilder) {
build(odsBuilder, odsState, ValueRange{control}, target, bodyBuilder);
}
LogicalResult CtrlOp::verify() {
auto& block = *getBody();
if (llvm::any_of(block, [](Operation& op) {
return isa<AllocOp, SinkOp, StaticOp, MeasureOp, ResetOp,
qtensor::ExtractOp, qtensor::InsertOp>(op);
})) {
return emitOpError("body must not contain non-unitary quantum operations "
"or modify a quantum register");
}
const auto numTargets = getNumTargets();
if (block.getArguments().size() != numTargets) {
return emitOpError(
"number of block arguments must match the number of targets");
}
auto qubitType = QubitType::get(getContext());
for (size_t i = 0; i < numTargets; ++i) {
if (block.getArgument(i).getType() != qubitType) {
return emitOpError("block argument type at index ")
<< i << " does not match target type";
}
}
auto* blockTerminator = block.getTerminator();
if (const auto numYieldOperands = blockTerminator->getNumOperands();
numYieldOperands != numTargets) {
return emitOpError("yield operation must yield ")
<< numTargets << " values, but found " << numYieldOperands;
}
SmallPtrSet<Value, 4> uniqueQubitsIn;
for (const auto& control : getInputQubits()) {
if (!uniqueQubitsIn.insert(control).second) {
return emitOpError("duplicate qubit found");
}
}
SmallPtrSet<Value, 4> uniqueQubitsOut;
for (const auto& control : getControlsOut()) {
if (!uniqueQubitsOut.insert(control).second) {
return emitOpError("duplicate control qubit found");
}
}
for (size_t i = 0; i < numTargets; i++) {
if (!uniqueQubitsOut.insert(blockTerminator->getOperand(i)).second) {
return emitOpError("duplicate qubit found");
}
}
return success();
}
void CtrlOp::getCanonicalizationPatterns(RewritePatternSet& results,
MLIRContext* context) {
results.add<MergeNestedCtrl, ReduceCtrl, EraseEmptyCtrl>(context);
}
bool CtrlOp::hasCompileTimeKnownUnitaryMatrix() {
return all_of(getBody()->getOps<UnitaryOpInterface>(),
[](UnitaryOpInterface op) {
return op.hasCompileTimeKnownUnitaryMatrix();
});
}
std::optional<DynamicMatrix> CtrlOp::getUnitaryMatrix() {
if (getNumControls() >= 32) {
llvm::reportFatalUsageError(
"Creating the unitary matrix for a CtrlOp with more than 31 controls "
"is not supported due to memory constraints.");
}
const auto numControls = getNumControls();
// Build `I_{2^controls} ⊗ U` by placing the target block in the bottom-right
// corner of a `2^controls * targetDim` identity.
const auto controlledMatrix =
[numControls](const int64_t targetDim,
const auto& targetBlock) -> DynamicMatrix {
auto matrix = DynamicMatrix::identity(static_cast<int64_t>(
(1ULL << numControls) * static_cast<size_t>(targetDim)));
matrix.setBottomRightCorner(targetBlock);
return matrix;
};
// Single inner unitary (e.g. `ctrl { h }`, `ctrl { cx }`).
if (auto bodyUnitary =
utils::getSoleBodyUnitary<UnitaryOpInterface>(*getBody())) {
if (const auto targetMatrix =
bodyUnitary.getUnitaryMatrix<DynamicMatrix>()) {
assert(targetMatrix->cols() == targetMatrix->rows());
return controlledMatrix(targetMatrix->cols(), *targetMatrix);
}
return std::nullopt;
}
// Composed body (e.g., `ctrl { h; x }` or `ctrl { swap; ry }`)
if (const auto composed = composeBodyMatrix(*getBody(), getNumTargets())) {
return controlledMatrix(composed->rows(), *composed);
}
return std::nullopt;
}