LLVM  17.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"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/Support/Format.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>
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 
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>
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>
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>
90 static void write_signed(raw_ostream &S, T N, size_t MinDigits,
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 
105 void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits,
107  write_unsigned(S, N, MinDigits, Style);
108 }
109 
110 void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits,
112  write_signed(S, N, MinDigits, Style);
113 }
114 
115 void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits,
117  write_unsigned(S, N, MinDigits, Style);
118 }
119 
120 void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits,
122  write_signed(S, N, MinDigits, Style);
123 }
124 
125 void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits,
127  write_unsigned(S, N, MinDigits, Style);
128 }
129 
130 void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits,
132  write_signed(S, N, MinDigits, Style);
133 }
134 
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;
144  bool Upper =
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 
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;
179  Letter = 'e';
180  else if (Style == FloatStyle::ExponentUpper)
181  Letter = 'E';
182  else
183  Letter = 'f';
184 
187  Out << "%." << Prec << Letter;
188 
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";
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";
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 
253 }
254 
256  switch (Style) {
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 }
MathExtras.h
llvm::bit_width
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition: bit.h:281
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::HexPrintStyle::Upper
@ Upper
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:159
T
NativeFormatting.h
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:276
writeWithCommas
static void writeWithCommas(raw_ostream &S, ArrayRef< char > Buffer)
Definition: NativeFormatting.cpp:37
llvm::FloatStyle::Percent
@ Percent
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::max
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:337
llvm::IntegerStyle
IntegerStyle
Definition: NativeFormatting.h:18
Format.h
llvm::ArrayRef::empty
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:158
llvm::ArrayRef::data
const T * data() const
Definition: ArrayRef.h:160
SmallString.h
write_signed
static void write_signed(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style)
Definition: NativeFormatting.cpp:90
llvm::FloatStyle::ExponentUpper
@ ExponentUpper
write_unsigned
static void write_unsigned(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative=false)
Definition: NativeFormatting.cpp:79
llvm::write_double
void write_double(raw_ostream &S, double D, FloatStyle Style, std::optional< size_t > Precision=std::nullopt)
Definition: NativeFormatting.cpp:165
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
llvm::FloatStyle
FloatStyle
Definition: NativeFormatting.h:17
format_to_buffer
static int format_to_buffer(T Value, char(&Buffer)[N])
Definition: NativeFormatting.cpp:26
llvm::SmallString< 8 >
llvm::ArrayRef::drop_front
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:202
llvm::IntegerStyle::Number
@ Number
uint64_t
llvm::HexPrintStyle::PrefixLower
@ PrefixLower
I
#define I(x, y, z)
Definition: MD5.cpp:58
StringExtras.h
size
i< reg-> size
Definition: README.txt:166
ArrayRef.h
llvm::HexStyle::Style
Style
Definition: MCInstPrinter.h:33
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
write_unsigned_impl
static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative)
Definition: NativeFormatting.cpp:56
llvm::FloatStyle::Exponent
@ Exponent
llvm::getDefaultPrecision
size_t getDefaultPrecision(FloatStyle Style)
Definition: NativeFormatting.cpp:255
llvm::write_hex
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
Definition: NativeFormatting.cpp:135
llvm::ArrayRef< char >
llvm::min
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:357
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
uint32_t
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::format
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
llvm::isPrefixedHexStyle
bool isPrefixedHexStyle(HexPrintStyle S)
Definition: NativeFormatting.cpp:251
llvm::HexPrintStyle::PrefixUpper
@ PrefixUpper
llvm::ArrayRef::take_front
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition: ArrayRef.h:226
llvm::HexPrintStyle
HexPrintStyle
Definition: NativeFormatting.h:22
x
TODO unsigned x
Definition: README.txt:10
llvm::Spec
Definition: FunctionSpecialization.h:87
llvm::write_integer
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
Definition: NativeFormatting.cpp:105
llvm::AMDGPU::Hwreg::Width
Width
Definition: SIDefines.h:439
N
#define N
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
raw_ostream.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::FloatStyle::Fixed
@ Fixed