#!/usr/bin/env python

import os, sys, argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description = "Generate queries")
    parser.add_argument("orig_bc",
            help = "the path to the original bc (with IDs tagged)")
    parser.add_argument("sliced_bc",
            help = "the path to the sliced bc")
    parser.add_argument("query_list",
            help = "the output query list")
    parser.add_argument("--orig", action = "store_true",
            help = "generate queries for the original program (default: false)")
    parser.add_argument("--loadload", action = "store_true",
            help = "Consider load-load aliases as well (default: false)")
    parser.add_argument("--cs", action = "store_true",
            help = "generate context-sensitive queries (default: false)")
    parser.add_argument("--concurrent", nargs = 2,
            metavar = ("full-trace", "landmark-trace"),
            help = "consider concurrent loads and stores only according to "
            "the full trace and the landmark trace")
    args = parser.parse_args()

    LLVM_ROOT = os.getenv("LLVM_ROOT")
    base_cmd = "opt "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libid-manager.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libbc2bdd.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libcallgraph-fp.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libmbb.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libcfg.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libslicer-trace.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libmax-slicing.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libint.so "
    base_cmd += "-load " + LLVM_ROOT + "/install/lib/libalias-query.so "

    cmd = base_cmd
    cmd += "-analyze "
    if args.orig:
        cmd += "-for-orig "
    if args.loadload:
        cmd += "-gen-loadload "
    if args.cs:
        cmd += "-cs "

    if not args.concurrent:
        # Static queries
        cmd += "-gen-queries < " + args.sliced_bc + " > " + args.query_list
    else:
        # Dynamic queries
        cmd += "-fulltrace " + args.concurrent[0] + " "
        cmd += "-input-landmark-trace " + args.concurrent[1] + " "
        cmd += "-concurrent "
        cmd += "-gen-queries < " + args.orig_bc + " > " + args.query_list

    print >> sys.stderr, "\033[1;34m" + cmd + "\033[m"
    os.system(cmd)
