Commit 29845df3 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

Reworked qcor python script, got it working with cmake, pretty cool

parent 8828e394
Loading
Loading
Loading
Loading
+58 −38
Original line number Diff line number Diff line
@@ -22,8 +22,8 @@

#include "fuzzy_parsing.hpp"

#include "qcor_ast_consumer.hpp"
#include "XACC.hpp"
#include "qcor_ast_consumer.hpp"
#include "xacc_service.hpp"

using namespace clang;
@@ -46,21 +46,18 @@ protected:

  void ExecuteAction() override {
    CompilerInstance &CI = getCompilerInstance();
    // CI.getLangOpts().CPlusPlus14 = 1;
    CI.createSema(getTranslationUnitKind(), nullptr);
    rewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts());

    // auto externalSemaSources = xacc::getServices<qcor::compiler::QCORExternalSemaSource>();
    auto fuzzyParser = std::make_shared<qcor::compiler::FuzzyParsingExternalSemaSource>();
    auto fuzzyParser =
        std::make_shared<qcor::compiler::FuzzyParsingExternalSemaSource>();
    fuzzyParser->initialize();
    // for (auto es : externalSemaSources) {
    //     es->setASTContext(&CI.getASTContext());
    //     es->initialize();
    CI.getSema().addExternalSource(fuzzyParser.get());
    // }

    // auto pragmaHandlers = xacc::getServices<qcor::compiler::QCORPragmaHandler>();
    // for (auto p : pragmaHandlers) {
    // FIXME Hook this back up
    // auto pragmaHandlers =
    // xacc::getServices<qcor::compiler::QCORPragmaHandler>(); for (auto p :
    // pragmaHandlers) {
    //     p->setRewriter(&rewriter);
    //     CI.getSema().getPreprocessor().AddPragmaHandler(p.get());
    // }
@@ -73,6 +70,29 @@ protected:

    CI.getDiagnosticClient().EndSourceFile();

    // Get the rewrite buffer
    const RewriteBuffer *RewriteBuf =
        rewriter.getRewriteBufferFor(CI.getSourceManager().getMainFileID());

    // if not null, rewrite to .fileName_out.cpp
    if (RewriteBuf) {
      auto getFileName = [](const std::string &s) {
        char sep = '/';

        size_t i = s.rfind(sep, s.length());
        if (i != std::string::npos) {
          return (s.substr(i + 1, s.length() - i));
        }

        return std::string("");
      };

      auto fileNameNoPath = getFileName(fileName);

      if (!fileNameNoPath.empty()) {
          fileName = fileNameNoPath;
      }
      
      std::string outName(fileName);
      size_t ext = outName.rfind(".");
      if (ext == std::string::npos)
@@ -80,22 +100,23 @@ protected:
      outName.insert(ext, "_out");
      outName = "." + outName;

    llvm::errs() << "Output to: " << outName << "\n";
      std::error_code OutErrorInfo;
      std::error_code ok;
      llvm::raw_fd_ostream outFile(llvm::StringRef(outName), OutErrorInfo,
                                   llvm::sys::fs::F_None);

      if (OutErrorInfo == ok) {

      const RewriteBuffer *RewriteBuf = rewriter.getRewriteBufferFor(
          CI.getSourceManager().getMainFileID());
      outFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
        auto s = std::string(RewriteBuf->begin(), RewriteBuf->end());
        outFile << s;
      } else {
        llvm::errs() << "Cannot open " << outName << " for writing\n";
        llvm::errs() << OutErrorInfo.message() << "\n";
      }

      outFile.close();
    } else {

      // Do we need to do anything here?
    }
  }
};

