Creating raw_ostream object in LLVM
Asked Answered
A

1

7

What is the correct way to create a raw_ostream object and use it for printing? I read various articles and the only example I can find is (How to redirect llvm::outs() to file?)

raw_ostream *output = &outs();

which made use of llvm::outs.

Sorry for asking this because I am not too familiar with C++ but had to understand how LLVM works.

Arnone answered 25/11, 2020 at 7:40 Comment(0)
E
19

llvm::raw_ostream is an abstract class with two important pure virtual functions implemented by subclasses; write_impl() which holds the logic for writing data to the underlying stream and current_pos() which returns the position currently being written to in the stream.

LLVM provides the following output stream implementations:

  • outs() for writing to stdout
  • errs() for writing to stderr
  • nulls() which discards the output (like writing to /dev/null)
  • raw_fd_ostream(StringRef, std::error_code) for writing to a file descriptor
  • raw_string_ostream(std::string) for writing to a std::string
  • raw_os_ostream(std::ostream &) for writing to a std::ostream

The first 3 streams directly return a reference to their stream objects. For example:

llvm::raw_ostream &output = llvm::outs();

For the other streams, you construct objects the old way. For example:

std::string str;
llvm::raw_string_ostream output(str);

For printing, every llvm::Value* has a print method that accepts a raw_ostream object.

Expectorate answered 25/11, 2020 at 22:39 Comment(4)
Hi, I have a question, How does one set create a raw_ostream object for a file, in order to make the llvm:Value* print function print it to a file?Adduce
@SupriyaBhide You could create an output stream that writes to a file based on raw_fd_ostream and pass this output stream object to the print() member function of the Value class. See here for more information on the member functions of the Value class: llvm.org/doxygen/classllvm_1_1Value.htmlCuffs
More recent versions of llvm also support raw_os_ostream to output to a std::ostreamEpilepsy
@ChrisDodd could you please edit the answer? Thanks.Expectorate

© 2022 - 2024 — McMap. All rights reserved.