#!/usr/bin/env python3
import argparse
from fractions import Fraction
import re

from llvm_paths import llvm_project_root

MASK64 = (1 << 64) - 1
MASK32 = (1 << 32) - 1
SIGNATURE_SEED = 0x1660012E
GROUP_SIGNATURE_SEED = 0xF64D0000
ITERATIONS = 128
CHECKPOINT_INTERVAL = 8
EXPRESSION_COUNT = 5
SUITE_ID = 302
SEEDS = (0x1660F64A1B2C3D4E, 0xC166D0B15EED1234,
         0x5EEDF64A89ABCDEF, 0x0123456789ABCDEF)
EDGES = (
    0x0000000000000000, 0x8000000000000000,
    0x0000000000000001, 0x8000000000000001,
    0x000FFFFFFFFFFFFF, 0x800FFFFFFFFFFFFF,
    0x0010000000000000, 0x8010000000000000,
    0x3FE0000000000000, 0xBFE0000000000000,
    0x3FF0000000000000, 0xBFF0000000000000,
    0x4000000000000000, 0xC004000000000000,
    0x7FEFFFFFFFFFFFFF, 0xFFEFFFFFFFFFFFFF,
)
UPSTREAM = (
    (0, "adddf3new_test.c", "adddf3"),
    (1, "subdf3new_test.c", "subdf3"),
    (2, "muldf3new_test.c", "muldf3"),
    (3, "divdf3new_test.c", "divdf3"),
)


def xorshift64(state):
    state ^= state << 13 & MASK64
    state ^= state >> 7
    state ^= state << 17 & MASK64
    return state & MASK64


def finite_bits(state):
    state = xorshift64(state)
    bits = state
    if bits >> 52 & 0x7FF == 0x7FF:
        bits ^= 1 << 52
    return state, bits


def decode_finite(bits):
    sign = -1 if bits >> 63 else 1
    exponent = bits >> 52 & 0x7FF
    fraction = bits & ((1 << 52) - 1)
    if exponent == 0:
        significand = fraction
        power = -1074
    else:
        significand = (1 << 52) | fraction
        power = exponent - 1023 - 52
    value = Fraction(sign * significand)
    return value * (1 << power) if power >= 0 else value / (1 << -power)


def round_ratio(numerator, denominator):
    quotient, remainder = divmod(numerator, denominator)
    doubled = remainder * 2
    if doubled > denominator or doubled == denominator and quotient & 1:
        quotient += 1
    return quotient


def scaled_round(value, power):
    numerator = value.numerator
    denominator = value.denominator
    if power >= 0:
        numerator <<= power
    else:
        denominator <<= -power
    return round_ratio(numerator, denominator)


def floor_log2(value):
    numerator = value.numerator
    denominator = value.denominator
    exponent = numerator.bit_length() - denominator.bit_length()
    if exponent >= 0:
        if numerator < denominator << exponent:
            exponent -= 1
    elif numerator << -exponent < denominator:
        exponent -= 1
    return exponent


def encode_fraction(value):
    sign = 0
    if value < 0:
        sign = 1
        value = -value
    if value == 0:
        return sign << 63

    exponent = floor_log2(value)
    if exponent >= -1022:
        significand = scaled_round(value, 52 - exponent)
        if significand == 1 << 53:
            significand >>= 1
            exponent += 1
        if exponent > 1023:
            return sign << 63 | 0x7FF0000000000000
        return (sign << 63 | (exponent + 1023) << 52 |
                (significand - (1 << 52)))

    significand = scaled_round(value, 1074)
    if significand == 0:
        return sign << 63
    if significand >= 1 << 52:
        return sign << 63 | 0x0010000000000000
    return sign << 63 | significand


def evaluate(expression, a_bits, b_bits):
    a = decode_finite(a_bits)
    b = decode_finite(b_bits)
    a_zero = a_bits & 0x7FFFFFFFFFFFFFFF == 0
    b_zero = b_bits & 0x7FFFFFFFFFFFFFFF == 0
    a_sign = a_bits >> 63
    b_sign = b_bits >> 63
    if expression == 0:
        if a_zero and b_zero:
            return (a_sign & b_sign) << 63
        result = a + b
    elif expression == 1:
        if a_zero and b_zero:
            return (a_sign & (b_sign ^ 1)) << 63
        result = a - b
    elif expression == 2:
        if a_zero or b_zero:
            return (a_sign ^ b_sign) << 63
        result = a * b
    elif expression == 3:
        if a_zero:
            return (a_sign ^ b_sign) << 63
        if b_zero:
            return ((a_sign ^ b_sign) << 63) | 0x7FF0000000000000
        result = a / b
    elif expression == 4:
        if a < b:
            return 0x3FF0000000000000
        elif a == b:
            return 0x4000000000000000
        elif a > b:
            return 0x4010000000000000
        else:
            return 0x4020000000000000
    return 0 if result == 0 else encode_fraction(result)


