109467b48Spatrick //===-- llvm/ADT/APSInt.cpp - Arbitrary Precision Signed Int ---*- C++ -*--===// 209467b48Spatrick // 309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information. 509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 609467b48Spatrick // 709467b48Spatrick //===----------------------------------------------------------------------===// 809467b48Spatrick // 909467b48Spatrick // This file implements the APSInt class, which is a simple class that 1009467b48Spatrick // represents an arbitrary sized integer that knows its signedness. 1109467b48Spatrick // 1209467b48Spatrick //===----------------------------------------------------------------------===// 1309467b48Spatrick 1409467b48Spatrick #include "llvm/ADT/APSInt.h" 1509467b48Spatrick #include "llvm/ADT/FoldingSet.h" 1609467b48Spatrick #include "llvm/ADT/StringRef.h" 17*097a140dSpatrick #include <cassert> 1809467b48Spatrick 1909467b48Spatrick using namespace llvm; 2009467b48Spatrick APSInt(StringRef Str)2109467b48SpatrickAPSInt::APSInt(StringRef Str) { 2209467b48Spatrick assert(!Str.empty() && "Invalid string length"); 2309467b48Spatrick 2409467b48Spatrick // (Over-)estimate the required number of bits. 2509467b48Spatrick unsigned NumBits = ((Str.size() * 64) / 19) + 2; 2609467b48Spatrick APInt Tmp(NumBits, Str, /*radix=*/10); 2709467b48Spatrick if (Str[0] == '-') { 2809467b48Spatrick unsigned MinBits = Tmp.getMinSignedBits(); 29*097a140dSpatrick if (MinBits < NumBits) 30*097a140dSpatrick Tmp = Tmp.trunc(std::max<unsigned>(1, MinBits)); 3109467b48Spatrick *this = APSInt(Tmp, /*isUnsigned=*/false); 3209467b48Spatrick return; 3309467b48Spatrick } 3409467b48Spatrick unsigned ActiveBits = Tmp.getActiveBits(); 35*097a140dSpatrick if (ActiveBits < NumBits) 36*097a140dSpatrick Tmp = Tmp.trunc(std::max<unsigned>(1, ActiveBits)); 3709467b48Spatrick *this = APSInt(Tmp, /*isUnsigned=*/true); 3809467b48Spatrick } 3909467b48Spatrick Profile(FoldingSetNodeID & ID) const4009467b48Spatrickvoid APSInt::Profile(FoldingSetNodeID& ID) const { 4109467b48Spatrick ID.AddInteger((unsigned) (IsUnsigned ? 1 : 0)); 4209467b48Spatrick APInt::Profile(ID); 4309467b48Spatrick } 44