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