def verify_upstream():
    verified = 0
    for operation, filename, helper in UPSTREAM:
        source = (llvm_project_root() / "compiler-rt" / "test" / "builtins" /
                  "Unit" / filename)
        pattern = re.compile(
            rf"test__{helper}\(\s*0x([0-9a-fA-F]{{16}})\s*,\s*"
            rf"0x([0-9a-fA-F]{{16}})\s*,\s*0x([0-9a-fA-F]{{16}})\s*\)"
        )
        for match in pattern.findall(source.read_text(encoding="utf-8")):
            a, b, expected = (int(word, 16) for word in match)
            if (a >> 52 & 0x7FF) == 0x7FF or (b >> 52 & 0x7FF) == 0x7FF:
                continue
            if operation == 3 and b & 0x7FFFFFFFFFFFFFFF == 0:
                continue
            actual = evaluate(operation, a, b)
            if actual != expected:
                raise SystemExit(
                    f"oracle mismatch {helper}: {a:016x} {b:016x}: "
                    f"{actual:016x} != {expected:016x}"
                )
            verified += 1
    if verified == 0:
        raise SystemExit("no upstream binary64 vectors verified")
    return verified


def input_pairs(seed_id, seed):
    state = seed
    for iteration in range(ITERATIONS):
        state, a = finite_bits(state)
        state, b = finite_bits(state)
        if iteration % 4 == 0:
            a = EDGES[(iteration + seed_id) % len(EDGES)]
        if iteration % 4 == 1:
            b = EDGES[(iteration * 3 + seed_id) % len(EDGES)]
        if b & 0x7FFFFFFFFFFFFFFF == 0:
            b = 0x3FF0000000000000
        if iteration % 16 == 15:
            b = a
        yield iteration, a, b


def signature_step(signature, case_id, value):
    case_id &= 0xFFFF
    tag = (case_id << 16) | case_id
    rotated = ((signature << 5) | (signature >> 27)) & MASK32
    return (rotated ^ value ^ tag) & MASK32


def checkpoint_groups():
    groups = []
    for seed_index, seed in enumerate(SEEDS):
        seed_id = seed_index + 1
        pairs = list(input_pairs(seed_id, seed))
        expression_groups = []
        for expression in range(EXPRESSION_COUNT):
            signature = (GROUP_SIGNATURE_SEED ^ (seed_id << 8) ^
                         expression)
            checkpoints = []
            for iteration, a, b in pairs:
                result = evaluate(expression, a, b)
                signature = signature_step(signature, iteration * 2 + 1,
                                           result >> 32)
                signature = signature_step(signature, iteration * 2 + 2,
                                           result & MASK32)
                if (iteration + 1) % CHECKPOINT_INTERVAL == 0:
                    checkpoints.append(signature)
            expression_groups.append(checkpoints)
        groups.append(expression_groups)
    return groups


