int.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/base/int.h"
  5. namespace Carbon {
  6. auto IntStore::CanonicalBitWidth(int significant_bits) -> int {
  7. // For larger integers, we store them in as a signed APInt with a canonical
  8. // width that is the smallest multiple of the word type's bits, but no
  9. // smaller than a minimum of 64 bits to avoid spurious resizing of the most
  10. // common cases (<= 64 bits).
  11. static constexpr int WordWidth = llvm::APInt::APINT_BITS_PER_WORD;
  12. return std::max<int>(
  13. MinAPWidth, ((significant_bits + WordWidth - 1) / WordWidth) * WordWidth);
  14. }
  15. auto IntStore::CanonicalizeSigned(llvm::APInt value) -> llvm::APInt {
  16. return value.sextOrTrunc(CanonicalBitWidth(value.getSignificantBits()));
  17. }
  18. auto IntStore::CanonicalizeUnsigned(llvm::APInt value) -> llvm::APInt {
  19. // We need the width to include a zero sign bit as we canonicalize to a
  20. // signed representation.
  21. return value.zextOrTrunc(CanonicalBitWidth(value.getActiveBits() + 1));
  22. }
  23. auto IntStore::AddLarge(int64_t value) -> IntId {
  24. auto ap_id =
  25. values_.Add(llvm::APInt(CanonicalBitWidth(64), value, /*isSigned=*/true));
  26. return MakeIndexOrNone(ap_id.index);
  27. }
  28. auto IntStore::AddSignedLarge(llvm::APInt value) -> IntId {
  29. auto ap_id = values_.Add(CanonicalizeSigned(value));
  30. return MakeIndexOrNone(ap_id.index);
  31. }
  32. auto IntStore::AddUnsignedLarge(llvm::APInt value) -> IntId {
  33. auto ap_id = values_.Add(CanonicalizeUnsigned(value));
  34. return MakeIndexOrNone(ap_id.index);
  35. }
  36. auto IntStore::LookupLarge(int64_t value) const -> IntId {
  37. auto ap_id = values_.Lookup(
  38. llvm::APInt(CanonicalBitWidth(64), value, /*isSigned=*/true));
  39. return MakeIndexOrNone(ap_id.index);
  40. }
  41. auto IntStore::LookupSignedLarge(llvm::APInt value) const -> IntId {
  42. auto ap_id = values_.Lookup(CanonicalizeSigned(value));
  43. return MakeIndexOrNone(ap_id.index);
  44. }
  45. auto IntStore::OutputYaml() const -> Yaml::OutputMapping {
  46. return values_.OutputYaml();
  47. }
  48. auto IntStore::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  49. -> void {
  50. mem_usage.Collect(std::string(label), values_);
  51. }
  52. } // namespace Carbon