[lldb] Nits on uses of llvm::raw_string_ostream (NFC) (#108745)

As specified in the docs,
1) raw_string_ostream is always unbuffered and
2) the underlying buffer may be used directly

( 65b13610a5 for further reference )

* Don't call raw_string_ostream::flush(), which is essentially a no-op.
* Avoid unneeded calls to raw_string_ostream::str(), to avoid excess
indirection.
This commit is contained in:
Youngsuk Kim
2024-09-16 00:26:51 -04:00
committed by GitHub
parent 4fdccd346b
commit d7796855b8
37 changed files with 35 additions and 69 deletions

View File

@@ -70,7 +70,7 @@ template <typename... Ts> inline std::string stringify_args(const Ts &...ts) {
std::string buffer;
llvm::raw_string_ostream ss(buffer);
stringify_helper(ss, ts...);
return ss.str();
return buffer;
}
/// RAII object for instrumenting LLDB API functions.

View File

@@ -1127,7 +1127,7 @@ json::Value Breakpoint::GetStatistics() {
llvm::raw_string_ostream ss(buffer);
json::OStream json_os(ss);
bp_data_sp->Serialize(json_os);
if (auto expected_value = llvm::json::parse(ss.str())) {
if (auto expected_value = llvm::json::parse(buffer)) {
bp.try_emplace("details", std::move(*expected_value));
} else {
std::string details_error = toString(expected_value.takeError());

View File

@@ -204,7 +204,7 @@ protected:
channel, args.GetArgumentArrayRef(), log_file, m_options.log_options,
m_options.buffer_size.GetCurrentValue(), m_options.handler,
error_stream);
result.GetErrorStream() << error_stream.str();
result.GetErrorStream() << error;
if (success)
result.SetStatus(eReturnStatusSuccessFinishNoResult);
@@ -273,7 +273,7 @@ protected:
if (Log::DisableLogChannel(channel, args.GetArgumentArrayRef(),
error_stream))
result.SetStatus(eReturnStatusSuccessFinishNoResult);
result.GetErrorStream() << error_stream.str();
result.GetErrorStream() << error;
}
}
};
@@ -313,7 +313,7 @@ protected:
if (success)
result.SetStatus(eReturnStatusSuccessFinishResult);
}
result.GetOutputStream() << output_stream.str();
result.GetOutputStream() << output;
}
};
class CommandObjectLogDump : public CommandObjectParsed {
@@ -404,7 +404,7 @@ protected:
result.SetStatus(eReturnStatusSuccessFinishNoResult);
} else {
result.SetStatus(eReturnStatusFailed);
result.GetErrorStream() << error_stream.str();
result.GetErrorStream() << error;
}
}

View File