@@ -117,8 +138,8 @@ int main(int argc, char **argv) {
  Rewriter Rewrite;

  auto action = new QCORFrontendAction(Rewrite, fileName);
  std::vector<std::string> args{
      "-ftime-report", "-std=c++14", "-I@CMAKE_INSTALL_PREFIX@/include/qcor",
  std::vector<std::string> args{"-Wno-dangling", "-std=c++14",
                                "-I@CMAKE_INSTALL_PREFIX@/include/qcor",
                                "-I@CMAKE_INSTALL_PREFIX@/include/xacc"};

  if (!tooling::runToolOnCodeWithArgs(action, src, args)) {
@@ -126,5 +147,4 @@ int main(int argc, char **argv) {
  }

  return 0;

}
 No newline at end of file
+4 −63
Original line number Diff line number Diff line
@@ -62,7 +62,7 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
  // If it is, then map it to XACC IR
  if (isqk.isQuantumKernel()) {

    std::cout << "LAMBDA IS Quantum Kernel\n";
    // std::cout << "LAMBDA IS Quantum Kernel\n";
    // LE->dumpColor();
    // exit(0);
    auto cb = LE->capture_begin(); // implicit_capture_begin();
@@ -112,7 +112,7 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
      targetAccelerator = xacc::getAccelerator();
    }

    std::cout << "LAMBDA STR:\n" << xaccKernelLambdaStr << "\n";
    // std::cout << "LAMBDA STR:\n" << xaccKernelLambdaStr << "\n";
    auto compiler = xacc::getCompiler("xasm");
    auto ir = compiler->compile(xaccKernelLambdaStr, targetAccelerator);

@@ -138,7 +138,7 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
      }
    }

    std::cout << "\n\nXACC IR:\n" << function->toString() << "\n";
    // std::cout << "\n\nXACC IR:\n" << function->toString() << "\n";

    auto sr = LE->getBody()->getSourceRange();
    if (!xacc::optionExists("accelerator")) {
@@ -168,58 +168,9 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
        Lexer::getSourceText(CharSourceRange(SourceRange(sl,end), true), SM,
                             lo)
            .str();
    // auto endOfParams =
    //     F->getParamDecl(nArgs - 1)->getEndLoc().getLocWithOffset(1);
    // rewriter.InsertText(endOfParams, ", bool execute = true");

    // std::cout << "LAMBDA DEF: " << lambdaDefinition << "\n";
    // std::string lambdaDefinition = "void _ast_visitor_function(bool execute = true) { return;};";
    // auto ast = tooling::buildASTFromCodeWithArgs(lambdaDefinition, {"-std=c++11"});

    // auto Matcher = namedDecl(hasName("_ast_visitor_function"));
    // FunctionDecl *tmp = FirstDeclMatcher<FunctionDecl>().match(ast
    //         ->getASTContext()
    //         .getTranslationUnitDecl(),
    //     Matcher);

    // tmp->dump();
    // // LE->getCallOperator()->getAsFunction() = tmp;
    // // LE = tmpRewriteF;

    // LE->getCallOperator()->setBody(tmp->getBody());
    // LE->getCallOperator()->setAttrs(tmp->getAttrs());
    // std::vector<ParmVarDecl*> params;
    // for (int i = 0; i < F->getNumParams(); i++ ){
    //     params.push_back(F->getParamDecl(i));
    // }

    // static IdentifierInfo& boolname(ci.getASTContext().Idents.get(StringRef("execute")));
    // auto boolExec = new (this->ci.getASTContext()) CXXBoolLiteralExpr(true, ci.getASTContext().BoolTy, SourceLocation());
    // auto newVar = ParmVarDecl::Create(ci.getASTContext(), ci.getSema().getFunctionLevelDeclContext(), SourceLocation(), SourceLocation(), &boolname, ci.getASTContext().BoolTy,  0, SC_None, boolExec);
    // params.push_back(newVar);

    // llvm::ArrayRef<ParmVarDecl *> parms(params);
    // LE->getCallOperator()->dump();
    // LE->getCallOperator()->setParams(parms);
    // std::cout << "AFTER\n";

    // LE->getCallOperator()->dump();
    // rewriter.ReplaceText(SourceRange(sl, end), "qbit " + bufferName +", std::vector<double> params, bool execute = true");
    // Rewrite the args list to have a boolean at the end
    // that is default to true and used to execute the accelerator
    // ESSENTIALLY rewrite to
    // n(qbit q, std::vector<double> params, bool execute = true)

    // Thought - I should design a QuantumKernel class, that
    // can be initialized with the IR string, and methods to toggle
    // execution, and a variadic template execute method.

 std::cout << "BEFORE:\n";
    LE->getCallOperator()->dump();

    std::vector<ParmVarDecl*> params;
    for (int i = 0; i < LE->getCallOperator()->getNumParams(); i++ ){
        std::cout << "ADDING PARAM: " << LE->getCallOperator()->getParamDecl(i)->getNameAsString() << "\n";
        params.push_back(LE->getCallOperator()->getParamDecl(i));
    }

@@ -229,7 +180,7 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
    std::string replacement =
        "{\nauto irstr = R\"irstr(" + ss.str() + ")irstr\";\n";

    replacement += "if (qcor::executeKernel) {\n";
    replacement += "if (qcor::__internal::executeKernel) {\n";
    replacement +=
        "auto function = "
        "xacc::getIRProvider(\"quantum\")->createComposite(\"f\");\n";
@@ -244,13 +195,10 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
        replacement += "," + F->getParamDecl(i)->getNameAsString();
      }
      replacement += "};\n";
      // }
      // if (F->getNumParams() > 1) {
      replacement += "function = function->operator()(params);\n";
    }
    replacement += "acc->execute(" + bufferName + ",function);\n";
    replacement += "}\n";
    // }
    replacement += "return irstr;\n";
    replacement += "}\n";
    rewriter.ReplaceText(sr, replacement);
