LLVM  16.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<T>::value, "Value is not unsigned!");
59 
60  char NumberBuffer[128];
61  std::memset(NumberBuffer, '0', sizeof(NumberBuffer));
62 
63  size_t Len = 0;
64  Len = format_to_buffer(N, NumberBuffer);
65 
66  if (IsNegative)
67  S << '-';
68 
69  if (Len < MinDigits && Style != IntegerStyle::Number) {
70  for (size_t I = Len; I < MinDigits; ++I)
71  S << '0';
72  }
73 
74  if (Style == IntegerStyle::Number) {
75  writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len));
76  } else {
77  S.write(std::end(NumberBuffer) - Len, Len);
78  }
79 }
80 
81 template <typename T>
82 static void write_unsigned(raw_ostream &S, T N, size_t MinDigits,
83  IntegerStyle Style, bool IsNegative = 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);
88  else
89  write_unsigned_impl(S, N, MinDigits, Style, IsNegative);
90 }
91 
92 template <typename T>
93 static void write_signed(raw_ostream &S, T N, size_t MinDigits,
95  static_assert(std::is_signed<T>::value, "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);
101  return;
102  }
103 
104  UnsignedT UN = -(UnsignedT)N;
105  write_unsigned(S, UN, MinDigits, Style, true);
106 }
107 
108 void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits,
110  write_unsigned(S, N, MinDigits, Style);
111 }
112 
113 void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits,
115  write_signed(S, N, MinDigits, Style);
116 }
117 
118 void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits,
120  write_unsigned(S, N, MinDigits, Style);
121 }
122 
123 void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits,
125  write_signed(S, N, MinDigits, Style);
126 }
127 
128 void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits,
130  write_unsigned(S, N, MinDigits, Style);
131 }
132 
133 void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits,
135  write_signed(S, N, MinDigits, Style);
136 }
137 
140  const size_t kMaxWidth = 128u;
141 
142  size_t W = std::min(kMaxWidth, Width.value_or(0u));
143 
144  unsigned Nibbles = (64 - countLeadingZeros(N) + 3) / 4;
147  bool Upper =
149  unsigned PrefixChars = Prefix ? 2 : 0;
150  unsigned NumChars =
151  std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars);
152 
153  char NumberBuffer[kMaxWidth];
154  ::memset(NumberBuffer, '0', std::size(NumberBuffer));
155  if (Prefix)
156  NumberBuffer[1] = 'x';
157  char *EndPtr = NumberBuffer + NumChars;
158  char *CurPtr = EndPtr;
159  while (N) {
160  unsigned char x = static_cast<unsigned char>(N) % 16;
161  *--CurPtr = hexdigit(x, !Upper);
162  N /= 16;
163  }
164 
165  S.write(NumberBuffer, NumChars);
166 }
167 
169  Optional<size_t> Precision) {
170  size_t Prec = Precision.value_or(getDefaultPrecision(Style));
171 
172  if (std::isnan(N)) {
173  S << "nan";
174  return;
175  } else if (std::isinf(N)) {
176  S << (std::signbit(N) ? "-INF" : "INF");
177  return;
178  }
179 
180  char Letter;
182  Letter = 'e';
183  else if (Style == FloatStyle::ExponentUpper)
184  Letter = 'E';
185  else
186  Letter = 'f';
187 
188  SmallString<8> Spec;
189  llvm::raw_svector_ostream Out(Spec);
190  Out << "%." << Prec << Letter;
191 
193 #ifdef _WIN32
194 // On MSVCRT and compatible, output of %e is incompatible to Posix
195 // by default. Number of exponent digits should be at least 2. "%+03d"
196 // FIXME: Implement our formatter to here or Support/Format.h!
197 #if defined(__MINGW32__)
198  // FIXME: It should be generic to C++11.
199  if (N == 0.0 && std::signbit(N)) {
200  char NegativeZero[] = "-0.000000e+00";
202  NegativeZero[strlen(NegativeZero) - 4] = 'E';
203  S << NegativeZero;
204  return;
205  }
206 #else
207  int fpcl = _fpclass(N);
208 
209  // negative zero
210  if (fpcl == _FPCLASS_NZ) {
211  char NegativeZero[] = "-0.000000e+00";
213  NegativeZero[strlen(NegativeZero) - 4] = 'E';
214  S << NegativeZero;
215  return;
216  }
217 #endif
218 
219  char buf[32];
220  unsigned len;
221  len = format(Spec.c_str(), N).snprint(buf, sizeof(buf));
222  if (len <= sizeof(buf) - 2) {
223  if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') &&
224  buf[len - 3] == '0') {
225  int cs = buf[len - 4];
226  if (cs == '+' || cs == '-') {
227  int c1 = buf[len - 2];
228  int c0 = buf[len - 1];
229  if (isdigit(static_cast<unsigned char>(c1)) &&
230  isdigit(static_cast<unsigned char>(c0))) {
231  // Trim leading '0': "...e+012" -> "...e+12\0"
232  buf[len - 3] = c1;
233  buf[len - 2] = c0;
234  buf[--len] = 0;
235  }
236  }
237  }
238  S << buf;
239  return;
240  }
241 #endif
242  }
243 
244  if (Style == FloatStyle::Percent)
245  N *= 100.0;
246 
247  char Buf[32];
248  format(Spec.c_str(), N).snprint(Buf, sizeof(Buf));
249  S << Buf;
250  if (Style == FloatStyle::Percent)
251  S << '%';
252 }
253 
256 }
257 
259  switch (Style) {
262  return 6; // Number of decimal places.
263  case FloatStyle::Fixed:
264  case FloatStyle::Percent:
265  return 2; // Number of decimal places.
266  }
267  llvm_unreachable("Unknown FloatStyle enum");
268 }
MathExtras.h
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:161
T
NativeFormatting.h
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:266
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::Optional< size_t >
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:159
llvm::ArrayRef::data
const T * data() const
Definition: ArrayRef.h:161
SmallString.h
write_signed
static void write_signed(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style)
Definition: NativeFormatting.cpp:93
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:82
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::SmallString::c_str
const char * c_str()
Definition: SmallString.h:263
llvm::ArrayRef::drop_front
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:203
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:32
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:258
llvm::write_hex
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, Optional< size_t > Width=None)
Definition: NativeFormatting.cpp:138
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:254
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:227
llvm::HexPrintStyle
HexPrintStyle
Definition: NativeFormatting.h:22
x
TODO unsigned x
Definition: README.txt:10
llvm::write_double
void write_double(raw_ostream &S, double D, FloatStyle Style, Optional< size_t > Precision=None)
Definition: NativeFormatting.cpp:168
llvm::write_integer
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
Definition: NativeFormatting.cpp:108
llvm::countLeadingZeros
unsigned countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: MathExtras.h:220
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:164
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:658
raw_ostream.h
llvm::Optional::value_or
constexpr T value_or(U &&alt) const &
Definition: Optional.h:334
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::FloatStyle::Fixed
@ Fixed