NativeFormatting.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. #include "llvm/Support/NativeFormatting.h"
  10. #include "llvm/ADT/ArrayRef.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/StringExtras.h"
  13. #include "llvm/Support/Format.h"
  14. using namespace llvm;
  15. static bool isHexStyle(IntegerStyle S) {
  16. switch (S) {
  17. case IntegerStyle::HexLowerNoPrefix:
  18. case IntegerStyle::HexLowerPrefix:
  19. case IntegerStyle::HexUpperNoPrefix:
  20. case IntegerStyle::HexUpperPrefix:
  21. return true;
  22. default:
  23. return false;
  24. }
  25. LLVM_BUILTIN_UNREACHABLE;
  26. }
  27. static HexStyle intHexStyleToHexStyle(IntegerStyle S) {
  28. assert(isHexStyle(S));
  29. switch (S) {
  30. case IntegerStyle::HexLowerNoPrefix:
  31. return HexStyle::Lower;
  32. case IntegerStyle::HexLowerPrefix:
  33. return HexStyle::PrefixLower;
  34. case IntegerStyle::HexUpperNoPrefix:
  35. return HexStyle::Upper;
  36. case IntegerStyle::HexUpperPrefix:
  37. return HexStyle::PrefixUpper;
  38. default:
  39. break;
  40. }
  41. LLVM_BUILTIN_UNREACHABLE;
  42. }
  43. static void writePadding(raw_ostream &S, Optional<int> FieldWidth,
  44. size_t Chars) {
  45. if (!FieldWidth.hasValue())
  46. return;
  47. int Pad = *FieldWidth - Chars;
  48. if (Pad > 0)
  49. S.indent(Pad);
  50. }
  51. template<typename T, std::size_t N>
  52. static int format_to_buffer(T Value, char (&Buffer)[N]) {
  53. char *EndPtr = std::end(Buffer);
  54. char *CurPtr = EndPtr;
  55. do {
  56. *--CurPtr = '0' + char(Value % 10);
  57. Value /= 10;
  58. } while (Value);
  59. return EndPtr - CurPtr;
  60. }
  61. static void repeat_char(raw_ostream &S, char C, size_t Times) {
  62. for (size_t I = 0; I < Times; ++I)
  63. S << C;
  64. }
  65. static void writeWithCommas(raw_ostream &S, ArrayRef<char> Buffer) {
  66. assert(!Buffer.empty());
  67. ArrayRef<char> ThisGroup;
  68. int InitialDigits = ((Buffer.size() - 1) % 3) + 1;
  69. ThisGroup = Buffer.take_front(InitialDigits);
  70. S.write(ThisGroup.data(), ThisGroup.size());
  71. Buffer = Buffer.drop_front(InitialDigits);
  72. assert(Buffer.size() % 3 == 0);
  73. while (!Buffer.empty()) {
  74. S << ',';
  75. ThisGroup = Buffer.take_front(3);
  76. S.write(ThisGroup.data(), 3);
  77. Buffer = Buffer.drop_front(3);
  78. }
  79. }
  80. template <typename T>
  81. static void write_unsigned_impl(raw_ostream &S, T N, IntegerStyle Style,
  82. Optional<size_t> Precision, Optional<int> Width,
  83. bool IsNegative) {
  84. static_assert(std::is_unsigned<T>::value, "Value is not unsigned!");
  85. if (Style == IntegerStyle::Exponent) {
  86. write_double(S, static_cast<double>(N), FloatStyle::Exponent, Precision,
  87. Width);
  88. return;
  89. } else if (Style == IntegerStyle::ExponentUpper) {
  90. write_double(S, static_cast<double>(N), FloatStyle::ExponentUpper,
  91. Precision, Width);
  92. return;
  93. } else if (isHexStyle(Style)) {
  94. write_hex(S, N, intHexStyleToHexStyle(Style), Precision, Width);
  95. return;
  96. }
  97. size_t Prec = Precision.getValueOr(getDefaultPrecision(Style));
  98. char NumberBuffer[128];
  99. std::memset(NumberBuffer, '0', sizeof(NumberBuffer));
  100. size_t Len = 0;
  101. Len = format_to_buffer(N, NumberBuffer);
  102. bool WriteDecimal =
  103. ((Style == IntegerStyle::Fixed || Style == IntegerStyle::Percent) &&
  104. Prec > 0);
  105. size_t LeadingZeros = 0;
  106. if ((Style == IntegerStyle::Integer || Style == IntegerStyle::Number) &&
  107. Prec > 0) {
  108. if (Prec > Len)
  109. LeadingZeros = Prec - Len;
  110. }
  111. Len += LeadingZeros;
  112. // One for the decimal sign, one for each point of precision.
  113. size_t DecimalChars = WriteDecimal ? 1 + Prec : 0;
  114. // One character for the negative sign.
  115. size_t Neg = (IsNegative) ? 1 : 0;
  116. // One comma for each group of 3 digits.
  117. size_t Commas = (Style != IntegerStyle::Number) ? 0 : (Len - 1) / 3;
  118. size_t PercentChars = 0;
  119. if (Style == IntegerStyle::Percent) {
  120. // For all numbers except 0, we append two additional 0s.
  121. PercentChars = (N == 0) ? 1 : 3;
  122. }
  123. writePadding(S, Width, Len + DecimalChars + Neg + Commas + PercentChars);
  124. if (IsNegative)
  125. S << '-';
  126. if (Style == IntegerStyle::Number) {
  127. writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len));
  128. } else {
  129. S.write(std::end(NumberBuffer) - Len, Len);
  130. if (Style == IntegerStyle::Percent && N != 0) {
  131. // Rather than multiply by 100, write the characters manually, in case the
  132. // multiplication would overflow.
  133. S << "00";
  134. }
  135. }
  136. if (WriteDecimal) {
  137. S << '.';
  138. repeat_char(S, '0', Prec);
  139. }
  140. if (Style == IntegerStyle::Percent)
  141. S << '%';
  142. }
  143. template <typename T>
  144. static void write_unsigned(raw_ostream &S, T N, IntegerStyle Style,
  145. Optional<size_t> Precision, Optional<int> Width,
  146. bool IsNegative = false) {
  147. write_unsigned_impl(S, N, Style, Precision, Width, IsNegative);
  148. }
  149. static void write_unsigned(raw_ostream &S, uint64_t N, IntegerStyle Style,
  150. Optional<size_t> Precision, Optional<int> Width,
  151. bool IsNegative = false) {
  152. // Output using 32-bit div/mod if possible.
  153. if (N == static_cast<uint32_t>(N)) {
  154. write_unsigned_impl(S, static_cast<uint32_t>(N), Style, Precision, Width,
  155. IsNegative);
  156. return;
  157. }
  158. write_unsigned_impl(S, N, Style, Precision, Width, IsNegative);
  159. }
  160. template <typename T>
  161. static void write_signed(raw_ostream &S, T N, IntegerStyle Style,
  162. Optional<size_t> Precision, Optional<int> Width) {
  163. static_assert(std::is_signed<T>::value, "Value is not signed!");
  164. using UnsignedT = typename std::make_unsigned<T>::type;
  165. if (N >= 0) {
  166. write_unsigned(S, static_cast<UnsignedT>(N), Style, Precision, Width);
  167. return;
  168. }
  169. UnsignedT UN = -(UnsignedT)N;
  170. if (isHexStyle(Style)) {
  171. static_assert(sizeof(UnsignedT) == sizeof(T),
  172. "Types do not have the same size!");
  173. std::memcpy(&UN, &N, sizeof(N));
  174. write_hex(S, UN, intHexStyleToHexStyle(Style), Precision, Width);
  175. return;
  176. }
  177. write_unsigned(S, UN, Style, Precision, Width, true);
  178. }
  179. void llvm::write_ulong(raw_ostream &S, unsigned long N, IntegerStyle Style,
  180. Optional<size_t> Precision, Optional<int> Width) {
  181. write_unsigned(S, N, Style, Precision, Width);
  182. }
  183. void llvm::write_long(raw_ostream &S, long N, IntegerStyle Style,
  184. Optional<size_t> Precision, Optional<int> Width) {
  185. write_signed(S, N, Style, Precision, Width);
  186. }
  187. void llvm::write_ulonglong(raw_ostream &S, unsigned long long N,
  188. IntegerStyle Style, Optional<size_t> Precision,
  189. Optional<int> Width) {
  190. write_unsigned(S, N, Style, Precision, Width);
  191. }
  192. void llvm::write_longlong(raw_ostream &S, long long N, IntegerStyle Style,
  193. Optional<size_t> Precision, Optional<int> Width) {
  194. write_signed(S, N, Style, Precision, Width);
  195. }
  196. void llvm::write_hex(raw_ostream &S, unsigned long long N, HexStyle Style,
  197. Optional<size_t> Precision, Optional<int> Width) {
  198. constexpr size_t kMaxWidth = 128u;
  199. size_t Prec =
  200. std::min(kMaxWidth, Precision.getValueOr(getDefaultPrecision(Style)));
  201. unsigned Nibbles = (64 - countLeadingZeros(N) + 3) / 4;
  202. bool Prefix =
  203. (Style == HexStyle::PrefixLower || Style == HexStyle::PrefixUpper);
  204. bool Upper = (Style == HexStyle::Upper || Style == HexStyle::PrefixUpper);
  205. unsigned PrefixChars = Prefix ? 2 : 0;
  206. unsigned NumChars = std::max(static_cast<unsigned>(Prec),
  207. std::max(1u, Nibbles) + PrefixChars);
  208. char NumberBuffer[kMaxWidth];
  209. ::memset(NumberBuffer, '0', llvm::array_lengthof(NumberBuffer));
  210. if (Prefix)
  211. NumberBuffer[1] = 'x';
  212. char *EndPtr = NumberBuffer + NumChars;
  213. char *CurPtr = EndPtr;
  214. while (N) {
  215. unsigned char x = static_cast<unsigned char>(N) % 16;
  216. *--CurPtr = hexdigit(x, !Upper);
  217. N /= 16;
  218. }
  219. writePadding(S, Width, NumChars);
  220. S.write(NumberBuffer, NumChars);
  221. }
  222. void llvm::write_double(raw_ostream &S, double N, FloatStyle Style,
  223. Optional<size_t> Precision, Optional<int> Width) {
  224. size_t Prec = Precision.getValueOr(getDefaultPrecision(Style));
  225. if (std::isnan(N)) {
  226. writePadding(S, Width, 3);
  227. S << "nan";
  228. return;
  229. } else if (std::isinf(N)) {
  230. writePadding(S, Width, 3);
  231. S << "INF";
  232. return;
  233. }
  234. char Letter;
  235. if (Style == FloatStyle::Exponent)
  236. Letter = 'e';
  237. else if (Style == FloatStyle::ExponentUpper)
  238. Letter = 'E';
  239. else
  240. Letter = 'f';
  241. SmallString<8> Spec;
  242. llvm::raw_svector_ostream Out(Spec);
  243. Out << "%." << Prec << Letter;
  244. if (Style == FloatStyle::Exponent || Style == FloatStyle::ExponentUpper) {
  245. #ifdef _WIN32
  246. // On MSVCRT and compatible, output of %e is incompatible to Posix
  247. // by default. Number of exponent digits should be at least 2. "%+03d"
  248. // FIXME: Implement our formatter to here or Support/Format.h!
  249. #if defined(__MINGW32__)
  250. // FIXME: It should be generic to C++11.
  251. if (N == 0.0 && std::signbit(N)) {
  252. const char *NegativeZero = "-0.000000e+00";
  253. writePadding(S, Width, strlen(NegativeZero));
  254. S << NegativeZero;
  255. return;
  256. }
  257. #else
  258. int fpcl = _fpclass(N);
  259. // negative zero
  260. if (fpcl == _FPCLASS_NZ) {
  261. const char *NegativeZero = "-0.000000e+00";
  262. writePadding(S, Width, strlen(NegativeZero));
  263. S << NegativeZero;
  264. return;
  265. }
  266. #endif
  267. char buf[32];
  268. unsigned len;
  269. len = format(Spec.c_str(), N).snprint(buf, sizeof(buf));
  270. if (len <= sizeof(buf) - 2) {
  271. if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') &&
  272. buf[len - 3] == '0') {
  273. int cs = buf[len - 4];
  274. if (cs == '+' || cs == '-') {
  275. int c1 = buf[len - 2];
  276. int c0 = buf[len - 1];
  277. if (isdigit(static_cast<unsigned char>(c1)) &&
  278. isdigit(static_cast<unsigned char>(c0))) {
  279. // Trim leading '0': "...e+012" -> "...e+12\0"
  280. buf[len - 3] = c1;
  281. buf[len - 2] = c0;
  282. buf[--len] = 0;
  283. }
  284. }
  285. }
  286. writePadding(S, Width, len);
  287. S << buf;
  288. return;
  289. }
  290. #endif
  291. }
  292. if (Style == FloatStyle::Percent)
  293. N *= 100.0;
  294. char Buf[32];
  295. unsigned Len;
  296. Len = format(Spec.c_str(), N).snprint(Buf, sizeof(Buf));
  297. if (Style == FloatStyle::Percent)
  298. ++Len;
  299. writePadding(S, Width, Len);
  300. S << Buf;
  301. if (Style == FloatStyle::Percent)
  302. S << '%';
  303. }
  304. IntegerStyle llvm::hexStyleToIntHexStyle(HexStyle S) {
  305. switch (S) {
  306. case HexStyle::Upper:
  307. return IntegerStyle::HexUpperNoPrefix;
  308. case HexStyle::Lower:
  309. return IntegerStyle::HexLowerNoPrefix;
  310. case HexStyle::PrefixUpper:
  311. return IntegerStyle::HexUpperPrefix;
  312. case HexStyle::PrefixLower:
  313. return IntegerStyle::HexLowerPrefix;
  314. }
  315. LLVM_BUILTIN_UNREACHABLE;
  316. }
  317. size_t llvm::getDefaultPrecision(FloatStyle Style) {
  318. switch (Style) {
  319. case FloatStyle::Exponent:
  320. case FloatStyle::ExponentUpper:
  321. return 6; // Number of decimal places.
  322. case FloatStyle::Fixed:
  323. case FloatStyle::Percent:
  324. return 2; // Number of decimal places.
  325. }
  326. LLVM_BUILTIN_UNREACHABLE;
  327. }
  328. size_t llvm::getDefaultPrecision(IntegerStyle Style) {
  329. switch (Style) {
  330. case IntegerStyle::Exponent:
  331. case IntegerStyle::ExponentUpper:
  332. return 6; // Number of decimal places.
  333. case IntegerStyle::Number:
  334. case IntegerStyle::Integer:
  335. return 0; // Minimum number of digits required.
  336. case IntegerStyle::Fixed:
  337. return 2; // Number of decimal places.
  338. case IntegerStyle::Percent:
  339. return 0; // Number of decimal places.
  340. case IntegerStyle::HexLowerNoPrefix:
  341. case IntegerStyle::HexLowerPrefix:
  342. case IntegerStyle::HexUpperNoPrefix:
  343. case IntegerStyle::HexUpperPrefix:
  344. return getDefaultPrecision(intHexStyleToHexStyle(Style));
  345. }
  346. LLVM_BUILTIN_UNREACHABLE;
  347. }
  348. size_t llvm::getDefaultPrecision(HexStyle) {
  349. // Number of digits in the resulting string.
  350. return 0;
  351. }