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