xref: /freebsd/contrib/llvm-project/llvm/lib/Support/NativeFormatting.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1 //===- NativeFormatting.cpp - Low level formatting helpers -------*- 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 #include "llvm/Support/NativeFormatting.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/Support/Format.h"
14 #include "llvm/Support/MathExtras.h"
15 #include "llvm/Support/raw_ostream.h"
16 
17 #include <cmath>
18 
19 #if defined(_WIN32) && !defined(__MINGW32__)
20 #include <float.h> // For _fpclass in llvm::write_double.
21 #endif
22 
23 using namespace llvm;
24 
25 template<typename T, std::size_t N>
format_to_buffer(T Value,char (& Buffer)[N])26 static int format_to_buffer(T Value, char (&Buffer)[N]) {
27   char *EndPtr = std::end(Buffer);
28   char *CurPtr = EndPtr;
29 
30   do {
31     *--CurPtr = '0' + char(Value % 10);
32     Value /= 10;
33   } while (Value);
34   return EndPtr - CurPtr;
35 }
36 
writeWithCommas(raw_ostream & S,ArrayRef<char> Buffer)37 static void writeWithCommas(raw_ostream &S, ArrayRef<char> Buffer) {
38   assert(!Buffer.empty());
39 
40   ArrayRef<char> ThisGroup;
41   int InitialDigits = ((Buffer.size() - 1) % 3) + 1;
42   ThisGroup = Buffer.take_front(InitialDigits);
43   S.write(ThisGroup.data(), ThisGroup.size());
44 
45   Buffer = Buffer.drop_front(InitialDigits);
46   assert(Buffer.size() % 3 == 0);
47   while (!Buffer.empty()) {
48     S << ',';
49     ThisGroup = Buffer.take_front(3);
50     S.write(ThisGroup.data(), 3);
51     Buffer = Buffer.drop_front(3);
52   }
53 }
54 
55 template <typename T>
write_unsigned_impl(raw_ostream & S,T N,size_t MinDigits,IntegerStyle Style,bool IsNegative)56 static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits,
57                                 IntegerStyle Style, bool IsNegative) {
58   static_assert(std::is_unsigned_v<T>, "Value is not unsigned!");
59 
60   char NumberBuffer[128];
61   size_t Len = format_to_buffer(N, NumberBuffer);
62 
63   if (IsNegative)
64     S << '-';
65 
66   if (Len < MinDigits && Style != IntegerStyle::Number) {
67     for (size_t I = Len; I < MinDigits; ++I)
68       S << '0';
69   }
70 
71   if (Style == IntegerStyle::Number) {
72     writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len));
73   } else {
74     S.write(std::end(NumberBuffer) - Len, Len);
75   }
76 }
77 
78 template <typename T>
write_unsigned(raw_ostream & S,T N,size_t MinDigits,IntegerStyle Style,bool IsNegative=false)79 static void write_unsigned(raw_ostream &S, T N, size_t MinDigits,
80                            IntegerStyle Style, bool IsNegative = false) {
81   // Output using 32-bit div/mod if possible.
82   if (N == static_cast<uint32_t>(N))
83     write_unsigned_impl(S, static_cast<uint32_t>(N), MinDigits, Style,
84                         IsNegative);
85   else
86     write_unsigned_impl(S, N, MinDigits, Style, IsNegative);
87 }
88 
89 template <typename T>
write_signed(raw_ostream & S,T N,size_t MinDigits,IntegerStyle Style)90 static void write_signed(raw_ostream &S, T N, size_t MinDigits,
91                          IntegerStyle Style) {
92   static_assert(std::is_signed_v<T>, "Value is not signed!");
93 
94   using UnsignedT = std::make_unsigned_t<T>;
95 
96   if (N >= 0) {
97     write_unsigned(S, static_cast<UnsignedT>(N), MinDigits, Style);
98     return;
99   }
100 
101   UnsignedT UN = -(UnsignedT)N;
102   write_unsigned(S, UN, MinDigits, Style, true);
103 }
104 
write_integer(raw_ostream & S,unsigned int N,size_t MinDigits,IntegerStyle Style)105 void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits,
106                          IntegerStyle Style) {
107   write_unsigned(S, N, MinDigits, Style);
108 }
109 
write_integer(raw_ostream & S,int N,size_t MinDigits,IntegerStyle Style)110 void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits,
111                          IntegerStyle Style) {
112   write_signed(S, N, MinDigits, Style);
113 }
114 
write_integer(raw_ostream & S,unsigned long N,size_t MinDigits,IntegerStyle Style)115 void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits,
116                          IntegerStyle Style) {
117   write_unsigned(S, N, MinDigits, Style);
118 }
119 
write_integer(raw_ostream & S,long N,size_t MinDigits,IntegerStyle Style)120 void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits,
121                          IntegerStyle Style) {
122   write_signed(S, N, MinDigits, Style);
123 }
124 
write_integer(raw_ostream & S,unsigned long long N,size_t MinDigits,IntegerStyle Style)125 void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits,
126                          IntegerStyle Style) {
127   write_unsigned(S, N, MinDigits, Style);
128 }
129 
write_integer(raw_ostream & S,long long N,size_t MinDigits,IntegerStyle Style)130 void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits,
131                          IntegerStyle Style) {
132   write_signed(S, N, MinDigits, Style);
133 }
134 
write_hex(raw_ostream & S,uint64_t N,HexPrintStyle Style,std::optional<size_t> Width)135 void llvm::write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style,
136                      std::optional<size_t> Width) {
137   const size_t kMaxWidth = 128u;
138 
139   size_t W = std::min(kMaxWidth, Width.value_or(0u));
140 
141   unsigned Nibbles = (llvm::bit_width(N) + 3) / 4;
142   bool Prefix = (Style == HexPrintStyle::PrefixLower ||
143                  Style == HexPrintStyle::PrefixUpper);
144   bool Upper =
145       (Style == HexPrintStyle::Upper || Style == HexPrintStyle::PrefixUpper);
146   unsigned PrefixChars = Prefix ? 2 : 0;
147   unsigned NumChars =
148       std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars);
149 
150   char NumberBuffer[kMaxWidth];
151   ::memset(NumberBuffer, '0', std::size(NumberBuffer));
152   if (Prefix)
153     NumberBuffer[1] = 'x';
154   char *EndPtr = NumberBuffer + NumChars;
155   char *CurPtr = EndPtr;
156   while (N) {
157     unsigned char x = static_cast<unsigned char>(N) % 16;
158     *--CurPtr = hexdigit(x, !Upper);
159     N /= 16;
160   }
161 
162   S.write(NumberBuffer, NumChars);
163 }
164 
write_double(raw_ostream & S,double N,FloatStyle Style,std::optional<size_t> Precision)165 void llvm::write_double(raw_ostream &S, double N, FloatStyle Style,
166                         std::optional<size_t> Precision) {
167   size_t Prec = Precision.value_or(getDefaultPrecision(Style));
168 
169   if (std::isnan(N)) {
170     S << "nan";
171     return;
172   } else if (std::isinf(N)) {
173     S << (std::signbit(N) ? "-INF" : "INF");
174     return;
175   }
176 
177   char Letter;
178   if (Style == FloatStyle::Exponent)
179     Letter = 'e';
180   else if (Style == FloatStyle::ExponentUpper)
181     Letter = 'E';
182   else
183     Letter = 'f';
184 
185   SmallString<8> Spec;
186   llvm::raw_svector_ostream Out(Spec);
187   Out << "%." << Prec << Letter;
188 
189   if (Style == FloatStyle::Exponent || Style == FloatStyle::ExponentUpper) {
190 #ifdef _WIN32
191 // On MSVCRT and compatible, output of %e is incompatible to Posix
192 // by default. Number of exponent digits should be at least 2. "%+03d"
193 // FIXME: Implement our formatter to here or Support/Format.h!
194 #if defined(__MINGW32__)
195     // FIXME: It should be generic to C++11.
196     if (N == 0.0 && std::signbit(N)) {
197       char NegativeZero[] = "-0.000000e+00";
198       if (Style == FloatStyle::ExponentUpper)
199         NegativeZero[strlen(NegativeZero) - 4] = 'E';
200       S << NegativeZero;
201       return;
202     }
203 #else
204     int fpcl = _fpclass(N);
205 
206     // negative zero
207     if (fpcl == _FPCLASS_NZ) {
208       char NegativeZero[] = "-0.000000e+00";
209       if (Style == FloatStyle::ExponentUpper)
210         NegativeZero[strlen(NegativeZero) - 4] = 'E';
211       S << NegativeZero;
212       return;
213     }
214 #endif
215 
216     char buf[32];
217     unsigned len;
218     len = format(Spec.c_str(), N).snprint(buf, sizeof(buf));
219     if (len <= sizeof(buf) - 2) {
220       if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') &&
221           buf[len - 3] == '0') {
222         int cs = buf[len - 4];
223         if (cs == '+' || cs == '-') {
224           int c1 = buf[len - 2];
225           int c0 = buf[len - 1];
226           if (isdigit(static_cast<unsigned char>(c1)) &&
227               isdigit(static_cast<unsigned char>(c0))) {
228             // Trim leading '0': "...e+012" -> "...e+12\0"
229             buf[len - 3] = c1;
230             buf[len - 2] = c0;
231             buf[--len] = 0;
232           }
233         }
234       }
235       S << buf;
236       return;
237     }
238 #endif
239   }
240 
241   if (Style == FloatStyle::Percent)
242     N *= 100.0;
243 
244   char Buf[32];
245   format(Spec.c_str(), N).snprint(Buf, sizeof(Buf));
246   S << Buf;
247   if (Style == FloatStyle::Percent)
248     S << '%';
249 }
250 
isPrefixedHexStyle(HexPrintStyle S)251 bool llvm::isPrefixedHexStyle(HexPrintStyle S) {
252   return (S == HexPrintStyle::PrefixLower || S == HexPrintStyle::PrefixUpper);
253 }
254 
getDefaultPrecision(FloatStyle Style)255 size_t llvm::getDefaultPrecision(FloatStyle Style) {
256   switch (Style) {
257   case FloatStyle::Exponent:
258   case FloatStyle::ExponentUpper:
259     return 6; // Number of decimal places.
260   case FloatStyle::Fixed:
261   case FloatStyle::Percent:
262     return 2; // Number of decimal places.
263   }
264   llvm_unreachable("Unknown FloatStyle enum");
265 }
266