@@ -287,8 +235,6 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {
    for (auto it = cs->child_begin(); it != cs->child_end(); ++it) {
      svec.push_back(*it);
    }

    // svec.push_back(LE->getCallOperator()->getBody());
    svec.push_back(rtrn);

    llvm::ArrayRef<Stmt *> stmts(svec);
@@ -298,12 +244,7 @@ bool QCORASTVisitor::VisitLambdaExpr(LambdaExpr *LE) {


    llvm::ArrayRef<ParmVarDecl *> parms(params);
    // LE->getCallOperator()->dump();
    LE->getCallOperator()->getAsFunction()->setParams(parms);
    std::cout << "AFTER\n";
    LE->getCallOperator()->dump();


  }

  return true;
+42 −0
Original line number Diff line number Diff line
#include "qcor.hpp"

template <typename T> std::vector<T> linspace(T a, T b, size_t N) {
  T h = (b - a) / static_cast<T>(N - 1);
  std::vector<T> xs(N);
  typename std::vector<T>::iterator x;
  T val;
  for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
    *x = val;
  return xs;
}

int main(int argc, char **argv) {

  qcor::Initialize(argc, argv);

  // Create an unmeasured ansatz
  auto ansatz = [&](qbit q, std::vector<double> t) {
    X(q[0]);
    Ry(q[1], t[0]);
    CNOT(q[1], q[0]);
  };

  // Manually add Measure calls to the
  // existing ansatz
  auto Z0 = [&](qbit q, std::vector<double> t) {
    Measure(q[0]);
  };
  auto ansatzZ0 = qcor::add(ansatz, Z0, std::vector<double>{});

  // Now lets compute <Z0>(theta)
  std::vector<double> all_params =
      linspace(-xacc::constants::pi, xacc::constants::pi, 10);
  for (auto &p : all_params) {
    auto buffer = xacc::qalloc(2);
    ansatzZ0(buffer, std::vector<double>{p});
    std::cout << "<Z0Z1> = " << buffer->getInformation("exp-val-z").as<double>()
              << "\n";
  }

  qcor::Finalize();
}
+6 −6
Original line number Diff line number Diff line
@@ -5,11 +5,11 @@ int main(int argc, char** argv) {
  qcor::Initialize(argc, argv);

  auto future = qcor::submit([&](qcor::qpu_handler &qh) {
    qh.execute([&]() { 
      H(0);
      CX(0, 1);
      Measure(0);
      Measure(1);
    qh.execute([&](qbit q) {
      H(q[0]);
      CX(q[0], q[1]);
      Measure(q[0]);
      Measure(q[1]);
    });
  });

examples/deuteron.cpp

deleted100644 → 0
+0 −26
Original line number Diff line number Diff line
#include "qcor.hpp"

int main(int argc, char **argv) {

  qcor::Initialize(argc, argv);

  auto optimizer = qcor::getOptimizer(
      "nlopt", {{"nlopt-optimizer", "cobyla"},
                {"nlopt-maxeval", 20}});

  auto op = qcor::getObservable("pauli", "5.907 - 2.1433 X0X1 "
                                         "- 2.1433 Y0Y1"
                                         "+ .21829 Z0 - 6.125 Z1");

  auto future = qcor::submit([&](qcor::qpu_handler &qh) {
    qh.vqe(
        [&](double t0) {
          X(0);
          Ry(t0, 1);
          CX(1, 0);
        },
        op, optimizer);
  });

  auto results = future.get();
}
Loading