raw_ostream.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. //===--- raw_ostream.h - Raw output stream ----------------------*- 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. // This file defines the raw_ostream class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
  14. #define LLVM_SUPPORT_RAW_OSTREAM_H
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Support/DataTypes.h"
  18. #include <system_error>
  19. namespace llvm {
  20. class format_object_base;
  21. class FormattedString;
  22. class FormattedNumber;
  23. template <typename T> class SmallVectorImpl;
  24. namespace sys {
  25. namespace fs {
  26. enum OpenFlags : unsigned;
  27. }
  28. }
  29. /// This class implements an extremely fast bulk output stream that can *only*
  30. /// output to a stream. It does not support seeking, reopening, rewinding, line
  31. /// buffered disciplines etc. It is a simple buffer that outputs
  32. /// a chunk at a time.
  33. class raw_ostream {
  34. private:
  35. void operator=(const raw_ostream &) = delete;
  36. raw_ostream(const raw_ostream &) = delete;
  37. /// The buffer is handled in such a way that the buffer is
  38. /// uninitialized, unbuffered, or out of space when OutBufCur >=
  39. /// OutBufEnd. Thus a single comparison suffices to determine if we
  40. /// need to take the slow path to write a single character.
  41. ///
  42. /// The buffer is in one of three states:
  43. /// 1. Unbuffered (BufferMode == Unbuffered)
  44. /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
  45. /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
  46. /// OutBufEnd - OutBufStart >= 1).
  47. ///
  48. /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
  49. /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
  50. /// managed by the subclass.
  51. ///
  52. /// If a subclass installs an external buffer using SetBuffer then it can wait
  53. /// for a \see write_impl() call to handle the data which has been put into
  54. /// this buffer.
  55. char *OutBufStart, *OutBufEnd, *OutBufCur;
  56. /// The base in which numbers will be written. default is 10. 8 and 16 are
  57. /// also possible.
  58. int writeBase; // HLSL Change
  59. enum BufferKind {
  60. Unbuffered = 0,
  61. InternalBuffer,
  62. ExternalBuffer
  63. } BufferMode;
  64. public:
  65. // color order matches ANSI escape sequence, don't change
  66. enum Colors {
  67. BLACK=0,
  68. RED,
  69. GREEN,
  70. YELLOW,
  71. BLUE,
  72. MAGENTA,
  73. CYAN,
  74. WHITE,
  75. SAVEDCOLOR
  76. };
  77. explicit raw_ostream(bool unbuffered = false)
  78. : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
  79. // Start out ready to flush.
  80. OutBufStart = OutBufEnd = OutBufCur = nullptr;
  81. writeBase = 10; // HLSL Change
  82. }
  83. virtual ~raw_ostream();
  84. /// tell - Return the current offset with the file.
  85. uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
  86. // HLSL Change Starts - needed to clean up properly
  87. virtual void close() { flush(); }
  88. virtual bool has_error() const { return false; }
  89. virtual void clear_error() { }
  90. // HLSL Change Ends
  91. //===--------------------------------------------------------------------===//
  92. // Configuration Interface
  93. //===--------------------------------------------------------------------===//
  94. /// Set the stream to be buffered, with an automatically determined buffer
  95. /// size.
  96. void SetBuffered();
  97. /// Set the stream to be buffered, using the specified buffer size.
  98. void SetBufferSize(size_t Size) {
  99. flush();
  100. SetBufferAndMode(new char[Size], Size, InternalBuffer);
  101. }
  102. size_t GetBufferSize() const {
  103. // If we're supposed to be buffered but haven't actually gotten around
  104. // to allocating the buffer yet, return the value that would be used.
  105. if (BufferMode != Unbuffered && OutBufStart == nullptr)
  106. return preferred_buffer_size();
  107. // Otherwise just return the size of the allocated buffer.
  108. return OutBufEnd - OutBufStart;
  109. }
  110. /// Set the stream to be unbuffered. When unbuffered, the stream will flush
  111. /// after every write. This routine will also flush the buffer immediately
  112. /// when the stream is being set to unbuffered.
  113. void SetUnbuffered() {
  114. flush();
  115. SetBufferAndMode(nullptr, 0, Unbuffered);
  116. }
  117. size_t GetNumBytesInBuffer() const {
  118. return OutBufCur - OutBufStart;
  119. }
  120. //===--------------------------------------------------------------------===//
  121. // Data Output Interface
  122. //===--------------------------------------------------------------------===//
  123. void flush() {
  124. if (OutBufCur != OutBufStart)
  125. flush_nonempty();
  126. }
  127. raw_ostream &operator<<(char C) {
  128. if (OutBufCur >= OutBufEnd)
  129. return write(C);
  130. *OutBufCur++ = C;
  131. return *this;
  132. }
  133. raw_ostream &operator<<(unsigned char C) {
  134. if (OutBufCur >= OutBufEnd)
  135. return write(C);
  136. *OutBufCur++ = C;
  137. return *this;
  138. }
  139. raw_ostream &operator<<(signed char C) {
  140. if (OutBufCur >= OutBufEnd)
  141. return write(C);
  142. *OutBufCur++ = C;
  143. return *this;
  144. }
  145. raw_ostream &operator<<(StringRef Str) {
  146. // Inline fast path, particularly for strings with a known length.
  147. size_t Size = Str.size();
  148. // Make sure we can use the fast path.
  149. if (Size > (size_t)(OutBufEnd - OutBufCur))
  150. return write(Str.data(), Size);
  151. if (Size) {
  152. memcpy(OutBufCur, Str.data(), Size);
  153. OutBufCur += Size;
  154. }
  155. return *this;
  156. }
  157. raw_ostream &operator<<(const char *Str) {
  158. // Inline fast path, particularly for constant strings where a sufficiently
  159. // smart compiler will simplify strlen.
  160. return this->operator<<(StringRef(Str));
  161. }
  162. raw_ostream &operator<<(const std::string &Str) {
  163. // Avoid the fast path, it would only increase code size for a marginal win.
  164. return write(Str.data(), Str.length());
  165. }
  166. raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
  167. return write(Str.data(), Str.size());
  168. }
  169. raw_ostream &operator<<(unsigned long N);
  170. raw_ostream &operator<<(long N);
  171. raw_ostream &operator<<(unsigned long long N);
  172. raw_ostream &operator<<(long long N);
  173. raw_ostream &operator<<(const void *P);
  174. raw_ostream &operator<<(unsigned int N) {
  175. return this->operator<<(static_cast<unsigned long>(N));
  176. }
  177. raw_ostream &operator<<(int N) {
  178. return this->operator<<(static_cast<long>(N));
  179. }
  180. raw_ostream &operator<<(double N);
  181. /// Output \p N in hexadecimal, without any prefix or padding.
  182. raw_ostream &write_hex(unsigned long long N);
  183. /// Output \p N in writeBase, without any prefix or padding.
  184. raw_ostream &write_base(unsigned long long N); // HLSL Change
  185. /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
  186. /// satisfy std::isprint into an escape sequence.
  187. raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
  188. raw_ostream &write(unsigned char C);
  189. raw_ostream &write(const char *Ptr, size_t Size);
  190. // Formatted output, see the format() function in Support/Format.h.
  191. raw_ostream &operator<<(const format_object_base &Fmt);
  192. // Formatted output, see the leftJustify() function in Support/Format.h.
  193. raw_ostream &operator<<(const FormattedString &);
  194. // Formatted output, see the formatHex() function in Support/Format.h.
  195. raw_ostream &operator<<(const FormattedNumber &);
  196. raw_ostream &
  197. operator<<(std::ios_base &(__cdecl*iomanip)(std::ios_base &)); // HLSL Change
  198. /// indent - Insert 'NumSpaces' spaces.
  199. raw_ostream &indent(unsigned NumSpaces);
  200. /// Changes the foreground color of text that will be output from this point
  201. /// forward.
  202. /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
  203. /// change only the bold attribute, and keep colors untouched
  204. /// @param Bold bold/brighter text, default false
  205. /// @param BG if true change the background, default: change foreground
  206. /// @returns itself so it can be used within << invocations
  207. virtual raw_ostream &changeColor(enum Colors Color,
  208. bool Bold = false,
  209. bool BG = false) {
  210. (void)Color;
  211. (void)Bold;
  212. (void)BG;
  213. return *this;
  214. }
  215. /// Resets the colors to terminal defaults. Call this when you are done
  216. /// outputting colored text, or before program exit.
  217. virtual raw_ostream &resetColor() { return *this; }
  218. /// Reverses the forground and background colors.
  219. virtual raw_ostream &reverseColor() { return *this; }
  220. /// This function determines if this stream is connected to a "tty" or
  221. /// "console" window. That is, the output would be displayed to the user
  222. /// rather than being put on a pipe or stored in a file.
  223. virtual bool is_displayed() const { return false; }
  224. /// This function determines if this stream is displayed and supports colors.
  225. virtual bool has_colors() const { return is_displayed(); }
  226. //===--------------------------------------------------------------------===//
  227. // Subclass Interface
  228. //===--------------------------------------------------------------------===//
  229. private:
  230. /// The is the piece of the class that is implemented by subclasses. This
  231. /// writes the \p Size bytes starting at
  232. /// \p Ptr to the underlying stream.
  233. ///
  234. /// This function is guaranteed to only be called at a point at which it is
  235. /// safe for the subclass to install a new buffer via SetBuffer.
  236. ///
  237. /// \param Ptr The start of the data to be written. For buffered streams this
  238. /// is guaranteed to be the start of the buffer.
  239. ///
  240. /// \param Size The number of bytes to be written.
  241. ///
  242. /// \invariant { Size > 0 }
  243. virtual void write_impl(const char *Ptr, size_t Size) = 0;
  244. // An out of line virtual method to provide a home for the class vtable.
  245. virtual void handle();
  246. /// Return the current position within the stream, not counting the bytes
  247. /// currently in the buffer.
  248. virtual uint64_t current_pos() const = 0;
  249. protected:
  250. /// Use the provided buffer as the raw_ostream buffer. This is intended for
  251. /// use only by subclasses which can arrange for the output to go directly
  252. /// into the desired output buffer, instead of being copied on each flush.
  253. void SetBuffer(_Out_opt_ char *BufferStart, size_t Size) { // HLSL Change - SAL
  254. SetBufferAndMode(BufferStart, Size, ExternalBuffer);
  255. }
  256. /// Return an efficient buffer size for the underlying output mechanism.
  257. virtual size_t preferred_buffer_size() const;
  258. /// Return the beginning of the current stream buffer, or 0 if the stream is
  259. /// unbuffered.
  260. const char *getBufferStart() const { return OutBufStart; }
  261. //===--------------------------------------------------------------------===//
  262. // Private Interface
  263. //===--------------------------------------------------------------------===//
  264. private:
  265. /// Install the given buffer and mode.
  266. void SetBufferAndMode(_Out_opt_ char *BufferStart, size_t Size, BufferKind Mode); // HLSL Change - SAL
  267. /// Flush the current buffer, which is known to be non-empty. This outputs the
  268. /// currently buffered data and resets the buffer to empty.
  269. void flush_nonempty();
  270. /// Copy data into the buffer. Size must not be greater than the number of
  271. /// unused bytes in the buffer.
  272. void copy_to_buffer(const char *Ptr, size_t Size);
  273. };
  274. /// An abstract base class for streams implementations that also support a
  275. /// pwrite operation. This is usefull for code that can mostly stream out data,
  276. /// but needs to patch in a header that needs to know the output size.
  277. class raw_pwrite_stream : public raw_ostream {
  278. virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
  279. public:
  280. explicit raw_pwrite_stream(bool Unbuffered = false)
  281. : raw_ostream(Unbuffered) {}
  282. void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
  283. #ifndef NDBEBUG
  284. uint64_t Pos = tell();
  285. // /dev/null always reports a pos of 0, so we cannot perform this check
  286. // in that case.
  287. if (Pos)
  288. assert(Size + Offset <= Pos && "We don't support extending the stream");
  289. #endif
  290. pwrite_impl(Ptr, Size, Offset);
  291. }
  292. };
  293. //===----------------------------------------------------------------------===//
  294. // File Output Streams
  295. //===----------------------------------------------------------------------===//
  296. /// A raw_ostream that writes to a file descriptor.
  297. ///
  298. class raw_fd_ostream : public raw_pwrite_stream {
  299. int FD;
  300. bool ShouldClose;
  301. /// Error This flag is true if an error of any kind has been detected.
  302. ///
  303. bool Error;
  304. /// Controls whether the stream should attempt to use atomic writes, when
  305. /// possible.
  306. bool UseAtomicWrites;
  307. uint64_t pos;
  308. bool SupportsSeeking;
  309. /// See raw_ostream::write_impl.
  310. void write_impl(const char *Ptr, size_t Size) override;
  311. void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
  312. /// Return the current position within the stream, not counting the bytes
  313. /// currently in the buffer.
  314. uint64_t current_pos() const override { return pos; }
  315. /// Determine an efficient buffer size.
  316. size_t preferred_buffer_size() const override;
  317. /// Set the flag indicating that an output error has been encountered.
  318. void error_detected() { Error = true; }
  319. public:
  320. /// Open the specified file for writing. If an error occurs, information
  321. /// about the error is put into EC, and the stream should be immediately
  322. /// destroyed;
  323. /// \p Flags allows optional flags to control how the file will be opened.
  324. ///
  325. /// As a special case, if Filename is "-", then the stream will use
  326. /// STDOUT_FILENO instead of opening a file. Note that it will still consider
  327. /// itself to own the file descriptor. In particular, it will close the
  328. /// file descriptor when it is done (this is necessary to detect
  329. /// output errors).
  330. raw_fd_ostream(StringRef Filename, std::error_code &EC,
  331. sys::fs::OpenFlags Flags);
  332. /// FD is the file descriptor that this writes to. If ShouldClose is true,
  333. /// this closes the file when the stream is destroyed.
  334. raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
  335. ~raw_fd_ostream() override;
  336. /// Manually flush the stream and close the file. Note that this does not call
  337. /// fsync.
  338. void close() override;
  339. bool supportsSeeking() { return SupportsSeeking; }
  340. /// Flushes the stream and repositions the underlying file descriptor position
  341. /// to the offset specified from the beginning of the file.
  342. uint64_t seek(uint64_t off);
  343. /// Set the stream to attempt to use atomic writes for individual output
  344. /// routines where possible.
  345. ///
  346. /// Note that because raw_ostream's are typically buffered, this flag is only
  347. /// sensible when used on unbuffered streams which will flush their output
  348. /// immediately.
  349. void SetUseAtomicWrites(bool Value) {
  350. UseAtomicWrites = Value;
  351. }
  352. raw_ostream &changeColor(enum Colors colors, bool bold=false,
  353. bool bg=false) override;
  354. raw_ostream &resetColor() override;
  355. raw_ostream &reverseColor() override;
  356. bool is_displayed() const override;
  357. bool has_colors() const override;
  358. /// Return the value of the flag in this raw_fd_ostream indicating whether an
  359. /// output error has been encountered.
  360. /// This doesn't implicitly flush any pending output. Also, it doesn't
  361. /// guarantee to detect all errors unless the stream has been closed.
  362. bool has_error() const override {
  363. return Error;
  364. }
  365. /// Set the flag read by has_error() to false. If the error flag is set at the
  366. /// time when this raw_ostream's destructor is called, report_fatal_error is
  367. /// called to report the error. Use clear_error() after handling the error to
  368. /// avoid this behavior.
  369. ///
  370. /// "Errors should never pass silently.
  371. /// Unless explicitly silenced."
  372. /// - from The Zen of Python, by Tim Peters
  373. ///
  374. void clear_error() override {
  375. Error = false;
  376. }
  377. };
  378. /// This returns a reference to a raw_ostream for standard output. Use it like:
  379. /// outs() << "foo" << "bar";
  380. raw_ostream &outs();
  381. /// This returns a reference to a raw_ostream for standard error. Use it like:
  382. /// errs() << "foo" << "bar";
  383. raw_ostream &errs();
  384. /// This returns a reference to a raw_ostream which simply discards output.
  385. raw_ostream &nulls();
  386. // HLSL Change Starts
  387. // Flush and close STDOUT/STDERR streams before MSFileSystem goes down,
  388. // otherwise static destructors will attempt to close after we no longer
  389. // have a file system, which will raise an exception on static shutdown.
  390. // This is a temporary work around until outs() and errs() is fixed to
  391. // do the right thing.
  392. // The usage pattern is to create an instance in main() after a console-based
  393. // MSFileSystem has been installed.
  394. class STDStreamCloser
  395. {
  396. public:
  397. ~STDStreamCloser()
  398. {
  399. llvm::raw_fd_ostream& fo = static_cast<llvm::raw_fd_ostream&>(llvm::outs());
  400. llvm::raw_fd_ostream& fe = static_cast<llvm::raw_fd_ostream&>(llvm::errs());
  401. fo.flush();
  402. fe.flush();
  403. fo.close();
  404. // do not close fe (STDERR), since it was initialized with ShouldClose to false.
  405. // (see errs() definition).
  406. }
  407. };
  408. // HLSL Change Ends
  409. //===----------------------------------------------------------------------===//
  410. // Output Stream Adaptors
  411. // //
  412. ///////////////////////////////////////////////////////////////////////////////
  413. /// A raw_ostream that writes to an std::string. This is a simple adaptor
  414. /// class. This class does not encounter output errors.
  415. class raw_string_ostream : public raw_ostream {
  416. std::string &OS;
  417. /// See raw_ostream::write_impl.
  418. void write_impl(const char *Ptr, size_t Size) override;
  419. /// Return the current position within the stream, not counting the bytes
  420. /// currently in the buffer.
  421. uint64_t current_pos() const override { return OS.size(); }
  422. public:
  423. explicit raw_string_ostream(std::string &O) : OS(O) {}
  424. ~raw_string_ostream() override;
  425. /// Flushes the stream contents to the target string and returns the string's
  426. /// reference.
  427. std::string& str() {
  428. flush();
  429. return OS;
  430. }
  431. };
  432. /// A raw_ostream that writes to an SmallVector or SmallString. This is a
  433. /// simple adaptor class. This class does not encounter output errors.
  434. class raw_svector_ostream : public raw_pwrite_stream {
  435. SmallVectorImpl<char> &OS;
  436. /// See raw_ostream::write_impl.
  437. void write_impl(const char *Ptr, size_t Size) override;
  438. void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
  439. /// Return the current position within the stream, not counting the bytes
  440. /// currently in the buffer.
  441. uint64_t current_pos() const override;
  442. protected:
  443. // Like the regular constructor, but doesn't call init.
  444. explicit raw_svector_ostream(SmallVectorImpl<char> &O, unsigned);
  445. void init();
  446. public:
  447. /// Construct a new raw_svector_ostream.
  448. ///
  449. /// \param O The vector to write to; this should generally have at least 128
  450. /// bytes free to avoid any extraneous memory overhead.
  451. explicit raw_svector_ostream(SmallVectorImpl<char> &O);
  452. ~raw_svector_ostream() override;
  453. /// This is called when the SmallVector we're appending to is changed outside
  454. /// of the raw_svector_ostream's control. It is only safe to do this if the
  455. /// raw_svector_ostream has previously been flushed.
  456. void resync();
  457. /// Flushes the stream contents to the target vector and return a StringRef
  458. /// for the vector contents.
  459. StringRef str();
  460. };
  461. /// A raw_ostream that discards all output.
  462. class raw_null_ostream : public raw_pwrite_stream {
  463. /// See raw_ostream::write_impl.
  464. void write_impl(const char *Ptr, size_t size) override;
  465. void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
  466. /// Return the current position within the stream, not counting the bytes
  467. /// currently in the buffer.
  468. uint64_t current_pos() const override;
  469. public:
  470. explicit raw_null_ostream() {}
  471. ~raw_null_ostream() override;
  472. };
  473. class buffer_ostream : public raw_svector_ostream {
  474. raw_ostream &OS;
  475. SmallVector<char, 0> Buffer;
  476. public:
  477. buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer, 0), OS(OS) {
  478. init();
  479. }
  480. ~buffer_ostream() { OS << str(); }
  481. };
  482. } // end llvm namespace
  483. #endif