xref: /llvm-project/clang/lib/AST/ByteCode/Integral.h (revision 2503a6659621e27e6b4c5946c3acff7a5b9dadca)
1 //===--- Integral.h - Wrapper for numeric types for the VM ------*- 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 // Defines the VM types and helpers operating on types.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_AST_INTERP_INTEGRAL_H
14 #define LLVM_CLANG_AST_INTERP_INTEGRAL_H
15 
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ComparisonCategories.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <cstddef>
22 #include <cstdint>
23 
24 #include "Primitives.h"
25 
26 namespace clang {
27 namespace interp {
28 
29 using APInt = llvm::APInt;
30 using APSInt = llvm::APSInt;
31 
32 template <bool Signed> class IntegralAP;
33 
34 // Helper structure to select the representation.
35 template <unsigned Bits, bool Signed> struct Repr;
36 template <> struct Repr<8, false> {
37   using Type = uint8_t;
38 };
39 template <> struct Repr<16, false> {
40   using Type = uint16_t;
41 };
42 template <> struct Repr<32, false> {
43   using Type = uint32_t;
44 };
45 template <> struct Repr<64, false> {
46   using Type = uint64_t;
47 };
48 template <> struct Repr<8, true> {
49   using Type = int8_t;
50 };
51 template <> struct Repr<16, true> {
52   using Type = int16_t;
53 };
54 template <> struct Repr<32, true> {
55   using Type = int32_t;
56 };
57 template <> struct Repr<64, true> {
58   using Type = int64_t;
59 };
60 
61 /// Wrapper around numeric types.
62 ///
63 /// These wrappers are required to shared an interface between APSint and
64 /// builtin primitive numeral types, while optimising for storage and
65 /// allowing methods operating on primitive type to compile to fast code.
66 template <unsigned Bits, bool Signed> class Integral final {
67 private:
68   template <unsigned OtherBits, bool OtherSigned> friend class Integral;
69 
70   // The primitive representing the integral.
71   using ReprT = typename Repr<Bits, Signed>::Type;
72   ReprT V;
73   static_assert(std::is_trivially_copyable_v<ReprT>);
74 
75   /// Primitive representing limits.
76   static const auto Min = std::numeric_limits<ReprT>::min();
77   static const auto Max = std::numeric_limits<ReprT>::max();
78 
79   /// Construct an integral from anything that is convertible to storage.
80   template <typename T> explicit Integral(T V) : V(V) {}
81 
82 public:
83   using AsUnsigned = Integral<Bits, false>;
84 
85   /// Zero-initializes an integral.
86   Integral() : V(0) {}
87 
88   /// Constructs an integral from another integral.
89   template <unsigned SrcBits, bool SrcSign>
90   explicit Integral(Integral<SrcBits, SrcSign> V) : V(V.V) {}
91 
92   /// Construct an integral from a value based on signedness.
93   explicit Integral(const APSInt &V)
94       : V(V.isSigned() ? V.getSExtValue() : V.getZExtValue()) {}
95 
96   bool operator<(Integral RHS) const { return V < RHS.V; }
97   bool operator>(Integral RHS) const { return V > RHS.V; }
98   bool operator<=(Integral RHS) const { return V <= RHS.V; }
99   bool operator>=(Integral RHS) const { return V >= RHS.V; }
100   bool operator==(Integral RHS) const { return V == RHS.V; }
101   bool operator!=(Integral RHS) const { return V != RHS.V; }
102 
103   bool operator>(unsigned RHS) const {
104     return V >= 0 && static_cast<unsigned>(V) > RHS;
105   }
106 
107   Integral operator-() const { return Integral(-V); }
108   Integral operator-(const Integral &Other) const {
109     return Integral(V - Other.V);
110   }
111   Integral operator~() const { return Integral(~V); }
112 
113   template <unsigned DstBits, bool DstSign>
114   explicit operator Integral<DstBits, DstSign>() const {
115     return Integral<DstBits, DstSign>(V);
116   }
117 
118   template <typename Ty, typename = std::enable_if_t<std::is_integral_v<Ty>>>
119   explicit operator Ty() const {
120     return V;
121   }
122 
123   APSInt toAPSInt() const {
124     return APSInt(APInt(Bits, static_cast<uint64_t>(V), Signed), !Signed);
125   }
126   APSInt toAPSInt(unsigned BitWidth) const {
127     return APSInt(toAPInt(BitWidth), !Signed);
128   }
129   APInt toAPInt(unsigned BitWidth) const {
130     if constexpr (Signed)
131       return APInt(Bits, static_cast<uint64_t>(V), Signed)
132           .sextOrTrunc(BitWidth);
133     else
134       return APInt(Bits, static_cast<uint64_t>(V), Signed)
135           .zextOrTrunc(BitWidth);
136   }
137   APValue toAPValue(const ASTContext &) const { return APValue(toAPSInt()); }
138 
139   Integral<Bits, false> toUnsigned() const {
140     return Integral<Bits, false>(*this);
141   }
142 
143   constexpr static unsigned bitWidth() { return Bits; }
144 
145   bool isZero() const { return !V; }
146 
147   bool isMin() const { return *this == min(bitWidth()); }
148 
149   bool isMinusOne() const { return Signed && V == ReprT(-1); }
150 
151   constexpr static bool isSigned() { return Signed; }
152 
153   bool isNegative() const { return V < ReprT(0); }
154   bool isPositive() const { return !isNegative(); }
155 
156   ComparisonCategoryResult compare(const Integral &RHS) const {
157     return Compare(V, RHS.V);
158   }
159 
160   void bitcastToMemory(std::byte *Dest) const {
161     std::memcpy(Dest, &V, sizeof(V));
162   }
163 
164   static Integral bitcastFromMemory(const std::byte *Src, unsigned BitWidth) {
165     assert(BitWidth == sizeof(ReprT) * 8);
166     ReprT V;
167 
168     std::memcpy(&V, Src, sizeof(ReprT));
169     return Integral(V);
170   }
171 
172   std::string toDiagnosticString(const ASTContext &Ctx) const {
173     std::string NameStr;
174     llvm::raw_string_ostream OS(NameStr);
175     OS << V;
176     return NameStr;
177   }
178 
179   unsigned countLeadingZeros() const {
180     if constexpr (!Signed)
181       return llvm::countl_zero<ReprT>(V);
182     if (isPositive())
183       return llvm::countl_zero<typename AsUnsigned::ReprT>(
184           static_cast<typename AsUnsigned::ReprT>(V));
185     llvm_unreachable("Don't call countLeadingZeros() on negative values.");
186   }
187 
188   Integral truncate(unsigned TruncBits) const {
189     assert(TruncBits >= 1);
190     if (TruncBits >= Bits)
191       return *this;
192     const ReprT BitMask = (ReprT(1) << ReprT(TruncBits)) - 1;
193     const ReprT SignBit = ReprT(1) << (TruncBits - 1);
194     const ReprT ExtMask = ~BitMask;
195     return Integral((V & BitMask) | (Signed && (V & SignBit) ? ExtMask : 0));
196   }
197 
198   void print(llvm::raw_ostream &OS) const { OS << V; }
199 
200   static Integral min(unsigned NumBits) { return Integral(Min); }
201   static Integral max(unsigned NumBits) { return Integral(Max); }
202 
203   template <typename ValT> static Integral from(ValT Value) {
204     if constexpr (std::is_integral<ValT>::value)
205       return Integral(Value);
206     else
207       return Integral::from(static_cast<Integral::ReprT>(Value));
208   }
209 
210   template <unsigned SrcBits, bool SrcSign>
211   static std::enable_if_t<SrcBits != 0, Integral>
212   from(Integral<SrcBits, SrcSign> Value) {
213     return Integral(Value.V);
214   }
215 
216   static Integral zero(unsigned BitWidth = 0) { return from(0); }
217 
218   template <typename T> static Integral from(T Value, unsigned NumBits) {
219     return Integral(Value);
220   }
221 
222   static bool inRange(int64_t Value, unsigned NumBits) {
223     return CheckRange<ReprT, Min, Max>(Value);
224   }
225 
226   static bool increment(Integral A, Integral *R) {
227     return add(A, Integral(ReprT(1)), A.bitWidth(), R);
228   }
229 
230   static bool decrement(Integral A, Integral *R) {
231     return sub(A, Integral(ReprT(1)), A.bitWidth(), R);
232   }
233 
234   static bool add(Integral A, Integral B, unsigned OpBits, Integral *R) {
235     return CheckAddUB(A.V, B.V, R->V);
236   }
237 
238   static bool sub(Integral A, Integral B, unsigned OpBits, Integral *R) {
239     return CheckSubUB(A.V, B.V, R->V);
240   }
241 
242   static bool mul(Integral A, Integral B, unsigned OpBits, Integral *R) {
243     return CheckMulUB(A.V, B.V, R->V);
244   }
245 
246   static bool rem(Integral A, Integral B, unsigned OpBits, Integral *R) {
247     *R = Integral(A.V % B.V);
248     return false;
249   }
250 
251   static bool div(Integral A, Integral B, unsigned OpBits, Integral *R) {
252     *R = Integral(A.V / B.V);
253     return false;
254   }
255 
256   static bool bitAnd(Integral A, Integral B, unsigned OpBits, Integral *R) {
257     *R = Integral(A.V & B.V);
258     return false;
259   }
260 
261   static bool bitOr(Integral A, Integral B, unsigned OpBits, Integral *R) {
262     *R = Integral(A.V | B.V);
263     return false;
264   }
265 
266   static bool bitXor(Integral A, Integral B, unsigned OpBits, Integral *R) {
267     *R = Integral(A.V ^ B.V);
268     return false;
269   }
270 
271   static bool neg(Integral A, Integral *R) {
272     if (Signed && A.isMin())
273       return true;
274 
275     *R = -A;
276     return false;
277   }
278 
279   static bool comp(Integral A, Integral *R) {
280     *R = Integral(~A.V);
281     return false;
282   }
283 
284   template <unsigned RHSBits, bool RHSSign>
285   static void shiftLeft(const Integral A, const Integral<RHSBits, RHSSign> B,
286                         unsigned OpBits, Integral *R) {
287     *R = Integral::from(A.V << B.V, OpBits);
288   }
289 
290   template <unsigned RHSBits, bool RHSSign>
291   static void shiftRight(const Integral A, const Integral<RHSBits, RHSSign> B,
292                          unsigned OpBits, Integral *R) {
293     *R = Integral::from(A.V >> B.V, OpBits);
294   }
295 
296 private:
297   template <typename T> static bool CheckAddUB(T A, T B, T &R) {
298     if constexpr (std::is_signed_v<T>) {
299       return llvm::AddOverflow<T>(A, B, R);
300     } else {
301       R = A + B;
302       return false;
303     }
304   }
305 
306   template <typename T> static bool CheckSubUB(T A, T B, T &R) {
307     if constexpr (std::is_signed_v<T>) {
308       return llvm::SubOverflow<T>(A, B, R);
309     } else {
310       R = A - B;
311       return false;
312     }
313   }
314 
315   template <typename T> static bool CheckMulUB(T A, T B, T &R) {
316     if constexpr (std::is_signed_v<T>) {
317       return llvm::MulOverflow<T>(A, B, R);
318     } else {
319       R = A * B;
320       return false;
321     }
322   }
323   template <typename T, T Min, T Max> static bool CheckRange(int64_t V) {
324     if constexpr (std::is_signed_v<T>) {
325       return Min <= V && V <= Max;
326     } else {
327       return V >= 0 && static_cast<uint64_t>(V) <= Max;
328     }
329   }
330 };
331 
332 template <unsigned Bits, bool Signed>
333 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, Integral<Bits, Signed> I) {
334   I.print(OS);
335   return OS;
336 }
337 
338 } // namespace interp
339 } // namespace clang
340 
341 #endif
342