forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslateToOpenQASM.cpp
More file actions
398 lines (362 loc) · 14.5 KB
/
Copy pathTranslateToOpenQASM.cpp
File metadata and controls
398 lines (362 loc) · 14.5 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*******************************************************************************
* Copyright (c) 2022 - 2026 NVIDIA Corporation & Affiliates. *
* All rights reserved. *
* *
* This source code and the accompanying materials are made available under *
* the terms of the Apache License 2.0 which accompanies this distribution. *
******************************************************************************/
#include "PassDetails.h"
#include "cudaq/Frontend/nvqpp/AttributeNames.h"
#include "cudaq/Optimizer/Builder/RuntimeNames.h"
#include "cudaq/Optimizer/CodeGen/Emitter.h"
#include "cudaq/Optimizer/CodeGen/OpenQASMEmitter.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "mlir/Analysis/CallGraph.h"
using namespace mlir;
//===----------------------------------------------------------------------===//
// Helper functions
//===----------------------------------------------------------------------===//
/// Translates operation names into OpenQASM gate names
static LogicalResult
translateOperatorName(cudaq::quake::OperatorInterface optor, StringRef &name) {
StringRef qkeName = optor->getName().stripDialect();
if (optor.getControls().size() == 0) {
name = StringSwitch<StringRef>(qkeName).Case("r1", "u1").Default(qkeName);
} else if (optor.getControls().size() == 1) {
name = StringSwitch<StringRef>(qkeName)
.Case("h", "ch")
.Case("x", "cx")
.Case("y", "cy")
.Case("z", "cz")
.Case("r1", "cu1")
.Case("rx", "crx")
.Case("ry", "cry")
.Case("rz", "crz")
.Case("swap", "cswap")
.Case("u3", "cu3")
.Default(qkeName);
} else if (optor.getControls().size() == 2) {
name = StringSwitch<StringRef>(qkeName).Case("x", "ccx").Default("");
}
if (name.empty())
return failure();
return success();
}
static LogicalResult printParameters(cudaq::Emitter &emitter,
ValueRange parameters) {
if (parameters.empty())
return success();
emitter.os << '(';
auto isFailure = false;
llvm::interleaveComma(parameters, emitter.os, [&](Value value) {
auto parameter = cudaq::getParameterValueAsDouble(value);
if (!parameter.has_value()) {
isFailure = true;
return;
}
emitter.os << *parameter;
});
emitter.os << ')';
// TODO: emit error here?
return failure(isFailure);
}
static StringRef printClassicalAllocation(cudaq::Emitter &emitter,
Value bitOrVector, size_t size) {
auto name = emitter.createName();
emitter.os << llvm::formatv("creg {0}[{1}];\n", name, size);
if (size == 1)
name.append("[0]");
return emitter.getOrAssignName(bitOrVector, name);
}
//===----------------------------------------------------------------------===//
// Emitters functions
//===----------------------------------------------------------------------===//
static LogicalResult emitOperation(cudaq::Emitter &emitter, Operation &op);
static LogicalResult emitEntryPoint(cudaq::Emitter &emitter,
func::FuncOp kernel) {
cudaq::Emitter::Scope scope(emitter, /*isEntryPoint=*/true);
for (Operation &op : kernel.getOps()) {
if (failed(emitOperation(emitter, op)))
return failure();
}
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter, ModuleOp moduleOp) {
func::FuncOp entryPoint = nullptr;
emitter.os << "// Code generated by NVIDIA's nvq++ compiler\n";
emitter.os << "OPENQASM 2.0;\n\n";
emitter.os << "include \"qelib1.inc\";\n\n";
// Build the call graph of the module
const mlir::CallGraph callGraph(moduleOp);
for (Operation &op : moduleOp) {
if (op.hasAttr(cudaq::entryPointAttrName)) {
if (entryPoint)
return moduleOp.emitError("has multiple entrypoints");
entryPoint = dyn_cast_or_null<func::FuncOp>(op);
continue;
}
if (!isa<func::FuncOp>(op)) {
// If not a FuncOp, just emit
if (failed(emitOperation(emitter, op)))
return failure();
emitter.os << '\n';
}
}
// Use PostOrderTraversal to get the ordered list of FuncOps.
// Note: this list will be in the reversed order, i.e., entry point function
// first.
llvm::ReversePostOrderTraversal<const mlir::CallGraph *> rpot(&callGraph);
std::vector<func::FuncOp> funcOps;
for (auto &node : rpot) {
if (node->isExternal())
continue;
auto *callableRegion = node->getCallableRegion();
auto *parentOp = callableRegion->getParentOp();
if (auto fnOp = dyn_cast_or_null<func::FuncOp>(parentOp)) {
// Don't add the entry point function.
if (fnOp != entryPoint) {
// Insert at the front, i.e., reverse the order.
funcOps.insert(funcOps.begin(), fnOp);
}
}
}
// Emit these functions as custom gate defs.
for (auto &op : funcOps) {
if (failed(emitOperation(emitter, *op)))
return failure();
emitter.os << '\n';
}
if (!entryPoint)
return moduleOp.emitError("does not contain an entrypoint");
return emitEntryPoint(emitter, entryPoint);
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::cc::ScopeOp scope) {
for (Block &block : scope.getInitRegion())
for (Operation &op : block)
if (failed(emitOperation(emitter, op)))
return failure();
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::quake::AllocaOp allocaOp) {
Value refOrVeq = allocaOp.getRefOrVec();
auto name = emitter.createName();
auto size = 1;
if (auto veq = dyn_cast<cudaq::quake::VeqType>(refOrVeq.getType())) {
if (!veq.hasSpecifiedSize())
return allocaOp.emitError("allocates unbounded veq");
size = veq.getSize();
}
emitter.os << llvm::formatv("qreg {0}[{1}];\n", name, size);
if (isa<cudaq::quake::RefType>(refOrVeq.getType()))
name.append("[0]");
emitter.getOrAssignName(refOrVeq, name);
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::quake::ApplyOp op) {
// In Quake's reference semantics form, kernels only return classical types.
// Thus, we check whether the numbers of results is zero or not.
if (op.getNumResults() > 0)
return op.emitError("cannot return classical results");
if (!op.getControls().empty())
return op.emitError("cannot add controls to a gate call");
emitter.os << op.getCallee();
// Separate classical and quantum arguments.
SmallVector<Value> parameters;
SmallVector<Value> targets;
for (auto arg : op.getActuals()) {
if (isa<cudaq::quake::RefType, cudaq::quake::VeqType>(arg.getType()))
targets.push_back(arg);
else
parameters.push_back(arg);
}
if (!parameters.empty()) {
emitter.os << '(';
llvm::interleaveComma(parameters, emitter.os, [&](auto param) {
emitter.os << emitter.getOrAssignName(param);
});
emitter.os << ')';
}
emitter.os << ' ';
llvm::interleaveComma(targets, emitter.os, [&](auto target) {
emitter.os << emitter.getOrAssignName(target);
});
emitter.os << ";\n";
return success();
}
// Format the function name to conform to OpenQASM spec
static inline StringRef formatFunctionName(StringRef quakeName) {
return quakeName.drop_while([](char C) { return C == '_'; });
}
static LogicalResult emitOperation(cudaq::Emitter &emitter, func::FuncOp op) {
if (op.isPrivate())
return success();
// Skip C++ ABI wrapper stubs: functions that have an empty body and whose
// name does not carry the `__nvqpp__mlirgen__` kernel prefix. These are stubs
// to satisfy the classical linker but contain no quantum operations and are
// not relevant to OpenQASM. Legitimate empty kernels (e.g. an explicitly
// empty `__qpu__` helper), which have the prefix and are kept so that any
// call sites remain valid.
if (!op.isExternal() && op.front().without_terminator().empty() &&
!op.getName().starts_with(cudaq::runtime::cudaqGenPrefixName))
return success();
// In Quake's reference semantics form, kernels only return classical types.
// Thus, we check whether the numbers of results is zero or not.
if (op.getNumResults() > 0)
return op.emitError("cannot return classical results");
// Separate classical and quantum arguments.
SmallVector<Value> parameters;
SmallVector<Value> targets;
for (auto arg : op.getArguments()) {
if (isa<cudaq::quake::RefType, cudaq::quake::VeqType>(arg.getType()))
targets.push_back(arg);
else
parameters.push_back(arg);
}
cudaq::Emitter::Scope scope(emitter);
emitter.os << "gate " << formatFunctionName(op.getName());
if (!parameters.empty()) {
emitter.os << '(';
llvm::interleaveComma(parameters, emitter.os, [&](auto param) {
auto name = emitter.createName("param");
emitter.getOrAssignName(param, name);
emitter.os << name;
});
emitter.os << ')';
}
emitter.os << ' ';
llvm::interleaveComma(targets, emitter.os, [&](auto target) {
auto name = emitter.createName("q");
emitter.getOrAssignName(target, name);
emitter.os << name;
});
emitter.os << " {\n";
emitter.os.indent();
for (Operation &op : op.getOps()) {
if (failed(emitOperation(emitter, op)))
return failure();
}
emitter.os.unindent();
emitter.os << "}\n";
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::quake::ExtractRefOp op) {
std::optional<int64_t> index = std::nullopt;
if (op.hasConstantIndex())
index = op.getConstantIndex();
else
index = cudaq::getIndexValueAsInt(op.getIndex());
auto veqName = emitter.getOrAssignName(op.getVeq());
auto qrefName = llvm::formatv("{0}[{1}]", veqName, *index);
emitter.getOrAssignName(op.getRef(), qrefName);
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
func::CallOp callOp) {
StringRef funcName = formatFunctionName(callOp.getCallee());
emitter.os << funcName;
emitter.os << ' ';
llvm::interleaveComma(callOp.getOperands(), emitter.os, [&](auto target) {
emitter.os << emitter.getOrAssignName(target);
});
emitter.os << ";\n";
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::quake::OperatorInterface optor) {
// Handle adjoint for T and S
StringRef name = "";
if (failed(translateOperatorName(optor, name)))
return optor.emitError("cannot convert operation to OpenQASM 2.0.");
if (optor.isAdj()) {
std::vector<std::string> validAdjointOps{"s", "t"};
if (std::find(validAdjointOps.begin(), validAdjointOps.end(), name.str()) ==
validAdjointOps.end())
return optor.emitError("cannot create adjoint for this operation.");
emitter.os << name << "dg";
} else
emitter.os << name;
if (failed(printParameters(emitter, optor.getParameters())))
return optor.emitError("failed to emit parameters");
if (!optor.getControls().empty()) {
emitter.os << ' ';
llvm::interleaveComma(optor.getControls(), emitter.os, [&](auto control) {
emitter.os << emitter.getOrAssignName(control);
});
emitter.os << ',';
}
emitter.os << ' ';
llvm::interleaveComma(optor.getTargets(), emitter.os, [&](auto target) {
emitter.os << emitter.getOrAssignName(target);
});
emitter.os << ";\n";
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::quake::MzOp op) {
if (op.getTargets().size() > 1)
return op.emitError(
"cannot translate measurements with more than one target");
auto qrefOrVeq = op.getTargets()[0];
auto size = 1;
if (auto veq = dyn_cast<cudaq::quake::VeqType>(qrefOrVeq.getType())) {
if (!veq.hasSpecifiedSize())
return op.emitError("cannot emmit measure on an unbounded veq");
size = veq.getSize();
}
auto bitsName = printClassicalAllocation(emitter, op.getMeasOut(), size);
emitter.os << "measure " << emitter.getOrAssignName(qrefOrVeq) << " -> "
<< bitsName << ";\n";
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter,
cudaq::quake::ResetOp op) {
emitter.os << "reset " << emitter.getOrAssignName(op.getTargets()) << ";";
return success();
}
static LogicalResult emitOperation(cudaq::Emitter &emitter, Operation &op) {
return llvm::TypeSwitch<Operation *, LogicalResult>(&op)
// MLIR
.Case<ModuleOp>([&](auto op) { return emitOperation(emitter, op); })
.Case<func::FuncOp>([&](auto op) { return emitOperation(emitter, op); })
.Case<func::CallOp>([&](auto op) { return emitOperation(emitter, op); })
// Quake
.Case<cudaq::quake::ApplyOp>(
[&](auto op) { return emitOperation(emitter, op); })
.Case<cudaq::quake::AllocaOp>(
[&](auto op) { return emitOperation(emitter, op); })
.Case<cudaq::quake::ExtractRefOp>(
[&](auto op) { return emitOperation(emitter, op); })
.Case<cudaq::quake::OperatorInterface>(
[&](auto optor) { return emitOperation(emitter, optor); })
.Case<cudaq::quake::MzOp>(
[&](auto op) { return emitOperation(emitter, op); })
.Case<cudaq::quake::ResetOp>(
[&](auto op) { return emitOperation(emitter, op); })
// Ignore
.Case<cudaq::quake::DeallocOp>([&](auto op) { return success(); })
.Case<func::ReturnOp>([&](auto op) { return success(); })
.Case<arith::ConstantOp>([&](auto op) { return success(); })
.Case<cudaq::cc::AllocaOp>([&](auto op) { return success(); })
.Case<cudaq::cc::StoreOp>([&](auto op) { return success(); })
.Case<cudaq::cc::CastOp>([&](auto op) { return success(); })
.Case<cudaq::cc::ComputePtrOp>([&](auto op) { return success(); })
.Case<cudaq::quake::DiscriminateOp>([&](auto op) { return success(); })
.Case<cudaq::cc::ScopeOp>(
[&](auto op) { return emitOperation(emitter, op); })
.Case<cudaq::cc::ContinueOp>([&](auto op) { return success(); })
.Default([&](Operation *) -> LogicalResult {
if (op.getName().getDialectNamespace() == "llvm")
return success();
return op.emitOpError("unable to translate op to OpenQASM 2.0");
});
}
LogicalResult cudaq::translateToOpenQASM(Operation *op, raw_ostream &os) {
cudaq::Emitter emitter(os);
return emitOperation(emitter, *op);
}