APSInt.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //===-- llvm/ADT/APSInt.cpp - Arbitrary Precision Signed Int ---*- C++ -*--===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the APSInt class, which is a simple class that
  10. // represents an arbitrary sized integer that knows its signedness.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/APSInt.h"
  14. #include "llvm/ADT/FoldingSet.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include <cassert>
  17. using namespace llvm;
  18. APSInt::APSInt(StringRef Str) {
  19. assert(!Str.empty() && "Invalid string length");
  20. // (Over-)estimate the required number of bits.
  21. unsigned NumBits = ((Str.size() * 64) / 19) + 2;
  22. APInt Tmp(NumBits, Str, /*radix=*/10);
  23. if (Str[0] == '-') {
  24. unsigned MinBits = Tmp.getMinSignedBits();
  25. if (MinBits < NumBits)
  26. Tmp = Tmp.trunc(std::max<unsigned>(1, MinBits));
  27. *this = APSInt(Tmp, /*isUnsigned=*/false);
  28. return;
  29. }
  30. unsigned ActiveBits = Tmp.getActiveBits();
  31. if (ActiveBits < NumBits)
  32. Tmp = Tmp.trunc(std::max<unsigned>(1, ActiveBits));
  33. *this = APSInt(Tmp, /*isUnsigned=*/true);
  34. }
  35. void APSInt::Profile(FoldingSetNodeID& ID) const {
  36. ID.AddInteger((unsigned) (IsUnsigned ? 1 : 0));
  37. APInt::Profile(ID);
  38. }