raw_ostream.h 19 KB

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