LLVM  14.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 #include <float.h>
17 
18 using namespace llvm;
19 
20 template<typename T, std::size_t N>
21 static int format_to_buffer(T Value, char (&Buffer)[N]) {
22  char *EndPtr = std::end(Buffer);
23  char *CurPtr = EndPtr;
24 
25  do {
26  *--CurPtr = '0' + char(Value % 10);
27  Value /= 10;
28  } while (Value);
29  return EndPtr - CurPtr;
30 }
31 
33  assert(!Buffer.empty());
34 
35  ArrayRef<char> ThisGroup;
36  int InitialDigits = ((Buffer.size() - 1) % 3) + 1;
37  ThisGroup = Buffer.take_front(InitialDigits);
38  S.write(ThisGroup.data(), ThisGroup.size());
39 
40  Buffer = Buffer.drop_front(InitialDigits);
41  assert(Buffer.size() % 3 == 0);
42  while (!Buffer.empty()) {
43  S << ',';
44  ThisGroup = Buffer.take_front(3);
45  S.write(ThisGroup.data(), 3);
46  Buffer = Buffer.drop_front(3);
47  }
48 }
49 
50 template <typename T>
51 static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits,
52  IntegerStyle Style, bool IsNegative) {
53  static_assert(std::is_unsigned<T>::value, "Value is not unsigned!");
54 
55  char NumberBuffer[128];
56  std::memset(NumberBuffer, '0', sizeof(NumberBuffer));
57 
58  size_t Len = 0;
59  Len = format_to_buffer(N, NumberBuffer);
60 
61  if (IsNegative)
62  S << '-';
63 
64  if (Len < MinDigits && Style != IntegerStyle::Number) {
65  for (size_t I = Len; I < MinDigits; ++I)
66  S << '0';
67  }
68 
69  if (Style == IntegerStyle::Number) {
70  writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len));
71  } else {
72  S.write(std::end(NumberBuffer) - Len, Len);
73  }
74 }
75 
76 template <typename T>
77 static void write_unsigned(raw_ostream &S, T N, size_t MinDigits,
78  IntegerStyle Style, bool IsNegative = false) {
79  // Output using 32-bit div/mod if possible.
80  if (N == static_cast<uint32_t>(N))
81  write_unsigned_impl(S, static_cast<uint32_t>(N), MinDigits, Style,
82  IsNegative);
83  else
84  write_unsigned_impl(S, N, MinDigits, Style, IsNegative);
85 }
86 
87 template <typename T>
88 static void write_signed(raw_ostream &S, T N, size_t MinDigits,
90  static_assert(std::is_signed<T>::value, "Value is not signed!");
91 
92  using UnsignedT = std::make_unsigned_t<T>;
93 
94  if (N >= 0) {
95  write_unsigned(S, static_cast<UnsignedT>(N), MinDigits, Style);
96  return;
97  }
98 
99  UnsignedT UN = -(UnsignedT)N;
100  write_unsigned(S, UN, MinDigits, Style, true);
101 }
102 
103 void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits,
105  write_unsigned(S, N, MinDigits, Style);
106 }
107 
108 void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits,
110  write_signed(S, N, MinDigits, Style);
111 }
112 
113 void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits,
115  write_unsigned(S, N, MinDigits, Style);
116 }
117 
118 void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits,
120  write_signed(S, N, MinDigits, Style);
121 }
122 
123 void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits,
125  write_unsigned(S, N, MinDigits, Style);
126 }
127 
128 void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits,
130  write_signed(S, N, MinDigits, Style);
131 }
132 
135  const size_t kMaxWidth = 128u;
136 
137  size_t W = std::min(kMaxWidth, Width.getValueOr(0u));
138 
139  unsigned Nibbles = (64 - countLeadingZeros(N) + 3) / 4;
142  bool Upper =
144  unsigned PrefixChars = Prefix ? 2 : 0;
145  unsigned NumChars =
146  std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars);
147 
148  char NumberBuffer[kMaxWidth];
149  ::memset(NumberBuffer, '0', llvm::array_lengthof(NumberBuffer));
150  if (Prefix)
151  NumberBuffer[1] = 'x';
152  char *EndPtr = NumberBuffer + NumChars;
153  char *CurPtr = EndPtr;
154  while (N) {
155  unsigned char x = static_cast<unsigned char>(N) % 16;
156  *--CurPtr = hexdigit(x, !Upper);
157  N /= 16;
158  }
159 
160  S.write(NumberBuffer, NumChars);
161 }
162 
164  Optional<size_t> Precision) {
165  size_t Prec = Precision.getValueOr(getDefaultPrecision(Style));
166 
167  if (std::isnan(N)) {
168  S << "nan";
169  return;
170  } else if (std::isinf(N)) {
171  S << "INF";
172  return;
173  }
174 
175  char Letter;
177  Letter = 'e';
178  else if (Style == FloatStyle::ExponentUpper)
179  Letter = 'E';
180  else
181  Letter = 'f';
182 
183  SmallString<8> Spec;
184  llvm::raw_svector_ostream Out(Spec);
185  Out << "%." << Prec << Letter;
186 
188 #ifdef _WIN32
189 // On MSVCRT and compatible, output of %e is incompatible to Posix
190 // by default. Number of exponent digits should be at least 2. "%+03d"
191 // FIXME: Implement our formatter to here or Support/Format.h!
192 #if defined(__MINGW32__)
193  // FIXME: It should be generic to C++11.
194  if (N == 0.0 && std::signbit(N)) {
195  char NegativeZero[] = "-0.000000e+00";
197  NegativeZero[strlen(NegativeZero) - 4] = 'E';
198  S << NegativeZero;
199  return;
200  }
201 #else
202  int fpcl = _fpclass(N);
203 
204  // negative zero
205  if (fpcl == _FPCLASS_NZ) {
206  char NegativeZero[] = "-0.000000e+00";
208  NegativeZero[strlen(NegativeZero) - 4] = 'E';
209  S << NegativeZero;
210  return;
211  }
212 #endif
213 
214  char buf[32];
215  unsigned len;
216  len = format(Spec.c_str(), N).snprint(buf, sizeof(buf));
217  if (len <= sizeof(buf) - 2) {
218  if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') &&
219  buf[len - 3] == '0') {
220  int cs = buf[len - 4];
221  if (cs == '+' || cs == '-') {
222  int c1 = buf[len - 2];
223  int c0 = buf[len - 1];
224  if (isdigit(static_cast<unsigned char>(c1)) &&
225  isdigit(static_cast<unsigned char>(c0))) {
226  // Trim leading '0': "...e+012" -> "...e+12\0"
227  buf[len - 3] = c1;
228  buf[len - 2] = c0;
229  buf[--len] = 0;
230  }
231  }
232  }
233  S << buf;
234  return;
235  }
236 #endif
237  }
238 
239  if (Style == FloatStyle::Percent)
240  N *= 100.0;
241 
242  char Buf[32];
243  format(Spec.c_str(), N).snprint(Buf, sizeof(Buf));
244  S << Buf;
245  if (Style == FloatStyle::Percent)
246  S << '%';
247 }
248 
251 }
252 
254  switch (Style) {
257  return 6; // Number of decimal places.
258  case FloatStyle::Fixed:
259  case FloatStyle::Percent:
260  return 2; // Number of decimal places.
261  }
263 }
MathExtras.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::HexPrintStyle::Upper
@ Upper
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:164
T
NativeFormatting.h
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:208
writeWithCommas
static void writeWithCommas(raw_ostream &S, ArrayRef< char > Buffer)
Definition: NativeFormatting.cpp:32
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::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:88
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:77
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::FloatStyle
FloatStyle
Definition: NativeFormatting.h:17
format_to_buffer
static int format_to_buffer(T Value, char(&Buffer)[N])
Definition: NativeFormatting.cpp:21
llvm::array_lengthof
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
Definition: STLExtras.h:1424
llvm::SmallString< 8 >
llvm::Optional::getValueOr
constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION
Definition: Optional.h:297
llvm::SmallString::c_str
const char * c_str()
Definition: SmallString.h:262
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:59
StringExtras.h
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:51
llvm::FloatStyle::Exponent
@ Exponent
llvm::getDefaultPrecision
size_t getDefaultPrecision(FloatStyle Style)
Definition: NativeFormatting.cpp:253
llvm::write_hex
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, Optional< size_t > Width=None)
Definition: NativeFormatting.cpp:133
llvm::ArrayRef< char >
llvm::min
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:357
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_BUILTIN_UNREACHABLE
#define LLVM_BUILTIN_UNREACHABLE
LLVM_BUILTIN_UNREACHABLE - On compilers which support it, expands to an expression which states that ...
Definition: Compiler.h:335
llvm::isPrefixedHexStyle
bool isPrefixedHexStyle(HexPrintStyle S)
Definition: NativeFormatting.cpp:249
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::write_double
void write_double(raw_ostream &S, double D, FloatStyle Style, Optional< size_t > Precision=None)
Definition: NativeFormatting.cpp:163
llvm::write_integer
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
Definition: NativeFormatting.cpp:103
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:225
llvm::AMDGPU::Hwreg::Width
Width
Definition: SIDefines.h:413
N
#define N
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:340
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:658
raw_ostream.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::FloatStyle::Fixed
@ Fixed