-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathPrograms.cpp
More file actions
739 lines (656 loc) · 23.6 KB
/
Copy pathPrograms.cpp
File metadata and controls
739 lines (656 loc) · 23.6 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*
* 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/Compiler/Programs.h"
#include "ir/QuantumComputation.hpp"
#include "mlir/Compiler/TargetCompilation.h"
#include "mlir/Conversion/JeffToQCO/JeffToQCO.h"
#include "mlir/Conversion/QCOToJeff/QCOToJeff.h"
#include "mlir/Conversion/QCOToQC/QCOToQC.h"
#include "mlir/Conversion/QCToQCO/QCToQCO.h"
#include "mlir/Conversion/QCToQIR/QIRAdaptive/QCToQIRAdaptive.h"
#include "mlir/Conversion/QCToQIR/QIRBase/QCToQIRBase.h"
#include "mlir/Dialect/QC/IR/QCDialect.h"
#include "mlir/Dialect/QC/Translation/TranslateQASM3ToQC.h"
#include "mlir/Dialect/QC/Translation/TranslateQCToOpenQASM3.h"
#include "mlir/Dialect/QC/Translation/TranslateQuantumComputationToQC.h"
#include "mlir/Dialect/QCO/IR/QCODialect.h"
#include "mlir/Dialect/QCO/Transforms/Passes.h"
#include "mlir/Dialect/QTensor/IR/QTensorDialect.h"
#include "mlir/Dialect/Utils/Transforms/GlobalPhaseNormalization.h"
#include "mlir/Support/Passes.h"
#include <capnp/common.h>
#include <jeff/IR/JeffDialect.h>
#include <jeff/Translation/Deserialize.hpp>
#include <jeff/Translation/Serialize.hpp>
#include <kj/array.h>
#include <llvm/ADT/STLFunctionalExtras.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_ostream.h>
#include <mlir/Dialect/Arith/IR/Arith.h>
#include <mlir/Dialect/ControlFlow/IR/ControlFlow.h>
#include <mlir/Dialect/Func/IR/FuncOps.h>
#include <mlir/Dialect/LLVMIR/LLVMDialect.h>
#include <mlir/Dialect/MemRef/IR/MemRef.h>
#include <mlir/Dialect/SCF/IR/SCF.h>
#include <mlir/IR/Diagnostics.h>
#include <mlir/IR/DialectRegistry.h>
#include <mlir/IR/Location.h>
#include <mlir/IR/OwningOpRef.h>
#include <mlir/Parser/Parser.h>
#include <mlir/Pass/PassManager.h>
#include <mlir/Support/FileUtilities.h>
#include <mlir/Support/LLVM.h>
#include <mlir/Support/LogicalResult.h>
#include <mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h>
#include <mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h>
#include <mlir/Target/LLVMIR/ModuleTranslation.h>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
namespace mlir {
[[nodiscard]] static std::shared_ptr<MLIRContext> createCompilerContext() {
DialectRegistry registry;
registry.insert<qc::QCDialect, qco::QCODialect, qtensor::QTensorDialect,
arith::ArithDialect, cf::ControlFlowDialect,
func::FuncDialect, scf::SCFDialect, LLVM::LLVMDialect,
memref::MemRefDialect, jeff::JeffDialect>();
registerBuiltinDialectTranslation(registry);
registerLLVMDialectTranslation(registry);
auto context = std::make_shared<MLIRContext>(registry);
context->loadAllAvailableDialects();
return context;
}
[[nodiscard]] static FailureOr<OwningOpRef<ModuleOp>>
parseMLIRString(MLIRContext* context, const StringRef source) {
auto mod = parseSourceString<ModuleOp>(source, context);
if (!mod) {
return emitError(UnknownLoc::get(context),
"failed to parse MLIR source string");
}
return std::move(mod);
}
[[nodiscard]] static LogicalResult
openSourceMgr(const std::filesystem::path& path, MLIRContext* context,
llvm::SourceMgr& sourceMgr) {
std::string errorMessage;
auto file = openInputFile(path.string(), &errorMessage);
if (!file) {
return emitError(UnknownLoc::get(context))
<< "failed to load file '" << path.string() << "': " << errorMessage;
}
sourceMgr.AddNewSourceBuffer(std::move(file), SMLoc());
return success();
}
[[nodiscard]] static FailureOr<OwningOpRef<ModuleOp>>
parseMLIRFile(MLIRContext* context, const std::filesystem::path& path) {
llvm::SourceMgr sourceMgr;
if (failed(openSourceMgr(path, context, sourceMgr))) {
return failure();
}
auto mod = parseSourceFile<ModuleOp>(sourceMgr, context);
if (!mod) {
return emitError(UnknownLoc::get(context))
<< "failed to parse MLIR file '" << path.string() << "'";
}
return std::move(mod);
}
/**
* @brief Check whether a module contains an operation from a dialect.
*/
[[nodiscard]] static bool moduleUsesDialect(ModuleOp mod,
const StringRef dialect) {
auto found = false;
mod->walk([&](Operation* operation) {
found |= operation->getDialect()->getNamespace() == dialect;
});
return found;
}
template <class ProgramType, class Parse>
[[nodiscard]] static std::optional<ProgramType>
parseTypedProgram(const StringRef dialect, Parse&& parse) {
auto context = createCompilerContext();
auto mod = std::forward<Parse>(parse)(context.get());
if (failed(mod)) {
return std::nullopt;
}
if (!moduleUsesDialect(**mod, dialect)) {
(**mod)->emitError() << "expected a module using the '" << dialect
<< "' dialect";
return std::nullopt;
}
return ProgramType({.context = std::move(context), .mod = std::move(*mod)});
}
[[nodiscard]] static LogicalResult
runPasses(ModuleOp mod,
const llvm::function_ref<void(OpPassManager&)> populatePasses,
const StringRef failureMessage, const bool enableTiming = false,
const bool enableStatistics = false) {
PassManager pm(mod.getContext());
if (enableTiming) {
pm.enableTiming();
}
if (enableStatistics) {
pm.enableStatistics();
}
populatePasses(pm);
if (failed(pm.run(mod))) {
return mod.emitError(failureMessage);
}
return success();
}
//===----------------------------------------------------------------------===//
// Program
//===----------------------------------------------------------------------===//
Program::Program(Storage storage) : storage_(std::move(storage)) {}
bool Program::isValid() const noexcept {
return static_cast<bool>(storage_.mod);
}
ModuleOp Program::mod() const {
assert(storage_.mod && "cannot use a consumed compiler program");
return *storage_.mod;
}
std::string Program::str() const {
std::string result;
llvm::raw_string_ostream stream(result);
mod().print(stream);
return result;
}
Program::Storage Program::cloneStorage() const {
const auto cloned = cast<ModuleOp>(mod()->clone());
return {.context = storage_.context, .mod = OwningOpRef<ModuleOp>(cloned)};
}
Program::Storage Program::releaseStorage() && {
assert(storage_.mod && "compiler program was already consumed");
return {.context = std::move(storage_.context),
.mod = std::move(storage_.mod)};
}
//===----------------------------------------------------------------------===//
// OpenQASMProgram
//===----------------------------------------------------------------------===//
const std::string& OpenQASMProgram::source() const noexcept { return source_; }
const std::string& OpenQASMProgram::str() const noexcept { return source_; }
bool OpenQASMProgram::write(const std::filesystem::path& path) const {
std::error_code error;
llvm::raw_fd_ostream stream(path.string(), error, llvm::sys::fs::OF_Text);
if (error) {
llvm::errs() << "failed to open OpenQASM output file '" << path.string()
<< "': " << error.message() << '\n';
return false;
}
stream << source_;
stream.flush();
if (stream.has_error()) {
llvm::errs() << "failed to write OpenQASM file '" << path.string() << "'\n";
return false;
}
return true;
}
//===----------------------------------------------------------------------===//
// QCProgram
//===----------------------------------------------------------------------===//
std::optional<QCProgram>
QCProgram::fromMLIRString(const std::string_view source) {
return parseTypedProgram<QCProgram>("qc", [source](MLIRContext* context) {
return parseMLIRString(context, source);
});
}
std::optional<QCProgram>
QCProgram::fromMLIRFile(const std::filesystem::path& path) {
return parseTypedProgram<QCProgram>("qc", [&path](MLIRContext* context) {
return parseMLIRFile(context, path);
});
}
std::optional<QCProgram>
QCProgram::fromQASMString(const std::string_view source) {
auto context = createCompilerContext();
auto mod = qc::translateQASM3ToQC(source, context.get());
if (!mod) {
emitError(UnknownLoc::get(context.get()),
"failed to translate OpenQASM 3 source to QC");
return std::nullopt;
}
return QCProgram({.context = std::move(context), .mod = std::move(mod)});
}
std::optional<QCProgram>
QCProgram::fromQASMFile(const std::filesystem::path& path) {
auto context = createCompilerContext();
llvm::SourceMgr sourceMgr;
if (failed(openSourceMgr(path, context.get(), sourceMgr))) {
return std::nullopt;
}
auto mod = qc::translateQASM3ToQC(sourceMgr, context.get());
if (!mod) {
emitError(UnknownLoc::get(context.get()))
<< "failed to translate OpenQASM 3 file '" << path.string()
<< "' to QC";
return std::nullopt;
}
return QCProgram({.context = std::move(context), .mod = std::move(mod)});
}
std::optional<QCProgram>
QCProgram::fromQuantumComputation(const ::qc::QuantumComputation& computation) {
auto context = createCompilerContext();
auto mod = translateQuantumComputationToQC(context.get(), computation);
if (!mod) {
emitError(UnknownLoc::get(context.get()),
"failed to translate QuantumComputation to QC");
return std::nullopt;
}
return QCProgram({.context = std::move(context), .mod = std::move(mod)});
}
QCProgram QCProgram::copy() const { return QCProgram(cloneStorage()); }
bool QCProgram::cleanup() {
return succeeded(runPasses(mod(), populateQCCleanupPipeline,
"failed to run the QC cleanup pipeline"));
}
bool QCProgram::normalizeGlobalPhases() {
return succeeded(mlir::mqt::normalizeGlobalPhases(mod()));
}
std::optional<OpenQASMProgram> QCProgram::toOpenQASM3() const {
auto cleaned = copy();
if (!cleaned.cleanup()) {
return std::nullopt;
}
auto source = qc::translateQCToOpenQASM3(cleaned.mod());
if (failed(source)) {
return std::nullopt;
}
return OpenQASMProgram(std::move(*source));
}
std::optional<QCOProgram> QCProgram::intoQCO() && {
if (failed(runPasses(
mod(), [](OpPassManager& pm) { pm.addPass(createQCToQCO()); },
"failed to convert QC to QCO"))) {
return std::nullopt;
}
return QCOProgram(std::move(*this).releaseStorage());
}
std::optional<QIRProgram> QCProgram::intoQIR(const QIRProfile profile) && {
if (failed(runPasses(
mod(),
[profile](OpPassManager& pm) {
if (profile == QIRProfile::Adaptive) {
pm.addPass(createQCToQIRAdaptive());
} else {
pm.addPass(createQCToQIRBase());
}
},
"failed to convert QC to QIR"))) {
return std::nullopt;
}
auto result = QIRProgram(std::move(*this).releaseStorage(), profile);
if (!result.cleanup()) {
return std::nullopt;
}
return result;
}
//===----------------------------------------------------------------------===//
// QCOProgram
//===----------------------------------------------------------------------===//
std::optional<QCOProgram>
QCOProgram::fromMLIRString(const std::string_view source) {
return parseTypedProgram<QCOProgram>("qco", [source](MLIRContext* context) {
return parseMLIRString(context, source);
});
}
std::optional<QCOProgram>
QCOProgram::fromMLIRFile(const std::filesystem::path& path) {
return parseTypedProgram<QCOProgram>("qco", [&path](MLIRContext* context) {
return parseMLIRFile(context, path);
});
}
QCOProgram QCOProgram::copy() const { return QCOProgram(cloneStorage()); }
bool QCOProgram::cleanup() {
return succeeded(runPasses(mod(), populateQCOCleanupPipeline,
"failed to run the QCO cleanup pipeline"));
}
bool QCOProgram::normalizeGlobalPhases() {
return succeeded(mlir::mqt::normalizeGlobalPhases(mod()));
}
bool QCOProgram::runPassPipeline(const std::string_view pipeline,
const bool enableTiming,
const bool enableStatistics) {
return succeeded(
::runPassPipeline(mod(), pipeline, enableTiming, enableStatistics));
}
bool QCOProgram::mergeSingleQubitRotationGates() {
return succeeded(runPasses(
mod(),
[](OpPassManager& pm) {
pm.addPass(qco::createMergeSingleQubitRotationGates());
},
"failed to merge single-qubit rotation gates"));
}
bool QCOProgram::fuseSingleQubitUnitaryRuns(const std::string_view basis) {
qco::FuseSingleQubitUnitaryRunsOptions options;
options.basis = basis;
return succeeded(runPasses(
mod(),
[&options](OpPassManager& pm) {
pm.addPass(qco::createFuseSingleQubitUnitaryRuns(options));
},
"failed to fuse single-qubit unitary runs"));
}
bool QCOProgram::unrollQuantumLoops(const int64_t factor) {
qco::QuantumLoopUnrollOptions options;
options.unrollFactor = factor;
return succeeded(runPasses(
mod(),
[&options](OpPassManager& pm) {
pm.addNestedPass<func::FuncOp>(qco::createQuantumLoopUnroll(options));
},
"failed to unroll quantum loops"));
}
bool QCOProgram::liftHadamards() {
return succeeded(runPasses(
mod(),
[](OpPassManager& pm) { pm.addPass(qco::createHadamardLifting()); },
"failed to lift Hadamard gates"));
}
bool QCOProgram::reuseQubits() {
return succeeded(runPasses(
mod(), [](OpPassManager& pm) { pm.addPass(qco::createReuseQubits()); },
"failed to reuse qubits"));
}
bool QCOProgram::runQubitReusePipeline() {
return succeeded(runPasses(
mod(), [](OpPassManager& pm) { populateQubitReusePipeline(pm); },
"failed to run the qubit reuse pipeline"));
}
bool QCOProgram::decomposeMultiControlled(const uint64_t minQubits) {
return succeeded(runPasses(
mod(),
[minQubits](OpPassManager& pm) {
populateDecomposeMultiControlledPipeline(pm, minQubits);
},
"failed to decompose multi-controlled gates"));
}
bool QCOProgram::compileForTarget(const CompilerTarget& target,
const bool enableTiming,
const bool enableStatistics) {
return succeeded(runPasses(
mod(),
[&target](OpPassManager& pm) {
populateTargetCompilationPipeline(pm, target);
},
"failed to compile the QCO program for the target", enableTiming,
enableStatistics));
}
std::optional<QCProgram> QCOProgram::intoQC() && {
if (failed(runPasses(
mod(), [](OpPassManager& pm) { pm.addPass(createQCOToQC()); },
"failed to convert QCO to QC"))) {
return std::nullopt;
}
return QCProgram(std::move(*this).releaseStorage());
}
std::optional<JeffProgram> QCOProgram::intoJeff() && {
if (failed(runPasses(
mod(), [](OpPassManager& pm) { pm.addPass(createQCOToJeff()); },
"failed to convert QCO to jeff"))) {
return std::nullopt;
}
return JeffProgram(std::move(*this).releaseStorage());
}
//===----------------------------------------------------------------------===//
// JeffProgram
//===----------------------------------------------------------------------===//
std::optional<JeffProgram>
JeffProgram::fromBytes(const std::span<const std::byte> bytes) {
if (bytes.size() % sizeof(capnp::word) != 0U) {
auto context = createCompilerContext();
emitError(UnknownLoc::get(context.get()),
"jeff data size must be a multiple of the Cap'n Proto word size");
return std::nullopt;
}
auto words = kj::heapArray<capnp::word>(bytes.size() / sizeof(capnp::word));
std::memcpy(words.begin(), bytes.data(), bytes.size());
auto context = createCompilerContext();
auto mod = deserialize(context.get(), words.asPtr());
if (!mod) {
emitError(UnknownLoc::get(context.get()),
"failed to deserialize jeff bytes");
return std::nullopt;
}
return JeffProgram({.context = std::move(context), .mod = std::move(mod)});
}
std::optional<JeffProgram>
JeffProgram::fromFile(const std::filesystem::path& path) {
auto context = createCompilerContext();
auto mod = deserializeFromFile(context.get(), path.string());
if (!mod) {
emitError(UnknownLoc::get(context.get()))
<< "failed to deserialize jeff file '" << path.string() << "'";
return std::nullopt;
}
return JeffProgram({.context = std::move(context), .mod = std::move(mod)});
}
JeffProgram JeffProgram::copy() const { return JeffProgram(cloneStorage()); }
bool JeffProgram::cleanup() {
return succeeded(runPasses(mod(), populateJeffCleanupPipeline,
"failed to run the jeff cleanup pipeline"));
}
std::vector<std::byte> JeffProgram::toBytes() const {
const auto serialized = serialize(mod());
const auto bytes = serialized.asBytes();
std::vector<std::byte> result(bytes.size());
std::memcpy(result.data(), bytes.begin(), bytes.size());
return result;
}
bool JeffProgram::write(const std::filesystem::path& path) const {
if (failed(serializeToFile(mod(), path.string()))) {
mod().emitError() << "failed to write jeff file '" << path.string() << "'";
return false;
}
return true;
}
std::optional<QCOProgram> JeffProgram::intoQCO() && {
if (failed(runPasses(
mod(), [](OpPassManager& pm) { pm.addPass(createJeffToQCO()); },
"failed to convert jeff to QCO"))) {
return std::nullopt;
}
return QCOProgram(std::move(*this).releaseStorage());
}
//===----------------------------------------------------------------------===//
// QIRProgram
//===----------------------------------------------------------------------===//
QIRProgram::QIRProgram(Storage storage, const QIRProfile profile)
: Program(std::move(storage)), profile_(profile) {}
QIRProgram QIRProgram::copy() const { return {cloneStorage(), profile_}; }
bool QIRProgram::cleanup() {
return succeeded(runPasses(
mod(),
[this](OpPassManager& pm) {
populateQIRCleanupPipeline(pm, profile_ == QIRProfile::Adaptive);
},
"failed to run the QIR cleanup pipeline"));
}
QIRProfile QIRProgram::profile() const noexcept { return profile_; }
[[nodiscard]] static std::unique_ptr<llvm::Module>
translateToLLVM(ModuleOp mod, llvm::LLVMContext& context) {
auto llvmModule = translateModuleToLLVMIR(mod, context);
if (!llvmModule) {
mod.emitError("failed to translate QIR MLIR to LLVM IR");
}
return llvmModule;
}
std::optional<std::string> QIRProgram::llvmIR() const {
llvm::LLVMContext context;
auto llvmModule = translateToLLVM(mod(), context);
if (!llvmModule) {
return std::nullopt;
}
std::string result;
llvm::raw_string_ostream stream(result);
llvmModule->print(stream, nullptr);
return result;
}
std::optional<std::vector<std::byte>> QIRProgram::toBitcode() const {
llvm::LLVMContext context;
auto llvmModule = translateToLLVM(mod(), context);
if (!llvmModule) {
return std::nullopt;
}
SmallVector<char> storage;
llvm::raw_svector_ostream stream(storage);
llvm::WriteBitcodeToFile(*llvmModule, stream);
std::vector<std::byte> result(storage.size());
std::memcpy(result.data(), storage.data(), storage.size());
return result;
}
bool QIRProgram::writeBitcode(const std::filesystem::path& path) const {
llvm::LLVMContext context;
auto llvmModule = translateToLLVM(mod(), context);
if (!llvmModule) {
return false;
}
std::error_code error;
llvm::raw_fd_ostream stream(path.string(), error, llvm::sys::fs::OF_None);
if (error) {
mod().emitError() << "failed to open bitcode output file '" << path.string()
<< "': " << error.message();
return false;
}
llvm::WriteBitcodeToFile(*llvmModule, stream);
stream.flush();
if (stream.has_error()) {
mod().emitError() << "failed to write bitcode file '" << path.string()
<< "'";
return false;
}
return true;
}
//===----------------------------------------------------------------------===//
// Pipeline
//===----------------------------------------------------------------------===//
std::optional<CompilerProgram>
runDefaultPipeline(CompilerInput&& program, const ProgramFormat output,
const CompilerTarget* const target,
const std::string_view qcoPipeline, const bool enableTiming,
const bool enableStatistics) {
if (target != nullptr &&
(output == ProgramFormat::QCImport || output == ProgramFormat::QCO ||
output == ProgramFormat::Jeff)) {
llvm::errs()
<< "a compiler target requires QCOOptimized, QC, OpenQASM3, or QIR "
"output.\n";
return std::nullopt;
}
if (target != nullptr && qcoPipeline != "mqt-qco-default") {
llvm::errs() << "a custom QCO pass pipeline cannot be combined with a "
"compiler target.\n";
return std::nullopt;
}
if ((output == ProgramFormat::QCImport || output == ProgramFormat::QCO) &&
qcoPipeline != "mqt-qco-default") {
llvm::errs() << "a custom QCO pass pipeline cannot be used with an output "
"that stops before QCO optimization.\n";
return std::nullopt;
}
if (output == ProgramFormat::QCImport) {
if (std::holds_alternative<QCProgram>(program)) {
return CompilerProgram(std::move(std::get<QCProgram>(program)));
}
if (std::holds_alternative<OpenQASMProgram>(program)) {
auto qc = QCProgram::fromQASMString(
std::get<OpenQASMProgram>(program).source());
if (qc) {
return CompilerProgram(std::move(*qc));
}
}
llvm::errs() << "QCImport output is only available for QC or OpenQASM "
"input.\n";
return std::nullopt;
}
auto qco = std::visit(
[]<typename T>(T&& value) -> std::optional<QCOProgram> {
using ProgramType = std::remove_cvref_t<T>;
if constexpr (std::is_same_v<ProgramType, QCOProgram>) {
return std::forward<T>(value);
} else if constexpr (std::is_same_v<ProgramType, OpenQASMProgram>) {
auto qc = QCProgram::fromQASMString(value.source());
if (!qc) {
return std::nullopt;
}
return std::move(*qc).intoQCO();
} else {
return std::forward<T>(value).intoQCO();
}
},
std::move(program));
if (!qco) {
return std::nullopt;
}
if (output == ProgramFormat::QCO) {
return CompilerProgram(std::move(*qco));
}
if (target != nullptr) {
if (!qco->compileForTarget(*target, enableTiming, enableStatistics)) {
return std::nullopt;
}
} else {
if (!qco->cleanup() ||
!qco->runPassPipeline(qcoPipeline, enableTiming, enableStatistics) ||
!qco->cleanup()) {
return std::nullopt;
}
}
if (output == ProgramFormat::QCOOptimized) {
return CompilerProgram(std::move(*qco));
}
if (output == ProgramFormat::Jeff) {
auto jeff = std::move(*qco).intoJeff();
if (!jeff || !jeff->cleanup()) {
return std::nullopt;
}
return CompilerProgram(std::move(*jeff));
}
auto qc = std::move(*qco).intoQC();
if (!qc || !qc->cleanup()) {
return std::nullopt;
}
if (output == ProgramFormat::QC) {
return CompilerProgram(std::move(*qc));
}
if (output == ProgramFormat::OpenQASM3) {
auto openQASM = qc->toOpenQASM3();
if (!openQASM) {
return std::nullopt;
}
return CompilerProgram(std::move(*openQASM));
}
const auto profile = output == ProgramFormat::QIRAdaptive
? QIRProfile::Adaptive
: QIRProfile::Base;
auto qir = std::move(*qc).intoQIR(profile);
if (!qir) {
return std::nullopt;
}
return CompilerProgram(std::move(*qir));
}
} // namespace mlir