LLVM 23.0.0git
NativeFormatting.cpp
Go to the documentation of this file.
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
10#include "llvm/ADT/ArrayRef.h"
13#include "llvm/Support/Format.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
37 assert(!Buffer.empty());
38
39 ArrayRef<char> ThisGroup;
40 int InitialDigits = ((Buffer.size() - 1) % 3) + 1;
41 ThisGroup = Buffer.take_front(InitialDigits);
42 S.write(ThisGroup.data(), ThisGroup.size());
43
44 Buffer = Buffer.drop_front(InitialDigits);
45 assert(Buffer.size() % 3 == 0);
46 while (!Buffer.empty()) {
47 S << ',';
48 ThisGroup = Buffer.take_front(3);
49 S.write(ThisGroup.data(), 3);
50 Buffer = Buffer.drop_front(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, ArrayRef<char>(std::end(NumberBuffer) - Len, Len));
75 } else {
76 S.write(std::end(NumberBuffer) - Len, 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, 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, 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, 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, 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
140 std::optional<size_t> Width) {
141 const size_t kMaxWidth = 128u;
142
143 size_t W = std::min(kMaxWidth, Width.value_or(0u));
144
145 unsigned Nibbles = (llvm::bit_width(N) + 3) / 4;
146 bool Prefix = (Style == HexPrintStyle::PrefixLower ||
148 bool Upper =
150 unsigned PrefixChars = Prefix ? 2 : 0;
151 unsigned NumChars =
152 std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars);
153
154 char NumberBuffer[kMaxWidth];
155 ::memset(NumberBuffer, '0', 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, !Upper);
163 N /= 16;
164 }
165
166 S.write(NumberBuffer, NumChars);
167}
168
170 std::optional<size_t> Precision) {
171 size_t Prec = Precision.value_or(getDefaultPrecision(Style));
172
173 if (std::isnan(N)) {
174 S << "nan";
175 return;
176 } else if (std::isinf(N)) {
177 S << (std::signbit(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
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(Spec.c_str(), N).snprint(Buf, sizeof(Buf));
250 S << Buf;
251 if (Style == FloatStyle::Percent)
252 S << '%';
253}
254
258
260 switch (Style) {
263 return 6; // Number of decimal places.
266 return 2; // Number of decimal places.
267 }
268 llvm_unreachable("Unknown FloatStyle enum");
269}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative, bool NonNegativePlus)
static int format_to_buffer(T Value, char(&Buffer)[N])
static void write_unsigned(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative=false, bool NonNegativePlus=false)
static void write_signed(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool NonNegativePlus=false)
static void writeWithCommas(raw_ostream &S, ArrayRef< char > Buffer)
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:219
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:195
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
const T * data() const
Definition ArrayRef.h:139
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:303
LLVM_ABI void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style, bool NonNegativePlus=false)
LLVM_ABI size_t getDefaultPrecision(FloatStyle Style)
char hexdigit(unsigned X, bool LowerCase=false)
hexdigit - Return the hexadecimal character for the given number X (which should be less than 16).
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
LLVM_ABI void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
LLVM_ABI void write_double(raw_ostream &S, double D, FloatStyle Style, std::optional< size_t > Precision=std::nullopt)
LLVM_ABI bool isPrefixedHexStyle(HexPrintStyle S)
#define N