staq_compiler.cpp 15.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*******************************************************************************
 * Copyright (c) 2020 UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompanies this
 * distribution. The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
 *License is available at https://eclipse.org/org/documents/edl-v10.php
 *
 * Contributors:
 *   Alexander J. McCaskey - initial API and implementation
 *******************************************************************************/
#include "staq_compiler.hpp"

#include "xacc.hpp"
#include "xacc_service.hpp"

#include "InstructionIterator.hpp"
#include "AcceleratorBuffer.hpp"

21
22
#include "staq_visitors.hpp"

23
24
25
26
27
#include "transformations/desugar.hpp"
#include "transformations/inline.hpp"
#include "transformations/oracle_synthesizer.hpp"
#include "optimization/simplify.hpp"

28
29
#include "output/cirq.hpp"

30
31
#include <streambuf>

32
33
34
35
using namespace staq::ast;

namespace xacc {

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
static std::vector<std::string> builtins{
    "u3", "u2",   "u1",  "cx",  "id",  "u0",  "x",   "y",  "z",
    "h",  "s",    "sdg", "t",   "tdg", "rx",  "ry",  "rz", "cz",
    "cy", "swap", "ch",  "ccx", "crz", "cu1", "cu2", "cu3"};

static std::map<std::string, std::string> missing_builtins{
    {"u", R"#(
gate u(theta,phi,lambda) q { U(theta,phi,lambda) q; })#"},
    {"p", R"#(gate p(theta) a
{
  rz(theta) a;
})#"},
    {"sx", R"#(gate sx a { sdg a; h a; sdg a; })#"},
    {"sxdg", R"#(gate sxdg a { s a; h a; s a; })#"},
    {"cswap", R"#(gate cswap a,b,c
{
  cx c,b;
  ccx a,b,c;
  cx c,b;
})#"},
    {"crx", R"#(gate crx(lambda) a,b
{
  u1(pi/2) b;
  cx a,b;
  u3(-lambda/2,0,0) b;
  cx a,b;
  u3(lambda/2,-pi/2,0) b;
})#"},
    {"cry", R"#(gate cry(lambda) a,b
{
  u3(lambda/2,0,0) b;
  cx a,b;
  u3(-lambda/2,0,0) b;
  cx a,b;
})#"},
    {"cp", R"#(gate cp(lambda) a,b
{
  p(lambda/2) a;
  cx a,b;
  p(-lambda/2) b;
  cx a,b;
  p(lambda/2) b;
})#"},
    {"csx", R"#(gate csx a,b { h b; cu1(pi/2) a,b; h b; })#"},
    {"cu", R"#(gate cu(theta,phi,lambda,gamma) c, t
{ p(gamma) c;
  p((lambda+phi)/2) c;
  p((lambda-phi)/2) t;
  cx c,t;
  u(-theta/2,0,-(phi+lambda)/2) t;
  cx c,t;
  u(theta/2,phi,0) t;
})#"},
    {"rxx", R"#(gate rxx(theta) a,b
{
  u3(pi/2, theta, 0) a;
  h b;
  cx a,b;
  u1(-theta) b;
  cx a,b;
  h b;
  u2(-pi, pi-theta) a;
})#"},
    {"rzz", R"#(gate rzz(theta) a,b
{
  cx a,b;
  u1(theta) b;
  cx a,b;
})#"},
    {"rccx", R"#(gate rccx a,b,c
{
  u2(0,pi) c;
  u1(pi/4) c;
  cx b, c;
  u1(-pi/4) c;
  cx a, c;
  u1(pi/4) c;
  cx b, c;
  u1(-pi/4) c;
  u2(0,pi) c;
})#"}};

118
119
StaqCompiler::StaqCompiler() {}

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
bool StaqCompiler::canParse(const std::string &src) {
  std::string _src = src;
  bool isXaccKernel = false;
  std::string prototype;
  auto xasm = xacc::getCompiler("xasm");

  /** staq prints to cerr, override this **/
  class buffer_override {
    std::ostream &os;
    std::streambuf *buf;

  public:
    buffer_override(std::ostream &os) : os(os), buf(os.rdbuf()) {}

    ~buffer_override() { os.rdbuf(buf); }
  };

  buffer_override b(std::cerr);
  std::stringstream xx;

  std::cerr.rdbuf(xx.rdbuf());

  /** --------------------------------- **/

  if (src.find("__qpu__") != std::string::npos) {
    prototype = _src.substr(0, _src.find_first_of("{")) + "{}";
    auto bufferNames = xasm->getKernelBufferNames(prototype);

    isXaccKernel = true;

    std::string tmp = "";
    auto first = _src.find_first_of("{");
    auto last = _src.find_last_of("}");
    auto sub = _src.substr(first + 1, last - first - 1);
    auto lines = xacc::split(sub, '\n');
    bool addedNames = false;
    for (auto &l : lines) {
      xacc::trim(l);
      if (l.find("measure") != std::string::npos) {
159
160
        // don't add measures
        continue;
161
162
163
164
165
166
167
168
169
170
171
172
173
      }
      tmp += l + "\n";
      if (l.find("include") != std::string::npos) {
        for (auto &b : bufferNames) {
          auto size = std::numeric_limits<int>::max();
          tmp += "qreg " + b + "[" + std::to_string(size) + "];\n";
        }
        addedNames = true;
      }
    }
    _src = tmp;
    if (!addedNames) {
      for (auto &b : bufferNames) {
174
        auto size = std::numeric_limits<int>::max();
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
        _src = "qreg " + b + "[" + std::to_string(size) + "];\n" + _src;
      }
    }
  }

  // we allow users to leave out OPENQASM 2.0 and include qelib.inc
  // If they did we need to add it for them
  std::string tmp = "";
  auto lines = xacc::split(_src, '\n');
  bool foundOpenQasm = false, foundInclude = false;
  for (auto &l : lines) {
    if (l.find("OPENQASM") != std::string::npos) {
      foundOpenQasm = true;
    }
    if (l.find("include") != std::string::npos) {
      foundInclude = true;
    }
  }

  if (!foundInclude) {
    _src = "include \"qelib1.inc\";\n" + _src;
  }
  if (!foundOpenQasm) {
    _src = "OPENQASM 2.0;\n" + _src;
  }

201
  // std::cout << " HELLO:\n" << _src << "\n";
202
203
204
205
206
207
208
209
210
211
  using namespace staq;

  try {
    auto prog = parser::parse_string(_src);
    return true;
  } catch (std::exception &e) {
    return false;
  }
}

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
std::shared_ptr<IR> StaqCompiler::compile(const std::string &src,
                                          std::shared_ptr<Accelerator> acc) {
  // IF src contains typical xacc quantum kernel prototype, then take
  // buffers names and add qreg declarations before parsing
  // IF it does not, then assume qreg decls already declared.
  auto xasm = xacc::getCompiler("xasm");
  std::string prototype;

  std::string _src = src;
  bool isXaccKernel = false;
  if (src.find("__qpu__") != std::string::npos) {
    prototype = _src.substr(0, _src.find_first_of("{")) + "{}";
    auto bufferNames = xasm->getKernelBufferNames(prototype);

    isXaccKernel = true;

    std::string tmp = "";
    auto first = _src.find_first_of("{");
    auto last = _src.find_last_of("}");
    auto sub = _src.substr(first + 1, last - first - 1);
    auto lines = xacc::split(sub, '\n');
233
    bool addedNames = false;
234
235
236
237
238
239
240
241
    for (auto &l : lines) {
      xacc::trim(l);
      tmp += l + "\n";
      if (l.find("include") != std::string::npos) {
        for (auto &b : bufferNames) {
          auto size = xacc::getBuffer(b)->size();
          tmp += "qreg " + b + "[" + std::to_string(size) + "];\n";
        }
242
        addedNames = true;
243
244
245
      }
    }
    _src = tmp;
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    if (!addedNames) {
      for (auto &b : bufferNames) {
        auto size = xacc::getBuffer(b)->size();
        _src = "qreg " + b + "[" + std::to_string(size) + "];\n" + _src;
      }
    }
  }

  // we allow users to leave out OPENQASM 2.0 and include qelib.inc
  // If they did we need to add it for them
  std::string tmp = "";
  auto lines = xacc::split(_src, '\n');
  bool foundOpenQasm = false, foundInclude = false;
  for (auto &l : lines) {
    if (l.find("OPENQASM") != std::string::npos) {
      foundOpenQasm = true;
    }
    if (l.find("include") != std::string::npos) {
      foundInclude = true;
    }
266
267
  }

268
269
270
271
272
273
  if (!foundInclude) {
    _src = "include \"qelib1.inc\";\n" + _src;
  }
  if (!foundOpenQasm) {
    _src = "OPENQASM 2.0;\n" + _src;
  }
274

275
276
277
278
279
280
281
  const std::string preamble = [](const std::string &srcTxt) {
    const auto includePos = srcTxt.find("include");
    assert(includePos != std::string::npos);
    const auto endPreample = srcTxt.find_first_of(";", includePos);
    assert(endPreample != std::string::npos);
    return srcTxt.substr(includePos, endPreample - includePos + 1);
  }(_src);
282
  auto preamble_start = _src.find(preamble);
283
  assert(preamble_start != std::string::npos);
284
285

  // Add any required missing pre-defines that we 
286
287
288
289
290
291
292
293
294
295
  // know the impl for.
  std::vector<std::string> added;
  std::string extra_insts = "\n";
  bool hasMeasures = false;
  auto tmp_lines = split(_src, '\n');
  for (auto line : tmp_lines) {
    if (line.find("OPENQASM") == std::string::npos &&
        line.find("include") == std::string::npos &&
        line.find("measure") == std::string::npos &&
        line.find("qreg") == std::string::npos &&
296
297
        line.find("creg") == std::string::npos
        && !line.empty()) {
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
      auto inst_name = split(line, ' ')[0];
      if (inst_name.find("(") != std::string::npos) {
        inst_name = inst_name.substr(0, inst_name.find("("));
      }
      if (std::find(builtins.begin(), builtins.end(), inst_name) ==
              builtins.end() &&
          std::find(added.begin(), added.end(), inst_name) == added.end()) {
        extra_insts += missing_builtins[inst_name] + "\n";
        added.push_back(inst_name);
      }
    }
  }
  _src.insert(preamble_start+preamble.length(), extra_insts);


313
  using namespace staq;
314
315
  ast::ptr<ast::Program> prog;
  try {
316
    prog = parser::parse_string(_src);
317
318
        // transformations::inline_ast(*prog);

319
320
321
322
323
324
325
326
    transformations::desugar(*prog);
    transformations::synthesize_oracles(*prog);
  } catch (std::exception &e) {
    std::stringstream ss;
    ss << e.what();
    ss << "\nXACC Error in Staq Compiler, here was the src:\n" << src << "\n";
    xacc::error(ss.str());
  }
327

328
329
  if (run_staq_optimize)
    optimization::simplify(*prog);
330

331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
  // at this point we have to find out if we have any ancilla
  // registers
  internal_staq::CountAncillas ancillas;
  dynamic_cast<ast::Traverse &>(ancillas).visit(*prog);

  // add ancilla registers to xacc
  for (auto &kv : ancillas.ancillas) {
    if (!xacc::hasBuffer(kv.first)) {
      auto q = xacc::qalloc(kv.second);
      q->setName(kv.first);
      xacc::storeBuffer(q);
    } else {
      xacc::getBuffer(kv.first)->resetBuffer();
    }
  }

  transformations::inline_ast(
      *prog, {false, transformations::default_overrides, "anc"});

350
  //   std::cout <<"PROG: " << *prog << "\n";
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
  
  // Determine the number of qreqs
  internal_staq::CountQregs countQreq;
  dynamic_cast<ast::Traverse &>(countQreq).visit(*prog);
  const auto nbQreqs = countQreq.qregs.size() + ancillas.ancillas.size();
  // Direct Staq's AST -> XACC's IR translation:
  // This can only be used (reliably) for simple QASM source,
  // that uses a single qreg (we can use simple qubit indexing to construct IR)
  // Note: we don't handle *embedded* QASM source in this direct translate mode.
  if (!isXaccKernel && nbQreqs == 1) {
    // Create a temporary kernel name:
    std::string name = "tmp";
    if (xacc::hasCompiled(name)) {
      int counter = 0;
      while (true) {
        name = "tmp" + std::to_string(counter);
        if (!xacc::hasCompiled(name)) {
          break;
        }
        counter++;
      }
    }

    // Direct translation
375
    internal_staq::StaqToIr translate(name, countQreq.qregs[0]);
376
377
378
    translate.visit(*prog);
    return translate.getIr();
  }
379

380
381
  // Otherwise, translate Staq's AST to XASM source string
  // then recompile.
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
  internal_staq::StaqToXasm translate;
  translate.visit(*prog);

  std::string kernel;
  if (isXaccKernel) {
    if (!ancillas.ancillas.empty()) {
      kernel = prototype.substr(0, prototype.find_first_of(")"));
      for (auto &kv : ancillas.ancillas) {
        kernel += ", qreg " + kv.first;
      }
      kernel += ") {\n" + translate.ss.str() + "}";
    } else {
      kernel = prototype.substr(0, prototype.length() - 1) + "\n" +
               translate.ss.str() + "}";
    }
  } else {
    internal_staq::CountQregs c;
    dynamic_cast<ast::Traverse &>(c).visit(*prog);

    std::stringstream xx;
    std::string name = "tmp";
    if (xacc::hasCompiled(name)) {
404
405
406
407
408
      int counter = 0;
      while (true) {
        name = "tmp" + std::to_string(counter);
        if (!xacc::hasCompiled(name)) {
          break;
409
        }
410
411
        counter++;
      }
412
    }
413
    xx << "__qpu__ void " << name << "(";
414
415
416
417
418
419
420
421
422
423
    xx << "qreg " << c.qregs[0];
    for (int i = 1; i < c.qregs.size(); i++) {
      xx << ", qreg " << c.qregs[i];
    }
    for (auto &kv : ancillas.ancillas) {
      xx << ", qreg " << kv.first;
    }
    xx << ") {\n" << translate.ss.str() << "}";
    kernel = xx.str();
  }
424
  // std::cout << "\n\nFinal:\n" << kernel << "\n";
425
426
427
428
429
430
431
432
433
  return xasm->compile(kernel, acc);
}

std::shared_ptr<IR> StaqCompiler::compile(const std::string &src) {
  return compile(src, nullptr);
}

const std::string
StaqCompiler::translate(std::shared_ptr<xacc::CompositeInstruction> function) {
434
  std::map<std::string, int> bufNamesToSize;
435
  std::map<std::string, int> cRegNamesToSize;
436
  InstructionIterator iter(function);
437
  // First search buffer names and see if we have
438
  while (iter.hasNext()) {
439
    auto &next = *iter.next();
440
    if (!next.isComposite() && next.isEnabled()) {
441
442
443
444
445
446
447
448
449
450
451
      if (next.name() == "Measure") {
        xacc::quantum::Measure &m = (xacc::quantum::Measure &)next;
        if (m.hasClassicalRegAssignment()) {
          auto cregName = next.getBufferName(1);
          int size = m.getClassicalBitIndex() + 1;
          if (cRegNamesToSize.count(cregName)) {
            if (cRegNamesToSize[cregName] < size) {
              cRegNamesToSize[cregName] = size;
            }
          } else {
            cRegNamesToSize.insert({cregName, size});
452
453
          }
        } else {
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
          auto bufName = next.getBufferName(0);
          int size = next.bits()[0] + 1;
          if (bufNamesToSize.count(bufName)) {
            if (bufNamesToSize[bufName] < size) {
              bufNamesToSize[bufName] = size;
            }
          } else {
            bufNamesToSize.insert({bufName, size});
          }
        }
      } else {
        for (int i = 0; i < next.nRequiredBits(); i++) {
          auto bufName = next.getBufferName(i);
          int size = next.bits()[i] + 1;
          if (bufNamesToSize.count(bufName)) {
            if (bufNamesToSize[bufName] < size) {
              bufNamesToSize[bufName] = size;
            }
          } else {
            bufNamesToSize.insert({bufName, size});
          }
475
        }
476
      }
477
478
479
    }
  }

480
  auto translate =
481
482
483
484
      cRegNamesToSize.empty()
          ? std::make_shared<internal_staq::XACCToStaqOpenQasm>(bufNamesToSize)
          : std::make_shared<internal_staq::XACCToStaqOpenQasm>(
                bufNamesToSize, cRegNamesToSize);
485
  InstructionIterator iter2(function);
486
  while (iter2.hasNext()) {
487
488
    auto &next = *iter2.next();
    if (next.isEnabled()) {
489
      next.accept(translate);
490
491
492
493
    }
  }

  return translate->ss.str();
494
}
495
496
497

const std::string
StaqCompiler::translate(std::shared_ptr<CompositeInstruction> program,
498
                        HeterogeneousMap &options) {
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
  if (options.stringExists("lang-type")) {
    auto langType = options.getString("lang-type");

    // map xacc to staq program
    std::map<std::string, int> bufNamesToSize;
    InstructionIterator iter(program);
    // First search buffer names and see if we have
    while (iter.hasNext()) {
      auto &next = *iter.next();
      if (next.isEnabled()) {
        for (int i = 0; i < next.nRequiredBits(); i++) {
          auto bufName = next.getBufferName(i);
          int size = next.bits()[i] + 1;
          if (bufNamesToSize.count(bufName)) {
            if (bufNamesToSize[bufName] < size) {
              bufNamesToSize[bufName] = size;
            }
          } else {
            bufNamesToSize.insert({bufName, size});
          }
        }
      }
    }
    auto translate =
        std::make_shared<internal_staq::XACCToStaqOpenQasm>(bufNamesToSize);
    InstructionIterator iter2(program);
    while (iter2.hasNext()) {
      auto &next = *iter2.next();
      if (next.isEnabled()) {
        next.accept(translate);
      }
    }
    // std::cout << "HELLO:\n" << translate->ss.str() << "\n";
    using namespace staq;
    auto prog = parser::parse_string(translate->ss.str());
    transformations::desugar(*prog);
    transformations::synthesize_oracles(*prog);

    optimization::simplify(*prog);

    std::stringstream ss;
    if (langType == "cirq") {
      staq::output::CirqOutputter outputter(ss);
      outputter.run(*prog);
    }

    return ss.str();

  } else {
    return translate(program);
  }
}

552
} // namespace xacc