@@ -51,7 +51,7 @@ llvm::Expected<std::string> CommandObjectRegexCommand::SubstituteVariables(
output << part;
}
return output.str();
return buffer;
}
void CommandObjectRegexCommand::DoExecute(llvm::StringRef command,

View File

@@ -1626,7 +1626,7 @@ uint32_t Module::Hash() {
const auto mtime = llvm::sys::toTimeT(m_object_mod_time);
if (mtime > 0)
id_strm << mtime;
return llvm::djbHash(id_strm.str());
return llvm::djbHash(identifier);
}
std::string Module::GetCacheKey() {
@@ -1636,7 +1636,7 @@ std::string Module::GetCacheKey() {
if (m_object_name)
strm << '(' << m_object_name << ')';
strm << '-' << llvm::format_hex(Hash(), 10);
return strm.str();
return key;
}
DataFileCache *Module::GetIndexCache() {

View File

@@ -261,8 +261,6 @@ void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
m_module->print(oss, nullptr);
oss.flush();
LLDB_LOGF(log, "Module being sent to JIT: \n%s", s.c_str());
}

View File

@@ -49,7 +49,6 @@ static std::string PrintValue(const Value *value, bool truncate = false) {
std::string s;
raw_string_ostream rso(s);
value->print(rso);
rso.flush();
if (truncate)
s.resize(s.length() - 1);
@@ -66,7 +65,6 @@ static std::string PrintType(const Type *type, bool truncate = false) {
std::string s;
raw_string_ostream rso(s);
type->print(rso);
rso.flush();
if (truncate)
s.resize(s.length() - 1);
return s;
@@ -698,8 +696,6 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
module.print(oss, nullptr);
oss.flush();
LLDB_LOGF(log, "Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
s.c_str());
}

View File

@@ -74,7 +74,6 @@ Status PipeWindows::CreateNew(bool child_process_inherit) {
std::string pipe_name;
llvm::raw_string_ostream pipe_name_stream(pipe_name);
pipe_name_stream << "lldb.pipe." << ::GetCurrentProcessId() << "." << serial;
pipe_name_stream.flush();
return CreateNew(pipe_name.c_str(), child_process_inherit);
}

View File

@@ -923,7 +923,7 @@ static std::string BuildShortOptions(const Option *long_options) {
}
}
}
return std::move(sstr.str());
return storage;
}
llvm::Expected<Args> Options::ParseAlias(const Args &args,

View File

@@ -1366,8 +1366,6 @@ void DisassemblerLLVMC::MCDisasmInstance::PrintMCInst(
*m_subtarget_info_up, inst_stream);
m_instr_printer_up->setCommentStream(llvm::nulls());
comments_stream.flush();
static std::string g_newlines("\r\n");
for (size_t newline_pos = 0;

View File

@@ -984,7 +984,6 @@ private:
ToInsert += "(";
raw_string_ostream OS(Description);
F->print(OS, m_desc_policy, false);
OS.flush();
} else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Description = V->getType().getAsString(m_desc_policy);
} else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
@@ -1358,7 +1357,6 @@ bool ClangExpressionParser::RewriteExpression(
llvm::raw_string_ostream out_stream(fixed_expression);
main_file_buffer.write(out_stream);
out_stream.flush();
diagnostic_manager.SetFixedExpression(fixed_expression);
return true;

View File

@@ -147,7 +147,6 @@ void StoringDiagnosticConsumer::HandleDiagnostic(
// Print the diagnostic to m_output.
m_output.clear();
m_diag_printer->HandleDiagnostic(DiagLevel, info);
m_os->flush();
// Store the diagnostic for later.
m_diagnostics.push_back(IDAndDiagnostic(DiagLevel, m_output));

View File

@@ -94,7 +94,6 @@ static std::string PrintValue(llvm::Value *V, bool truncate = false) {
std::string s;
raw_string_ostream rso(s);
V->print(rso);
rso.flush();
if (truncate)
s.resize(s.length() - 1);
return s;
@@ -553,8 +552,6 @@ bool IRDynamicChecks::runOnModule(llvm::Module &M) {
M.print(oss, nullptr);
oss.flush();
LLDB_LOGF(log, "Module after dynamic checks: \n%s", s.c_str());
}

View File

@@ -86,7 +86,6 @@ static std::string PrintValue(const Value *value, bool truncate = false) {
if (value) {
raw_string_ostream rso(s);
value->print(rso);
rso.flush();
if (truncate)
s.resize(s.length() - 1);
}
@@ -97,7 +96,6 @@ static std::string PrintType(const llvm::Type *type, bool truncate = false) {
std::string s;
raw_string_ostream rso(s);
type->print(rso);
rso.flush();
if (truncate)
s.resize(s.length() - 1);
return s;
@@ -244,7 +242,6 @@ bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
std::string decl_desc_str;
raw_string_ostream decl_desc_stream(decl_desc_str);
result_decl->print(decl_desc_stream);
decl_desc_stream.flush();
LLDB_LOG(log, "Found result decl: \"{0}\"", decl_desc_str);
}
@@ -1616,8 +1613,6 @@ bool IRForTarget::runOnModule(Module &llvm_module) {
m_module->print(oss, nullptr);
oss.flush();
LLDB_LOG(log, "Module as passed in to IRForTarget: \n\"{0}\"", s);
}
@@ -1663,8 +1658,6 @@ bool IRForTarget::runOnModule(Module &llvm_module) {
m_module->print(oss, nullptr);
oss.flush();
LLDB_LOG(log, "Module after creating the result variable: \n\"{0}\"", s);
}
@@ -1762,8 +1755,6 @@ bool IRForTarget::runOnModule(Module &llvm_module) {
m_module->print(oss, nullptr);
oss.flush();
LLDB_LOG(log, "Module after preparing for execution: \n\"{0}\"", s);
}

View File

@@ -2685,7 +2685,7 @@ void AppleObjCRuntimeV2::WarnIfNoExpandedSharedCache() {
}
os << ". This will likely reduce debugging performance.\n";
Debugger::ReportWarning(os.str(), debugger.GetID(),
Debugger::ReportWarning(buffer, debugger.GetID(),
&m_no_expanded_cache_warning);
}

View File

@@ -548,7 +548,7 @@ NativeProcessWindows::OnDebugException(bool first_chance,
<< " encountered at address "
<< llvm::format_hex(record.GetExceptionAddress(), 8);
StopThread(record.GetThreadID(), StopReason::eStopReasonException,
desc_stream.str().c_str());
desc.c_str());
SetState(eStateStopped, true);
}

View File

@@ -492,10 +492,10 @@ void ProcessWindows::RefreshStateAfterStop() {
<< llvm::format_hex(active_exception->GetExceptionAddress(), 8);
DumpAdditionalExceptionInformation(desc_stream, active_exception);
stop_info = StopInfo::CreateStopReasonWithException(
*stop_thread, desc_stream.str().c_str());
stop_info =
StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
stop_thread->SetStopInfo(stop_info);
LLDB_LOG(log, "{0}", desc_stream.str());
LLDB_LOG(log, "{0}", desc);
return;
}
}

View File

@@ -3668,7 +3668,6 @@ GDBRemoteCommunicationClient::SendTraceStop(const TraceStopRequest &request,
std::string json_string;
llvm::raw_string_ostream os(json_string);
os << toJSON(request);
os.flush();
escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
@@ -3738,7 +3737,6 @@ GDBRemoteCommunicationClient::SendTraceGetState(llvm::StringRef type,
std::string json_string;
llvm::raw_string_ostream os(json_string);
os << toJSON(TraceGetStateRequest{type.str()});
os.flush();
escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
@@ -3772,7 +3770,6 @@ GDBRemoteCommunicationClient::SendTraceGetBinaryData(
std::string json_string;
llvm::raw_string_ostream os(json_string);
os << toJSON(request);
os.flush();
escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size());
@@ -4045,7 +4042,7 @@ GDBRemoteCommunicationClient::ReadExtFeature(llvm::StringRef object,
}
}
return output_stream.str();
return output;
}
// Notify the target that gdb is prepared to serve symbol lookup requests.

View File

@@ -5360,7 +5360,7 @@ std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
output_stream << end_delimiter;
m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
return output_stream.str();
return output;
}
void ProcessGDBRemote::HandleStopReply() {

View File

@@ -289,8 +289,8 @@ void ProcessMinidump::RefreshStateAfterStop() {
<< " encountered at address "
<< llvm::format_hex(
exception_stream.ExceptionRecord.ExceptionAddress, 8);
stop_info = StopInfo::CreateStopReasonWithException(
*stop_thread, desc_stream.str().c_str());
stop_info =
StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
}
stop_thread->SetStopInfo(stop_info);

View File

@@ -501,5 +501,5 @@ void DebugNamesDWARFIndex::Dump(Stream &s) {
std::string data;
llvm::raw_string_ostream os(data);
m_debug_names_up->dump(os);
s.PutCString(os.str());
s.PutCString(data);
}

View File

@@ -697,7 +697,7 @@ std::string ManualDWARFIndex::GetCacheKey() {
ObjectFile *objfile = m_dwarf->GetObjectFile();
strm << objfile->GetModule()->GetCacheKey() << "-dwarf-index-"
<< llvm::format_hex(objfile->GetCacheHash(), 10);
return strm.str();
return key;
}
bool ManualDWARFIndex::LoadFromCache() {

View File

@@ -72,7 +72,7 @@ Error TraceIntelPTBundleLoader::CreateJSONError(json::Path::Root &root,
root.printErrorContext(value, os);
return createStringError(
std::errc::invalid_argument, "%s\n\nContext:\n%s\n\nSchema:\n%s",
toString(root.getError()).c_str(), os.str().c_str(), GetSchema().data());
toString(root.getError()).c_str(), err.c_str(), GetSchema().data());
}
ThreadPostMortemTraceSP

View File

@@ -1179,7 +1179,7 @@ std::string Symtab::GetCacheKey() {
// another object file in a separate symbol file.
strm << m_objfile->GetModule()->GetCacheKey() << "-symtab-"
<< llvm::format_hex(m_objfile->GetCacheHash(), 10);
return strm.str();
return key;
}
void Symtab::SaveToCache() {

View File

@@ -414,7 +414,7 @@ llvm::json::Value DebuggerStats::ReportStatistics(
llvm::raw_string_ostream ss(buffer);
json::OStream json_os(ss);
transcript.Serialize(json_os);
if (auto json_transcript = llvm::json::parse(ss.str()))
if (auto json_transcript = llvm::json::parse(buffer))
global_stats.try_emplace("transcript",
std::move(json_transcript.get()));
}

View File

@@ -4603,7 +4603,7 @@ void TargetProperties::CheckJITObjectsDir() {
std::optional<lldb::user_id_t> debugger_id;
if (m_target)
debugger_id = m_target->GetDebugger().GetID();
Debugger::ReportError(os.str(), debugger_id);
Debugger::ReportError(buffer, debugger_id);
}
bool TargetProperties::GetEnableSyntheticValue() const {

View File

@@ -54,7 +54,7 @@ void lldb_assert(bool expression, const char *expr_text, const char *func,
llvm::formatv("Assertion failed: ({0}), function {1}, file {2}, line {3}",
expr_text, func, file, line)
.str(),
backtrace.str(),
buffer,
"Please file a bug report against lldb reporting this failure log, and "
"as many details as possible");
}

View File

@@ -374,7 +374,7 @@ void Log::Format(llvm::StringRef file, llvm::StringRef function,
llvm::raw_string_ostream message(message_string);
WriteHeader(message, file, function);
message << payload << "\n";
WriteMessage(message.str());
WriteMessage(message_string);
}
StreamLogHandler::StreamLogHandler(int fd, bool should_close,

View File

@@ -184,12 +184,11 @@ void DAP::SendJSON(const std::string &json_str) {
// Serialize the JSON value into a string and send the JSON packet to
// the "out" stream.
void DAP::SendJSON(const llvm::json::Value &json) {
std::string s;
llvm::raw_string_ostream strm(s);
std::string json_str;
llvm::raw_string_ostream strm(json_str);
strm << json;
static std::mutex mutex;
std::lock_guard<std::mutex> locker(mutex);
std::string json_str = strm.str();
SendJSON(json_str);
if (log) {
@@ -660,7 +659,6 @@ PacketStatus DAP::GetNextObject(llvm::json::Object &object) {
std::string error_str;
llvm::raw_string_ostream strm(error_str);
strm << error;
strm.flush();
*log << "error: failed to parse JSON: " << error_str << std::endl
<< json << std::endl;
}

View File

@@ -1480,7 +1480,6 @@ std::string JSONToString(const llvm::json::Value &json) {
std::string data;
llvm::raw_string_ostream os(data);
os << json;
os.flush();
return data;
}

View File

@@ -84,7 +84,6 @@ std::string RunLLDBCommands(llvm::StringRef prefix,
llvm::raw_string_ostream strm(s);
required_command_failed =
!RunLLDBCommands(prefix, commands, strm, parse_command_directives);
strm.flush();
return s;
}

View File

@@ -635,7 +635,6 @@ void SetSourceMapFromArguments(const llvm::json::Object &arguments) {
// Do any source remapping needed before we create our targets
strm << "\".\" \"" << sourcePath << "\"";
}
strm.flush();
if (!sourceMapCommand.empty()) {
g_dap.RunLLDBCommands("Setting source map:", {sourceMapCommand});
}
@@ -4127,7 +4126,6 @@ void request_disassemble(const llvm::json::Object &request) {
sb << llvm::format("%2.2x ", b);
}
}
sb.flush();
llvm::json::Object disassembled_inst{
{"address", "0x" + llvm::utohexstr(inst_addr)},
@@ -4158,7 +4156,6 @@ void request_disassemble(const llvm::json::Object &request) {
if (c && c[0]) {
si << " ; " << c;
}
si.flush();
disassembled_inst.try_emplace("instruction", instruction);

View File

@@ -59,13 +59,13 @@ public:
if (C->getBeginLoc().isMacroID()) {
CharSourceRange Range =
MyRewriter.getSourceMgr().getExpansionRange(C->getSourceRange());
MyRewriter.ReplaceText(Range, Macro.str());
MyRewriter.ReplaceText(Range, Buffer);
} else {
Macro << ";";
SourceLocation InsertLoc = Lexer::getLocForEndOfToken(
Body->getBeginLoc(), 0, MyRewriter.getSourceMgr(),
MyRewriter.getLangOpts());
MyRewriter.InsertTextAfter(InsertLoc, Macro.str());
MyRewriter.InsertTextAfter(InsertLoc, Buffer);
}
break;
}

View File

@@ -73,7 +73,7 @@ bool LLDBServerUtilities::SetupLogging(const std::string &log_file,
channel_then_categories.GetArgumentArrayRef(), error_stream);
if (!success) {
errs() << formatv("Unable to setup logging for channel \"{0}\": {1}",
channel, error_stream.str());
channel, error);
return false;
}
}

View File

@@ -414,7 +414,7 @@ std::string opts::breakpoint::substitute(StringRef Cmd) {
break;
}
}
return std::move(OS.str());
return Result;
}
int opts::breakpoint::evaluateBreakpoints(Debugger &Dbg) {

View File

@@ -161,7 +161,7 @@ static std::string ParseAndGenerateDWARF(llvm::StringRef expr) {
llvm::raw_string_ostream os(result);
llvm::DWARFExpression(extractor, addr_size, llvm::dwarf::DWARF32)
.print(os, llvm::DIDumpOptions(), nullptr);
return std::move(os.str());
return result;
}
TEST(PostfixExpression, ToDWARF) {

View File

@@ -43,7 +43,7 @@ CheckValidProgramTranslation(llvm::StringRef fpo_program,
.print(os, llvm::DIDumpOptions(), nullptr);
// actual check
ASSERT_EQ(expected_dwarf_expression, os.str());
ASSERT_EQ(expected_dwarf_expression, result);
}
TEST(PDBFPOProgramToDWARFExpressionTests, SingleAssignmentRegisterRef) {