llvm.org GIT mirror llvm / 2559070
Introduce a string_ostream string builder facilty string_ostream is a safe and efficient string builder that combines opaque stack storage with a built-in ostream interface. small_string_ostream<bytes> additionally permits an explicit stack storage size other than the default 128 bytes to be provided. Beyond that, storage is transferred to the heap. This convenient class can be used in most places an std::string+raw_string_ostream pair or SmallString<>+raw_svector_ostream pair would previously have been used, in order to guarantee consistent access without byte truncation. The patch also converts much of LLVM to use the new facility. These changes include several probable bug fixes for truncated output, a programming error that's no longer possible with the new interface. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@211749 91177308-0d34-0410-b5e6-96231b3b80d8 Alp Toker 5 years ago
57 changed file(s) with 225 addition(s) and 288 deletion(s). Raw diff Collapse all Expand all
3535 if (!Node->getName().empty())
3636 return Node->getName().str();
3737
38 std::string Str;
39 raw_string_ostream OS(Str);
40
38 string_ostream OS;
4139 Node->printAsOperand(OS, false);
4240 return OS.str();
4341 }
4543 static std::string getCompleteNodeLabel(const BasicBlock *Node,
4644 const Function *) {
4745 enum { MaxColumns = 80 };
48 std::string Str;
49 raw_string_ostream OS(Str);
46 string_ostream OS;
5047
5148 if (Node->getName().empty()) {
5249 Node->printAsOperand(OS, false);
108105
109106 if (SuccNo == 0) return "def";
110107
111 std::string Str;
112 raw_string_ostream OS(Str);
108 string_ostream OS;
113109 SwitchInst::ConstCaseIt Case =
114110 SwitchInst::ConstCaseIt::fromSuccessorIndex(SI, SuccNo);
115111 OS << Case.getCaseValue()->getValue();
5757 class ObjectBufferStream : public ObjectBuffer {
5858 void anchor() override;
5959 public:
60 ObjectBufferStream() : OS(SV) {}
60 ObjectBufferStream() {}
6161 virtual ~ObjectBufferStream() {}
6262
6363 raw_ostream &getOStream() { return OS; }
6464 void flush()
6565 {
66 OS.flush();
67
6866 // Make the data accessible via the ObjectBuffer::Buffer
69 Buffer.reset(MemoryBuffer::getMemBuffer(StringRef(SV.data(), SV.size()),
70 "",
71 false));
67 Buffer.reset(MemoryBuffer::getMemBuffer(OS.str(), "", false));
7268 }
7369
7470 protected:
75 SmallVector SV; // Working buffer into which we JIT.
76 raw_svector_ostream OS; // streaming wrapper
71 small_string_ostream<4096> OS; // Working buffer into which we JIT.
7772 };
7873
7974 } // namespace llvm
183183 O << "|" << DOT::EscapeString(NodeDesc);
184184 }
185185
186 std::string edgeSourceLabels;
187 raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
186 string_ostream EdgeSourceLabels;
188187 bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
189188
190189 if (hasEdgeSourceLabels) {
611611 typename std::enable_if::value,void>::type
612612 yamlize(IO &io, T &Val, bool) {
613613 if ( io.outputting() ) {
614 std::string Storage;
615 llvm::raw_string_ostream Buffer(Storage);
614 llvm::string_ostream Buffer;
616615 ScalarTraits::output(Val, io.getContext(), Buffer);
617616 StringRef Str = Buffer.str();
618617 io.scalarString(Str, ScalarTraits::mustQuote(Str));
1414 #define LLVM_SUPPORT_RAW_OSTREAM_H
1515
1616 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/SmallVector.h"
1718 #include "llvm/Support/Compiler.h"
1819 #include "llvm/Support/DataTypes.h"
1920
460461 /// current_pos - Return the current position within the stream, not
461462 /// counting the bytes currently in the buffer.
462463 uint64_t current_pos() const override;
464
465 protected:
466 // This constructor is specified not to access \p O provided for storage as it
467 // may not yet be initialized at construction time.
468 explicit raw_svector_ostream(SmallVectorImpl &O, std::nullptr_t)
469 : OS(O){};
470 void init();
471
463472 public:
464473 /// Construct a new raw_svector_ostream.
465474 ///
492501 ~raw_null_ostream();
493502 };
494503
504 /// string_ostream - A raw_ostream that builds a string. This is a
505 /// raw_svector_ostream with storage.
506 template
507 class small_string_ostream : public raw_svector_ostream {
508 SmallVector Buffer;
509 // There's no need to flush explicitly.
510 using raw_svector_ostream::flush;
511
512 public:
513 small_string_ostream() : raw_svector_ostream(Buffer, nullptr) { init(); }
514
515 void clear() {
516 flush();
517 Buffer.clear();
518 }
519 };
520
521 typedef small_string_ostream<128> string_ostream;
522
495523 } // end llvm namespace
496524
497525 #endif
4141
4242 void EmitString(raw_ostream &O) {
4343 // Escape the string.
44 SmallString<256> Str;
45 raw_svector_ostream(Str).write_escaped(AggregateString);
44 small_string_ostream<256> Str;
45 Str.write_escaped(AggregateString);
4646 AggregateString = Str.str();
4747
4848 O << " \"";
7474 LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
7575 char **OutMessages) {
7676 raw_ostream *DebugOS = Action != LLVMReturnStatusAction ? &errs() : nullptr;
77 std::string Messages;
78 raw_string_ostream MsgsOS(Messages);
77 string_ostream MsgsOS;
7978
8079 LLVMBool Result = verifyModule(*unwrap(M), OutMessages ? &MsgsOS : DebugOS);
8180
8786 report_fatal_error("Broken module found, compilation aborted!");
8887
8988 if (OutMessages)
90 *OutMessages = strdup(MsgsOS.str().c_str());
89 *OutMessages = strndup(MsgsOS.str().data(), MsgsOS.str().size());
9190
9291 return Result;
9392 }
8181
8282 std::string getNodeLabel(const BasicBlock *Node,
8383 const BlockFrequencyInfo *Graph) {
84 std::string Result;
85 raw_string_ostream OS(Result);
84 string_ostream OS;
8685
87 OS << Node->getName().str() << ":";
86 OS << Node->getName() << ":";
8887 switch (ViewBlockFreqPropagationDAG) {
8988 case GVDT_Fraction:
9089 Graph->printBlockFreq(OS, Node);
9796 "never reach this point.");
9897 }
9998
100 return Result;
99 return OS.str();
101100 }
102101 };
103102
104104 const DataLayout *DL;
105105 TargetLibraryInfo *TLI;
106106
107 std::string Messages;
108 raw_string_ostream MessagesStr;
107 string_ostream MessagesStr;
109108
110109 static char ID; // Pass identification, replacement for typeid
111 Lint() : FunctionPass(ID), MessagesStr(Messages) {
110 Lint() : FunctionPass(ID) {
112111 initializeLintPass(*PassRegistry::getPassRegistry());
113112 }
114113
180179 TLI = &getAnalysis();
181180 visit(F);
182181 dbgs() << MessagesStr.str();
183 Messages.clear();
182 MessagesStr.clear();
184183 return false;
185184 }
186185
2727 using namespace llvm;
2828
2929 static std::string getTypeString(Type *T) {
30 std::string Result;
31 raw_string_ostream Tmp(Result);
32 Tmp << *T;
33 return Tmp.str();
30 string_ostream Result;
31 Result << *T;
32 return Result.str();
3433 }
3534
3635 /// Run: module ::= toplevelentity*
15841584
15851585 // Otherwise report the problem to the user.
15861586 {
1587 std::string S;
1588 raw_string_ostream OS(S);
1587 string_ostream OS;
15891588 OS << "Unsupported expression in static initializer: ";
15901589 CE->printAsOperand(OS, /*PrintType=*/false,
15911590 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
240240 }
241241 }
242242 if (Error) {
243 std::string msg;
244 raw_string_ostream Msg(msg);
243 string_ostream Msg;
245244 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
246245 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
247246 }
412411 }
413412 }
414413 if (Error) {
415 std::string msg;
416 raw_string_ostream Msg(msg);
414 string_ostream Msg;
417415 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
418416 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
419417 }
470468
471469 // Emit the inline asm to a temporary string so we can emit it through
472470 // EmitInlineAsm.
473 SmallString<256> StringData;
474 raw_svector_ostream OS(StringData);
471 small_string_ostream<256> OS;
475472
476473 // The variant of the current asmprinter.
477474 int AsmPrinterVariant = MAI->getAssemblerDialect();
516513 }
517514 OS << Counter;
518515 } else {
519 std::string msg;
520 raw_string_ostream Msg(msg);
516 string_ostream Msg;
521517 Msg << "Unknown special formatter '" << Code
522518 << "' for machine instr: " << *MI;
523519 report_fatal_error(Msg.str());
8888
8989 std::string getNodeLabel(const MachineBasicBlock *Node,
9090 const MachineBlockFrequencyInfo *Graph) {
91 std::string Result;
92 raw_string_ostream OS(Result);
91 string_ostream OS;
9392
94 OS << Node->getName().str() << ":";
93 OS << Node->getName() << ":";
9594 switch (ViewMachineBlockFreqPropagationDAG) {
9695 case GVDT_Fraction:
9796 Graph->printBlockFreq(OS, Node);
104103 "never reach this point.");
105104 }
106105
107 return Result;
106 return OS.str();
108107 }
109108 };
110109
263263 ///
264264 /// Only used by debug logging.
265265 static std::string getBlockName(MachineBasicBlock *BB) {
266 std::string Result;
267 raw_string_ostream OS(Result);
266 string_ostream OS;
268267 OS << "BB#" << BB->getNumber()
269268 << " (derived from LLVM BB '" << BB->getName() << "')";
270 OS.flush();
271 return Result;
269 return OS.str();
272270 }
273271
274272 /// \brief Helper to print the number of a MBB.
275273 ///
276274 /// Only used by debug logging.
277275 static std::string getBlockNum(MachineBasicBlock *BB) {
278 std::string Result;
279 raw_string_ostream OS(Result);
276 string_ostream OS;
280277 OS << "BB#" << BB->getNumber();
281 OS.flush();
282 return Result;
278 return OS.str();
283279 }
284280 #endif
285281
464464
465465 const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
466466 DL->getPrivateGlobalPrefix();
467 SmallString<60> Name;
468 raw_svector_ostream(Name)
469 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
467 small_string_ostream<60> Name;
468 Name << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
470469 return Ctx.GetOrCreateSymbol(Name.str());
471470 }
472471
32343234 }
32353235
32363236 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3237 std::string Str;
3238 raw_string_ostream SS(Str);
3237 string_ostream SS;
32393238 const ScheduleDAGMI *DAG = static_cast(G);
32403239 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
32413240 static_cast(G)->getDFSResult() : nullptr;
11961196 }
11971197
11981198 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1199 std::string s;
1200 raw_string_ostream oss(s);
1199 string_ostream oss;
12011200 if (SU == &EntrySU)
12021201 oss << "";
12031202 else if (SU == &ExitSU)
32443244
32453245
32463246 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3247 std::string msg;
3248 raw_string_ostream Msg(msg);
3247 string_ostream Msg;
32493248 Msg << "Cannot select: ";
32503249
32513250 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
267267 }
268268
269269 std::string ScheduleDAGSDNodes::getGraphNodeLabel(const SUnit *SU) const {
270 std::string s;
271 raw_string_ostream O(s);
270 string_ostream O;
272271 O << "SU(" << SU->NodeNum << "): ";
273272 if (SU->getNode()) {
274273 SmallVector GluedNodes;
211211 if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
212212 && !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()
213213 && SchedModel.isComplete()) {
214 std::string Err;
215 raw_string_ostream ss(Err);
216 ss << "DefIdx " << DefIdx << " exceeds machine model writes for "
217 << *DefMI;
218 report_fatal_error(ss.str());
214 string_ostream Err;
215 Err << "DefIdx " << DefIdx << " exceeds machine model writes for "
216 << *DefMI;
217 report_fatal_error(Err.str());
219218 }
220219 #endif
221220 // FIXME: Automatically giving all implicit defs defaultDefLatency is
352352 Entries.back()->parseInstructions(Data, &Offset, EndStructureOffset);
353353
354354 if (Offset != EndStructureOffset) {
355 std::string Str;
356 raw_string_ostream OS(Str);
357 OS << format("Parsing entry instructions at %lx failed", StartOffset);
358 report_fatal_error(Str);
355 string_ostream Str;
356 Str << format("Parsing entry instructions at %lx failed", StartOffset);
357 report_fatal_error(Str.str());
359358 }
360359 }
361360 }
6161
6262 /*===-- Error handling ----------------------------------------------------===*/
6363
64 static char *LLVMCreateMessage(StringRef Message) {
65 assert(Message.find('\0') == Message.npos);
66 return strndup(Message.data(), Message.size());
67 }
68
6469 char *LLVMCreateMessage(const char *Message) {
6570 return strdup(Message);
6671 }
109114 }
110115
111116 char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) {
112 std::string MsgStorage;
113 raw_string_ostream Stream(MsgStorage);
114 DiagnosticPrinterRawOStream DP(Stream);
115
117 string_ostream Msg;
118 DiagnosticPrinterRawOStream DP(Msg);
116119 unwrap(DI)->print(DP);
117 Stream.flush();
118
119 return LLVMCreateMessage(MsgStorage.c_str());
120 return LLVMCreateMessage(Msg.str());
120121 }
121122
122123 LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI){
200201 }
201202
202203 char *LLVMPrintModuleToString(LLVMModuleRef M) {
203 std::string buf;
204 raw_string_ostream os(buf);
205
204 string_ostream os;
206205 unwrap(M)->print(os, nullptr);
207 os.flush();
208
209 return strdup(buf.c_str());
206 return LLVMCreateMessage(os.str());
210207 }
211208
212209 /*--.. Operations on inline assembler ......................................--*/
277274 }
278275
279276 char *LLVMPrintTypeToString(LLVMTypeRef Ty) {
280 std::string buf;
281 raw_string_ostream os(buf);
277 string_ostream os;
282278
283279 if (unwrap(Ty))
284280 unwrap(Ty)->print(os);
285281 else
286282 os << "Printing Type";
287283
288 os.flush();
289
290 return strdup(buf.c_str());
284 return strndup(os.str().data(), os.str().size());
291285 }
292286
293287 /*--.. Operations on integer types .........................................--*/
531525 }
532526
533527 char* LLVMPrintValueToString(LLVMValueRef Val) {
534 std::string buf;
535 raw_string_ostream os(buf);
528 string_ostream os;
536529
537530 if (unwrap(Val))
538531 unwrap(Val)->print(os);
539532 else
540533 os << "Printing Value";
541534
542 os.flush();
543
544 return strdup(buf.c_str());
535 return strndup(os.str().data(), os.str().size());
545536 }
546537
547538 void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) {
518518 }
519519
520520 std::string DataLayout::getStringRepresentation() const {
521 std::string Result;
522 raw_string_ostream OS(Result);
521 string_ostream OS;
523522
524523 OS << (LittleEndian ? "e" : "E");
525524
163163 }
164164
165165 // Otherwise, print the message with a prefix based on the severity.
166 std::string MsgStorage;
167 raw_string_ostream Stream(MsgStorage);
168 DiagnosticPrinterRawOStream DP(Stream);
166 string_ostream Msg;
167 DiagnosticPrinterRawOStream DP(Msg);
169168 DI.print(DP);
170 Stream.flush();
169
171170 switch (DI.getSeverity()) {
172171 case DS_Error:
173 errs() << "error: " << MsgStorage << "\n";
172 errs() << "error: " << Msg.str() << "\n";
174173 exit(1);
175174 case DS_Warning:
176 errs() << "warning: " << MsgStorage << "\n";
175 errs() << "warning: " << Msg.str() << "\n";
177176 break;
178177 case DS_Remark:
179 errs() << "remark: " << MsgStorage << "\n";
178 errs() << "remark: " << Msg.str() << "\n";
180179 break;
181180 case DS_Note:
182 errs() << "note: " << MsgStorage << "\n";
181 errs() << "note: " << Msg.str() << "\n";
183182 break;
184183 }
185184 }
107107
108108 if(!*OutM) {
109109 if (OutMessage) {
110 std::string buf;
111 raw_string_ostream os(buf);
112
110 string_ostream os;
113111 Diag.print(nullptr, os, false);
114 os.flush();
115
116 *OutMessage = strdup(buf.c_str());
112 *OutMessage = strndup(os.str().data(), os.str().size());
117113 }
118114 return 1;
119115 }
548548 break;
549549 }
550550 // Create the string that will be reported to the external diagnostic handler.
551 std::string MsgStorage;
552 raw_string_ostream Stream(MsgStorage);
553 DiagnosticPrinterRawOStream DP(Stream);
551 string_ostream Msg;
552 DiagnosticPrinterRawOStream DP(Msg);
554553 DI.print(DP);
555 Stream.flush();
554
555 // Null-terminate the C string.
556 Msg << '\0';
556557
557558 // If this method has been called it means someone has set up an external
558559 // diagnostic handler. Assert on that.
559560 assert(DiagHandler && "Invalid diagnostic handler");
560 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
561 (*DiagHandler)(Severity, Msg.str().data(), DiagContext);
561562 }
562563
563564 void
11741174 raw_ostream &OS = GetCommentOS();
11751175 SmallString<256> Code;
11761176 SmallVector Fixups;
1177 raw_svector_ostream VecOS(Code);
1178 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1179 VecOS.flush();
1177 {
1178 raw_svector_ostream VecOS(Code);
1179 Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
1180 }
11801181
11811182 // If we are showing fixups, create symbolic markers in the encoded
11821183 // representation. We do this by making a per-bit map to the fixup item index,
139139 }
140140
141141 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
142 SmallString<128> NameSV;
143 raw_svector_ostream(NameSV)
144 << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
145 return CreateSymbol(NameSV);
142 small_string_ostream<128> NameSV;
143 NameSV << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
144 return CreateSymbol(NameSV.str());
146145 }
147146
148147 MCSymbol *MCContext::CreateTempSymbol() {
149 SmallString<128> NameSV;
150 raw_svector_ostream(NameSV)
151 << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
152 return CreateSymbol(NameSV);
148 small_string_ostream<128> NameSV;
149 NameSV << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
150 return CreateSymbol(NameSV.str());
153151 }
154152
155153 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
269269 const MCDisassembler *DisAsm = DC->getDisAsm();
270270 MCInstPrinter *IP = DC->getIP();
271271 MCDisassembler::DecodeStatus S;
272 SmallVector InsnStr;
273 raw_svector_ostream Annotations(InsnStr);
272 small_string_ostream<64> Annotations;
274273 S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
275274 /*REMOVE*/ nulls(), Annotations);
276275 switch (S) {
280279 return 0;
281280
282281 case MCDisassembler::Success: {
283 Annotations.flush();
284 StringRef AnnotationsStr = Annotations.str();
285
286282 SmallVector InsnStr;
287283 raw_svector_ostream OS(InsnStr);
288284 formatted_raw_ostream FormattedOS(OS);
289 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
285 IP->printInst(&Inst, FormattedOS, Annotations.str());
290286
291287 if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
292288 emitLatency(DC, Inst);
419419 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
420420 uint64_t AddrDelta) {
421421 MCContext &Context = MCOS->getContext();
422 SmallString<256> Tmp;
423 raw_svector_ostream OS(Tmp);
422 small_string_ostream<256> OS;
424423 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
425424 MCOS->EmitBytes(OS.str());
426425 }
16461645 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
16471646 uint64_t AddrDelta) {
16481647 MCContext &Context = Streamer.getContext();
1649 SmallString<256> Tmp;
1650 raw_svector_ostream OS(Tmp);
1648 small_string_ostream<256> OS;
16511649 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
16521650 Streamer.EmitBytes(OS.str());
16531651 }
45794579 }
45804580
45814581 // Build the IR assembly string.
4582 std::string AsmStringIR;
4583 raw_string_ostream OS(AsmStringIR);
4582 string_ostream OS;
45844583 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
45854584 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
45864585 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
46454644 }
46464645 case AOK_DotOperator:
46474646 // Insert the dot if the user omitted it.
4648 OS.flush();
4649 if (AsmStringIR.back() != '.')
4647 if (OS.str().back() != '.')
46504648 OS << '.';
46514649 OS << AR.Val;
46524650 break;
300300
301301 static void printRelocationTargetName(const MachOObjectFile *O,
302302 const MachO::any_relocation_info &RE,
303 raw_string_ostream &fmt) {
303 raw_ostream &fmt) {
304304 bool IsScattered = O->isRelocationScattered(RE);
305305
306306 // Target of a scattered relocation is an address. In the interest of
10091009
10101010 unsigned Arch = this->getArch();
10111011
1012 std::string fmtbuf;
1013 raw_string_ostream fmt(fmtbuf);
1012 string_ostream fmt;
10141013 unsigned Type = this->getAnyRelocationType(RE);
10151014 bool IsPCRel = this->getAnyRelocationPCRel(RE);
10161015
11731172 } else
11741173 printRelocationTargetName(this, RE, fmt);
11751174
1176 fmt.flush();
1175 StringRef fmtbuf = fmt.str();
11771176 Result.append(fmtbuf.begin(), fmtbuf.end());
11781177 return object_error::success;
11791178 }
6161 }
6262
6363 std::string Arg::getAsString(const ArgList &Args) const {
64 SmallString<256> Res;
65 llvm::raw_svector_ostream OS(Res);
64 small_string_ostream<256> OS;
6665
6766 ArgStringList ASL;
6867 render(Args, ASL);
9493 break;
9594
9695 case Option::RenderCommaJoinedStyle: {
97 SmallString<256> Res;
98 llvm::raw_svector_ostream OS(Res);
96 small_string_ostream<256> OS;
9997 OS << getSpelling();
10098 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
10199 if (i) OS << ',';
13411341
13421342 // printOptionDiff - Specializations for printing basic value types.
13431343 //
1344 #define PRINT_OPT_DIFF(T) \
1345 void parser:: \
1346 printOptionDiff(const Option &O, T V, OptionValue D, \
1347 size_t GlobalWidth) const { \
1348 printOptionName(O, GlobalWidth); \
1349 std::string Str; \
1350 { \
1351 raw_string_ostream SS(Str); \
1352 SS << V; \
1353 } \
1354 outs() << "= " << Str; \
1355 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1356 outs().indent(NumSpaces) << " (default: "; \
1357 if (D.hasValue()) \
1358 outs() << D.getValue(); \
1359 else \
1360 outs() << "*no default*"; \
1361 outs() << ")\n"; \
1362 } \
1344 #define PRINT_OPT_DIFF(T) \
1345 void parser::printOptionDiff(const Option &O, T V, OptionValue D, \
1346 size_t GlobalWidth) const { \
1347 printOptionName(O, GlobalWidth); \
1348 string_ostream SS; \
1349 SS << V; \
1350 outs() << "= " << SS.str(); \
1351 size_t NumSpaces = MaxOptWidth > SS.tell() ? MaxOptWidth - SS.tell() : 0; \
1352 outs().indent(NumSpaces) << " (default: "; \
1353 if (D.hasValue()) \
1354 outs() << D.getValue(); \
1355 else \
1356 outs() << "*no default*"; \
1357 outs() << ")\n"; \
1358 }
13631359
13641360 PRINT_OPT_DIFF(bool)
13651361 PRINT_OPT_DIFF(boolOrDefault)
703703 // and we only need to set the vector size when the data is flushed.
704704
705705 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl &O) : OS(O) {
706 init();
707 }
708
709 void raw_svector_ostream::init() {
706710 // Set up the initial external buffer. We make sure that the buffer has at
707711 // least 128 bytes free; raw_ostream itself only requires 64, but we want to
708712 // make sure that we don't grow the buffer unnecessarily on destruction (when
208208 break;
209209 else if (Step < 0 && From < To)
210210 break;
211 std::string Name;
212 raw_string_ostream OS(Name);
213 OS << format(Format.c_str(), unsigned(From));
214 Record *Rec = Records.getDef(OS.str());
211 string_ostream Name;
212 Name << format(Format.c_str(), unsigned(From));
213 Record *Rec = Records.getDef(Name.str());
215214 if (!Rec)
216 PrintFatalError(Loc, "No def named '" + Name + "': " +
217 Expr->getAsString());
215 PrintFatalError(Loc, "No def named '" + Name.str() + "': " +
216 Expr->getAsString());
218217 // Try to reevaluate Rec in case it is a set.
219218 if (const RecVec *Result = ST.expand(Rec))
220219 Elts.insert(Result->begin(), Result->end());
13061306 if (ItemType) {
13071307 ListRecTy *ListType = dyn_cast(ItemType);
13081308 if (!ListType) {
1309 std::string s;
1310 raw_string_ostream ss(s);
1309 string_ostream ss;
13111310 ss << "Type mismatch for list, expected list type, got "
13121311 << ItemType->getAsString();
13131312 TokError(ss.str());
145145
146146 // Otherwise report the problem to the user.
147147 {
148 std::string S;
149 raw_string_ostream OS(S);
148 string_ostream OS;
150149 OS << "Unsupported expression in static initializer: ";
151150 CE->printAsOperand(OS, /*PrintType=*/ false,
152151 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
236236 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
237237 LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
238238 LLVMMemoryBufferRef *OutMemBuf) {
239 std::string CodeString;
240 raw_string_ostream OStream(CodeString);
241 formatted_raw_ostream Out(OStream);
239 string_ostream Code;
240 formatted_raw_ostream Out(Code);
242241 bool Result = LLVMTargetMachineEmit(T, M, Out, codegen, ErrorMessage);
243 OStream.flush();
244
245 std::string &Data = OStream.str();
246 *OutMemBuf = LLVMCreateMemoryBufferWithMemoryRangeCopy(Data.c_str(),
247 Data.length(), "");
242
243 StringRef Buffer = Code.str();
244 *OutMemBuf = LLVMCreateMemoryBufferWithMemoryRangeCopy(Buffer.data(),
245 Buffer.size(), "");
248246 return Result;
249247 }
250248
24112411 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
24122412 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
24132413
2414 SmallString<126> Msg;
2415 raw_svector_ostream OS(Msg);
2414 small_string_ostream<128> OS;
24162415 OS << "ambiguous instructions require an explicit suffix (could be ";
24172416 for (unsigned i = 0; i != NumMatches; ++i) {
24182417 if (i != 0)
280280 unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
281281
282282 if (RelaxedOp == Inst.getOpcode()) {
283 SmallString<256> Tmp;
284 raw_svector_ostream OS(Tmp);
283 small_string_ostream<256> OS;
285284 Inst.dump_pretty(OS);
286285 OS << "\n";
287286 report_fatal_error("unexpected instruction to relax: " + OS.str());
549549 }
550550
551551 void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
552 SmallString<128> Directive;
553 raw_svector_ostream OS(Directive);
552 small_string_ostream<128> OS;
554553 StringRef Name = Sym->getName();
555554
556555 if (Subtarget->isTargetKnownWindowsMSVC())
571570 OS << ",data";
572571 }
573572
574 OS.flush();
575 OutStreamer.EmitBytes(Directive);
573 OutStreamer.EmitBytes(OS.str());
576574 }
577575
578576 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
266266 }
267267
268268 void XCoreAsmPrinter::EmitInstruction(const MachineInstr *MI) {
269 SmallString<128> Str;
270 raw_svector_ostream O(Str);
269 small_string_ostream<128> O;
271270
272271 switch (MI->getOpcode()) {
273272 case XCore::DBG_VALUE:
351351 }
352352
353353 std::string getTypeName(Type *T) {
354 std::string TypeName;
355 raw_string_ostream TypeStream(TypeName);
354 string_ostream OS;
356355 if (T)
357 T->print(TypeStream);
356 T->print(OS);
358357 else
359 TypeStream << "Printing Type";
360 TypeStream.flush();
361 return TypeName;
358 OS << "Printing Type";
359 return OS.str();
362360 }
363361
364362 /// Returns the MDNode that represents type T if it is already created, or 0
315315 }
316316 ReturnBlock = new GCOVBlock(i++, os);
317317
318 std::string FunctionNameAndLine;
319 raw_string_ostream FNLOS(FunctionNameAndLine);
320 FNLOS << getFunctionName(SP) << SP.getLineNumber();
321 FNLOS.flush();
322 FuncChecksum = hash_value(FunctionNameAndLine);
318 string_ostream FnNameLine;
319 FnNameLine << getFunctionName(SP) << SP.getLineNumber();
320 FuncChecksum = hash_value(FnNameLine.str());
323321 }
324322
325323 ~GCOVFunction() {
336334 }
337335
338336 std::string getEdgeDestinations() {
339 std::string EdgeDestinations;
340 raw_string_ostream EDOS(EdgeDestinations);
337 string_ostream EdgeDestinations;
341338 Function *F = Blocks.begin()->first->getParent();
342339 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
343340 GCOVBlock &Block = *Blocks[I];
344341 for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
345 EDOS << Block.OutEdges[i]->Number;
346 }
347 return EdgeDestinations;
342 EdgeDestinations << Block.OutEdges[i]->Number;
343 }
344 return EdgeDestinations.str();
348345 }
349346
350347 uint32_t getFuncChecksum() {
24232423
24242424 if (PoisonStack && MS.TrackOrigins) {
24252425 setOrigin(&I, getCleanOrigin());
2426 SmallString<2048> StackDescriptionStorage;
2427 raw_svector_ostream StackDescription(StackDescriptionStorage);
2426 small_string_ostream<2048> StackDescription;
24282427 // We create a string with a description of the stack allocation and
24292428 // pass it into __msan_set_alloca_origin.
24302429 // It will be printed by the run-time if stack-originated UMR is found.
834834 // of line at the module level and to provide a very simple format
835835 // encoding the information herein. Both of these makes it simpler to
836836 // parse the annotations by a simple external program.
837 std::string Str;
838 raw_string_ostream os(Str);
837 string_ostream os;
839838 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
840839 << Inst->getName() << ")";
841840
848847 Hash = cast(Node->getOperand(0));
849848 }
850849 } else if (Argument *Arg = dyn_cast(Ptr)) {
851 std::string str;
852 raw_string_ostream os(str);
850 string_ostream os;
853851 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
854852 << ")";
855853 Hash = MDString::get(Arg->getContext(), os.str());
859857 }
860858
861859 static std::string SequenceToString(Sequence A) {
862 std::string str;
863 raw_string_ostream os(str);
860 string_ostream os;
864861 os << A;
865862 return os.str();
866863 }
6464 Vars[i].Alignment = std::max(Vars[i].Alignment, kMinAlignment);
6565
6666 std::stable_sort(Vars.begin(), Vars.end(), CompareVars);
67 SmallString<2048> StackDescriptionStorage;
68 raw_svector_ostream StackDescription(StackDescriptionStorage);
67 small_string_ostream<2048> StackDescription;
6968 StackDescription << NumVars;
7069 Layout->FrameAlignment = std::max(Granularity, Vars[0].Alignment);
7170 SmallVector &SB(Layout->ShadowBytes);
211211 /// Optimization analysis message produced during vectorization. Messages inform
212212 /// the user why vectorization did not occur.
213213 class Report {
214 std::string Message;
215 raw_string_ostream Out;
214 string_ostream Message;
216215 Instruction *Instr;
217216
218217 public:
219 Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
220 Out << "loop not vectorized: ";
218 Report(Instruction *I = nullptr) : Instr(I) {
219 Message << "loop not vectorized: ";
221220 }
222221
223222 template Report &operator<<(const A &Value) {
224 Out << Value;
223 Message << Value;
225224 return *this;
226225 }
227226
228227 Instruction *getInstr() { return Instr; }
229228
230 std::string &str() { return Out.str(); }
231 operator Twine() { return Out.str(); }
229 StringRef str() { return Message.str(); }
230 operator Twine() { return Message.str(); }
232231 };
233232
234233 /// InnerLoopVectorizer vectorizes loops which contain only one basic
502501 #ifndef NDEBUG
503502 /// \return string containing a file name and a line # for the given loop.
504503 static std::string getDebugLocString(const Loop *L) {
505 std::string Result;
506 if (L) {
507 raw_string_ostream OS(Result);
508 const DebugLoc LoopDbgLoc = L->getStartLoc();
509 if (!LoopDbgLoc.isUnknown())
510 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
511 else
512 // Just print the module name.
513 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
514 OS.flush();
515 }
516 return Result;
504 if (!L)
505 return std::string();
506
507 string_ostream OS;
508 const DebugLoc LoopDbgLoc = L->getStartLoc();
509 if (!LoopDbgLoc.isUnknown())
510 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
511 else
512 // Just print the module name.
513 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
514 return OS.str();
517515 }
518516 #endif
519517
688688 std::vector> &MemberOffsetRefs) {
689689 unsigned StartOffset = 0;
690690 unsigned MemberNum = 0;
691 std::string NameBuf;
692 raw_string_ostream NameOS(NameBuf);
691 string_ostream NameOS;
693692 unsigned NumSyms = 0;
694693 LLVMContext &Context = getGlobalContext();
695694 for (ArrayRef::iterator I = Members.begin(),
221221 Out << "";
222222
223223 // Escape special chars and print the instruction in mnemonic form.
224 std::string Str;
225 raw_string_ostream OS(Str);
224 string_ostream OS;
226225 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
227226 Out << DOT::EscapeString(OS.str());
228227 }
472471 if (Symbols.empty())
473472 Symbols.push_back(std::make_pair(0, name));
474473
475
476 SmallString<40> Comments;
477 raw_svector_ostream CommentStream(Comments);
474 small_string_ostream<40> Comments;
478475
479476 StringRef Bytes;
480477 if (error(Section.getContents(Bytes)))
512509 MCInst Inst;
513510
514511 if (DisAsm->getInstruction(Inst, Size, memoryObject,
515 SectionAddr + Index,
516 DebugOut, CommentStream)) {
512 SectionAddr + Index, DebugOut, Comments)) {
517513 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
518514 if (!NoShowRawInsn) {
519515 outs() << "\t";
520516 DumpBytes(StringRef(Bytes.data() + Index, Size));
521517 }
522518 IP->printInst(&Inst, outs(), "");
523 outs() << CommentStream.str();
519 outs() << Comments.str();
524520 Comments.clear();
525521 outs() << "\n";
526522 } else {
9494
9595 static std::string formatSymbol(StringRef Name, uint64_t Address,
9696 uint64_t Offset = 0) {
97 std::string Buffer;
98 raw_string_ostream OS(Buffer);
97 string_ostream OS;
9998
10099 if (!Name.empty())
101100 OS << Name << " ";
114114 static std::string formatSymbol(const Dumper::Context &Ctx,
115115 const coff_section *Section, uint64_t Offset,
116116 uint32_t Displacement) {
117 std::string Buffer;
118 raw_string_ostream OS(Buffer);
117 string_ostream OS;
119118
120119 StringRef Name;
121120 SymbolRef Symbol;
130129 OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset);
131130 else
132131 OS << format(" (0x%" PRIX64 ")", Offset);
132
133133 return OS.str();
134134 }
135135
6969 }
7070
7171 std::string DumpFunction(const Function *F) {
72 std::string Result;
73 raw_string_ostream(Result) << "" << *F;
74 return Result;
72 string_ostream Result;
73 Result << "" << *F;
74 return Result.str();
7575 }
7676
7777 class RecordingJITMemoryManager : public JITMemoryManager {
169169 SMDiagnostic Error;
170170 bool success =
171171 nullptr != ParseAssemblyString(assembly, M, Error, M->getContext());
172 std::string errMsg;
173 raw_string_ostream os(errMsg);
174 Error.print("", os);
175 EXPECT_TRUE(success) << os.str();
172 string_ostream errMsg;
173 Error.print("", errMsg);
174 EXPECT_TRUE(success) << errMsg.str();
176175 return success;
177176 }
178177
457457 // variable values.
458458 if (!VariableUses.empty()) {
459459 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
460 SmallString<256> Msg;
461 raw_svector_ostream OS(Msg);
460 small_string_ostream<256> OS;
462461 StringRef Var = VariableUses[i].first;
463462 if (Var[0] == '@') {
464463 std::string Value;
318318
319319 // Default case: unhandled opcode
320320 o << " default:\n"
321 << " std::string msg;\n"
322 << " raw_string_ostream Msg(msg);\n"
321 << " string_ostream Msg;\n"
323322 << " Msg << \"Not supported instr: \" << MI;\n"
324323 << " report_fatal_error(Msg.str());\n"
325324 << " }\n"
165165 }
166166
167167 static std::string createJSONText(size_t MemoryMB, unsigned ValueSize) {
168 std::string JSONText;
169 llvm::raw_string_ostream Stream(JSONText);
170 Stream << "[\n";
168 llvm::string_ostream OS;
169 OS << "[\n";
171170 size_t MemoryBytes = MemoryMB * 1024 * 1024;
172 while (JSONText.size() < MemoryBytes) {
173 Stream << " {\n"
174 << " \"key1\": \"" << std::string(ValueSize, '*') << "\",\n"
175 << " \"key2\": \"" << std::string(ValueSize, '*') << "\",\n"
176 << " \"key3\": \"" << std::string(ValueSize, '*') << "\"\n"
177 << " }";
178 Stream.flush();
179 if (JSONText.size() < MemoryBytes) Stream << ",";
180 Stream << "\n";
181 }
182 Stream << "]\n";
183 Stream.flush();
184 return JSONText;
171 while (OS.tell() < MemoryBytes) {
172 OS << " {\n"
173 << " \"key1\": \"" << std::string(ValueSize, '*') << "\",\n"
174 << " \"key2\": \"" << std::string(ValueSize, '*') << "\",\n"
175 << " \"key3\": \"" << std::string(ValueSize, '*') << "\"\n"
176 << " }";
177 if (OS.tell() < MemoryBytes)
178 OS << ",";
179 OS << "\n";
180 }
181 OS << "]\n";
182 return OS.str();
185183 }
186184
187185 int main(int argc, char **argv) {