Jlm
value-representation.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2014 Helge Bahmann <hcb@chaoticmind.net>
3  * Copyright 2015 Nico Reißmann <nico.reissmann@gmail.com>
4  * See COPYING for terms of redistribution.
5  */
6 
8 
9 #include <stdexcept>
10 
11 namespace jlm::rvsdg
12 {
13 
14 uint64_t
16 {
17  size_t limit = std::min(nbits(), size_t(64));
18  /* bits beyond 64 must be zero, else value is not representable as uint64_t */
19  for (size_t n = limit; n < nbits(); ++n)
20  {
21  if (data_[n] != '0')
22  throw std::range_error("Bit constant value exceeds uint64 range");
23  }
24 
25  uint64_t result = 0;
26  uint64_t pos_value = 1;
27  for (size_t n = 0; n < limit; ++n)
28  {
29  switch (data_[n])
30  {
31  case '0':
32  {
33  break;
34  }
35  case '1':
36  {
37  result |= pos_value;
38  break;
39  }
40  default:
41  {
42  throw std::range_error("Undetermined bit constant");
43  }
44  }
45  pos_value = pos_value << 1;
46  }
47  return result;
48 }
49 
50 int64_t
52 {
53  /* all bits from 63 on must be identical, else value is not representable as int64_t */
54  char sign_bit = data_[nbits() - 1];
55  size_t limit = std::min(nbits(), size_t(63));
56  for (size_t n = limit; n < nbits(); ++n)
57  {
58  if (data_[n] != sign_bit)
59  throw std::range_error("Bit constant value exceeds int64 range");
60  }
61 
62  int64_t result = 0;
63  uint64_t pos_value = 1;
64  for (size_t n = 0; n < 64; ++n)
65  {
66  switch (n < nbits() ? data_[n] : sign_bit)
67  {
68  case '0':
69  {
70  break;
71  }
72  case '1':
73  {
74  result |= pos_value;
75  break;
76  }
77  default:
78  {
79  throw std::range_error("Undetermined bit constant");
80  }
81  }
82  pos_value = pos_value << 1;
83  }
84  return result;
85 }
86 
87 }