def expected_signature(selected_expression=None):
    signature = SIGNATURE_SEED
    for seed_index, expressions in enumerate(checkpoint_groups()):
        for expression, checkpoints in enumerate(expressions):
            if (selected_expression is not None and
                    expression != selected_expression):
                continue
            base = ((seed_index * EXPRESSION_COUNT + expression) *
                    (ITERATIONS // CHECKPOINT_INTERVAL))
            for checkpoint_index, checkpoint in enumerate(checkpoints):
                case_id = base + checkpoint_index + 1
                signature = signature_step(signature, case_id, checkpoint)
    return signature


def emit_u32_array(name, values):
    print(f"static const abi_u32 {name}[{len(values)}] = {{")
    for index in range(0, len(values), 4):
        line = ", ".join(f"0x{value:08x}UL"
                         for value in values[index:index + 4])
        suffix = "," if index + 4 < len(values) else ""
        print(f"  {line}{suffix}")
    print("};")


def emit_corpus():
    checkpoints = [checkpoint
                   for expressions in checkpoint_groups()
                   for group in expressions for checkpoint in group]
    print("#ifndef SEEDED_F64_CORPUS_INC")
    print("#define SEEDED_F64_CORPUS_INC")
    print()
    print(f"#define ABI_SEEDED_F64_SUITE_ID {SUITE_ID}U")
    print(f"#define ABI_SEEDED_F64_ITERATIONS {ITERATIONS}U")
    print(f"#define ABI_SEEDED_F64_SEED_COUNT {len(SEEDS)}U")
    print(f"#define ABI_SEEDED_F64_EXPRESSION_COUNT {EXPRESSION_COUNT}U")
    print(f"#define ABI_SEEDED_F64_CHECKPOINT_INTERVAL "
          f"{CHECKPOINT_INTERVAL}U")
    print(f"#define ABI_SEEDED_F64_CHECKPOINTS_PER_GROUP "
          f"{ITERATIONS // CHECKPOINT_INTERVAL}U")
    print(f"#define ABI_SEEDED_F64_CHECKPOINT_COUNT "
          f"{len(checkpoints)}U")
    print(f"#define ABI_SEEDED_F64_RESULT_COUNT "
          f"{len(SEEDS) * EXPRESSION_COUNT * ITERATIONS}UL")
    print(f"#define ABI_SEEDED_F64_RAW_WORD_COUNT "
          f"{len(SEEDS) * EXPRESSION_COUNT * ITERATIONS * 2}UL")
    print(f"#define ABI_SEEDED_F64_GROUP_SIGNATURE_SEED "
          f"0x{GROUP_SIGNATURE_SEED:08x}UL")
    print()
    emit_u32_array("abi_seeded_f64_seed_hi",
                   [seed >> 32 for seed in SEEDS])
    emit_u32_array("abi_seeded_f64_seed_lo",
                   [seed & MASK32 for seed in SEEDS])
    emit_u32_array("abi_seeded_f64_edge_hi",
                   [edge >> 32 for edge in EDGES])
    emit_u32_array("abi_seeded_f64_edge_lo",
                   [edge & MASK32 for edge in EDGES])
    emit_u32_array("abi_seeded_f64_expected", checkpoints)
    print()
    print("#endif")


def main():
    global ITERATIONS, CHECKPOINT_INTERVAL, SEEDS, SUITE_ID

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mode",
        choices=("corpus", "signature", "check-count",
                 "result-count", "raw-word-count", "verify-upstream"),
    )
    parser.add_argument("--iterations", type=int, default=ITERATIONS)
    parser.add_argument(
        "--checkpoint-interval", type=int, default=CHECKPOINT_INTERVAL
    )
    parser.add_argument("--suite-id", type=int, default=SUITE_ID)
    parser.add_argument(
        "--seed", action="append", type=lambda value: int(value, 0), default=[]
    )
    parser.add_argument("--expression", type=int, choices=range(EXPRESSION_COUNT))
    args = parser.parse_args()
    seeds = tuple(args.seed) if args.seed else SEEDS
    if not 1 <= args.iterations <= 32767:
        parser.error("--iterations must be in 1..32767")
    if (args.checkpoint_interval <= 0 or
            args.checkpoint_interval & (args.checkpoint_interval - 1)):
        parser.error("--checkpoint-interval must be a power of two")
    if args.iterations % args.checkpoint_interval:
        parser.error("--iterations must be divisible by --checkpoint-interval")
    if not seeds or any(not 0 <= seed <= MASK64 for seed in seeds):
        parser.error("each --seed must be an unsigned 64-bit value")
    checkpoint_count = (len(seeds) * EXPRESSION_COUNT *
                        (args.iterations // args.checkpoint_interval))
    if checkpoint_count > 4095:
        parser.error("checkpoint table must fit one 16 KiB Classic far object")
    if not 0 <= args.suite_id <= 65535:
        parser.error("--suite-id must fit unsigned 16 bits")

    ITERATIONS = args.iterations
    CHECKPOINT_INTERVAL = args.checkpoint_interval
    SEEDS = seeds
    SUITE_ID = args.suite_id

    if args.mode == "corpus":
        emit_corpus()
    elif args.mode == "signature":
        print(expected_signature(args.expression))
    elif args.mode == "check-count":
        print(checkpoint_count)
    elif args.mode == "result-count":
        print(len(SEEDS) * EXPRESSION_COUNT * ITERATIONS)
    elif args.mode == "raw-word-count":
        print(len(SEEDS) * EXPRESSION_COUNT * ITERATIONS * 2)
    else:
        print(verify_upstream())


if __name__ == "__main__":
    main()
