From 8ae1cb2bcb55293cce31bb75c38d6b4e8a13cc23 Mon Sep 17 00:00:00 2001 From: Iman Hosseini Date: Fri, 17 Jan 2025 14:40:31 +0000 Subject: add power function to APInt (#122788) I am trying to calculate power function for APFloat, APInt to constant fold vector reductions: https://github.com/llvm/llvm-project/pull/122450 I need this utility to fold N `mul`s into power. --------- Co-authored-by: ImanHosseini Co-authored-by: Jakub Kuderski --- llvm/lib/Support/APInt.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'llvm/lib/Support/APInt.cpp') diff --git a/llvm/lib/Support/APInt.cpp b/llvm/lib/Support/APInt.cpp index ea8295f..38cf485 100644 --- a/llvm/lib/Support/APInt.cpp +++ b/llvm/lib/Support/APInt.cpp @@ -3108,3 +3108,21 @@ APInt APIntOps::mulhu(const APInt &C1, const APInt &C2) { APInt C2Ext = C2.zext(FullWidth); return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); } + +APInt APIntOps::pow(const APInt &X, int64_t N) { + assert(N >= 0 && "negative exponents not supported."); + APInt Acc = APInt(X.getBitWidth(), 1); + if (N == 0) + return Acc; + APInt Base = X; + int64_t RemainingExponent = N; + while (RemainingExponent > 0) { + while (RemainingExponent % 2 == 0) { + Base *= Base; + RemainingExponent /= 2; + } + --RemainingExponent; + Acc *= Base; + } + return Acc; +}; -- cgit v1.1