void native(const Twine &path, SmallVectorImpl<char> &result, Style style) { assert((!path.isSingleStringRef() || path.getSingleStringRef().data() != result.data()) && "path and result are not allowed to overlap!"); // Clear result. result.clear(); path.toVector(result); native(result, style); }
void Value::setName(const Twine &NewName) { assert(SubclassID != MDStringVal && "Cannot set the name of MDString with this method!"); // Fast path for common IRBuilder case of setName("") when there is no name. if (NewName.isTriviallyEmpty() && !hasName()) return; SmallString<256> NameData; StringRef NameRef = NewName.toStringRef(NameData); // Name isn't changing? if (getName() == NameRef) return; assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); // Get the symbol table to update for this object. ValueSymbolTable *ST; if (getSymTab(this, ST)) return; // Cannot set a name on this value (e.g. constant). if (!ST) { // No symbol table to update? Just do the change. if (NameRef.empty()) { // Free the name for this value. Name->Destroy(); Name = 0; return; } if (Name) Name->Destroy(); // NOTE: Could optimize for the case the name is shrinking to not deallocate // then reallocated. // Create the new name. Name = ValueName::Create(NameRef.begin(), NameRef.end()); Name->setValue(this); return; } // NOTE: Could optimize for the case the name is shrinking to not deallocate // then reallocated. if (hasName()) { // Remove old name. ST->removeValueName(Name); Name->Destroy(); Name = 0; if (NameRef.empty()) return; } // Name is changing to something new. Name = ST->createValueName(NameRef, this); }
/// \brief Construct a triple from string representations of the architecture, /// vendor, and OS. /// /// This joins each argument into a canonical string representation and parses /// them into enum members. It leaves the environment unknown and omits it from /// the string representation. Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr) : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr).str()), Arch(parseArch(ArchStr.str())), SubArch(parseSubArch(ArchStr.str())), Vendor(parseVendor(VendorStr.str())), OS(parseOS(OSStr.str())), Environment(), ObjectFormat(Triple::UnknownObjectFormat) { ObjectFormat = getDefaultFormat(*this); }
void Attributes::addComment(const Twine &Comment) { if (!Comment.isTriviallyEmpty()) { if (Comments.empty()) Comments = " // "; else Comments += ", "; Comments += Comment.str(); } }
/// \brief Construct a triple from string representations of the architecture, /// vendor, OS, and environment. /// /// This joins each argument into a canonical string representation and parses /// them into enum members. Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr, const Twine &EnvironmentStr) : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr + Twine('-') + EnvironmentStr).str()), Arch(parseArch(ArchStr.str())), Vendor(parseVendor(VendorStr.str())), OS(parseOS(OSStr.str())), Environment(parseEnvironment(EnvironmentStr.str())) { }
void Attributes::add(const Twine &Name, const Twine &Value, const Twine &Comment) { std::string A = Name.str(); A += "=\""; A += Value.str(); A += "\""; Attrs.push_back(A); addComment(Comment); }
void Value::setNameImpl(const Twine &NewName) { // Fast-path: LLVMContext can be set to strip out non-GlobalValue names if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this)) return; // Fast path for common IRBuilder case of setName("") when there is no name. if (NewName.isTriviallyEmpty() && !hasName()) return; SmallString<256> NameData; StringRef NameRef = NewName.toStringRef(NameData); assert(NameRef.find_first_of(0) == StringRef::npos && "Null bytes are not allowed in names"); // Name isn't changing? if (getName() == NameRef) return; assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); // Get the symbol table to update for this object. ValueSymbolTable *ST; if (getSymTab(this, ST)) return; // Cannot set a name on this value (e.g. constant). if (!ST) { // No symbol table to update? Just do the change. if (NameRef.empty()) { // Free the name for this value. destroyValueName(); return; } // NOTE: Could optimize for the case the name is shrinking to not deallocate // then reallocated. destroyValueName(); // Create the new name. setValueName(ValueName::Create(NameRef)); getValueName()->setValue(this); return; } // NOTE: Could optimize for the case the name is shrinking to not deallocate // then reallocated. if (hasName()) { // Remove old name. ST->removeValueName(getValueName()); destroyValueName(); if (NameRef.empty()) return; } // Name is changing to something new. setValueName(ST->createValueName(NameRef, this)); }
/// setName - Set the name of this named metadata. void NamedMDNode::setName(const Twine &NewName) { assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!"); SmallString<256> NameData; StringRef NameRef = NewName.toStringRef(NameData); // Name isn't changing? if (getName() == NameRef) return; Name = NameRef.str(); if (Parent) Parent->getMDSymbolTable().insert(NameRef, this); }
void Attributes::add(const Twine &Name, const Twine &Value, const Twine &Comment) { std::string A = Name.str(); A += "=\""; A += Value.str(); A += "\""; Attrs.push_back(A); if (!Comment.isTriviallyEmpty()) { if (Comments.empty()) Comments = " // "; else Comments += ", "; Comments += Comment.str(); } }
bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code, const std::vector<std::string> &Args, const Twine &FileName) { SmallString<16> FileNameStorage; StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); llvm::IntrusiveRefCntPtr<FileManager> Files( new FileManager(FileSystemOptions())); ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction, Files.getPtr()); SmallString<1024> CodeStorage; Invocation.mapVirtualFile(FileNameRef, Code.toNullTerminatedStringRef(CodeStorage)); return Invocation.run(); }
bool FileRemapper::report(const Twine &err, DiagnosticsEngine &Diag) { SmallString<128> buf; unsigned ID = Diag.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Error, err.toStringRef(buf)); Diag.Report(ID); return true; }
// This is for use when debugging LTO. static void saveBuffer(StringRef Buffer, const Twine &Path) { std::error_code EC; raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None); if (EC) error(EC, "cannot create " + Path); OS << Buffer; }
static std::string GetName(Value *V) { static unsigned Id = 0; if (!Ids.count(V)) Ids[V] = Id++; Twine Name; if (V->hasName()) { if (isa<Instruction>(V) || isa<Argument>(V)) Name = V->getName(); else Name = "__SRA_SYM_UNKNOWN_" + V->getName() + "__"; } else { Name = "__SRA_SYM_UNAMED__"; } return Name.str() + "." + std::to_string(Ids[V]); }
/// getNameWithPrefix - Fill OutName with the name of the appropriate prefix /// and the specified name as the global variable name. GVName must not be /// empty. void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName, const Twine &GVName, ManglerPrefixTy PrefixTy) { SmallString<256> TmpData; StringRef Name = GVName.toStringRef(TmpData); assert(!Name.empty() && "getNameWithPrefix requires non-empty name"); // If the global name is not led with \1, add the appropriate prefixes. if (Name[0] == '\1') { Name = Name.substr(1); } else { if (PrefixTy == Mangler::Private) { const char *Prefix = DL->getPrivateGlobalPrefix(); OutName.append(Prefix, Prefix+strlen(Prefix)); } else if (PrefixTy == Mangler::LinkerPrivate) { const char *Prefix = DL->getLinkerPrivateGlobalPrefix(); OutName.append(Prefix, Prefix+strlen(Prefix)); } char Prefix = DL->getGlobalPrefix(); if (Prefix != '\0') OutName.push_back(Prefix); } // If this is a simple string that doesn't need escaping, just append it. OutName.append(Name.begin(), Name.end()); }
static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx, Twine Filename, raw_ostream &OS) { logAllUnhandledErrors(DICtx.loadRegisterInfo(Obj), errs(), Filename.str() + ": "); // The UUID dump already contains all the same information. if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All) OS << Filename << ":\tfile format " << Obj.getFileFormatName() << '\n'; // Handle the --lookup option. if (Lookup) return lookup(DICtx, Lookup, OS); // Handle the --name option. if (!Name.empty()) { StringSet<> Names; for (auto name : Name) Names.insert((IgnoreCase && !UseRegex) ? StringRef(name).lower() : name); filterByName(Names, DICtx.compile_units(), OS); filterByName(Names, DICtx.dwo_compile_units(), OS); return true; } // Handle the --find option and lower it to --debug-info=<offset>. if (!Find.empty()) { filterByAccelName(Find, DICtx, OS); return true; } // Dump the complete DWARF structure. DICtx.dump(OS, getDumpOpts(), DumpOffsets); return true; }
void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { llvm::fatal_error_handler_t handler = nullptr; void* handlerData = nullptr; { // Only acquire the mutex while reading the handler, so as not to invoke a // user-supplied callback under a lock. #if LLVM_ENABLE_THREADS == 1 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex); #endif handler = ErrorHandler; handlerData = ErrorHandlerUserData; } if (handler) { handler(handlerData, Reason.str(), GenCrashDiag); } else { // Blast the result out to stderr. We don't try hard to make sure this // succeeds (e.g. handling EINTR) and we can't use errs() here because // raw ostreams can call report_fatal_error. SmallVector<char, 64> Buffer; raw_svector_ostream OS(Buffer); OS << "LLVM ERROR: " << Reason << "\n"; StringRef MessageStr = OS.str(); ssize_t written = ::write(2, MessageStr.data(), MessageStr.size()); (void)written; // If something went wrong, we deliberately just give up. } // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); }
static void getNameWithPrefixx(raw_ostream &OS, const Twine &GVName, Mangler::ManglerPrefixTy PrefixTy, const DataLayout &DL, char Prefix) { SmallString<256> TmpData; StringRef Name = GVName.toStringRef(TmpData); assert(!Name.empty() && "getNameWithPrefix requires non-empty name"); // No need to do anything special if the global has the special "do not // mangle" flag in the name. if (Name[0] == '\1') { OS << Name.substr(1); return; } if (PrefixTy == Mangler::Private) OS << DL.getPrivateGlobalPrefix(); else if (PrefixTy == Mangler::LinkerPrivate) OS << DL.getLinkerPrivateGlobalPrefix(); if (Prefix != '\0') OS << Prefix; // If this is a simple string that doesn't need escaping, just append it. OS << Name; }
void cFontLoader:: ExportDFFToFile(tDistanceFontHandle font, const Twine& in_path /*= ""*/) { auto& dff = DistanceFont(font); size_t face_size = cSerialization::SerializedSize(dff.Face()); cDFFFile pair(dff, face_size); AlignedBuffer<16> buffer; cSerialization::SerializeLZMA(pair,buffer); cStringRef file_data(buffer.ptr<char>(), buffer.size()); try{ if (sys::path::has_filename(in_path)) { WriteFileToDisk(file_data, in_path); } else { cSmallVector<char, 256> path_buf; cStringRef temp_path = in_path.toNullTerminatedStringRef(path_buf); sys::path::append(path_buf, in_path, dff.FontName() + ".dff"); cStringRef full_path(path_buf.data(), path_buf.size()); WriteFileToDisk(file_data, full_path); } } catch (const Exception& e) { Log::Warn("Swallowed exception while trying to write dff file: %s", e.what()); } }
/// \brief Construct a triple from the string representation provided. /// /// This stores the string representation and parses the various pieces into /// enum members. Triple::Triple(const Twine &Str) : Data(Str.str()), Arch(parseArch(getArchName())), Vendor(parseVendor(getVendorName())), OS(parseOS(getOSName())), Environment(parseEnvironment(getEnvironmentName())) { }
error_code RealFile::getBuffer(const Twine &Name, std::unique_ptr<MemoryBuffer> &Result, int64_t FileSize, bool RequiresNullTerminator) { assert(FD != -1 && "cannot get buffer for closed file"); return MemoryBuffer::getOpenFile(FD, Name.str().c_str(), Result, FileSize, RequiresNullTerminator); }
std::unique_ptr<MemoryBuffer> MemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) { // Allocate space for the MemoryBuffer, the data and the name. It is important // that MemoryBuffer and data are aligned so PointerIntPair works with them. // TODO: Is 16-byte alignment enough? We copy small object files with large // alignment expectations into this buffer. SmallString<256> NameBuf; StringRef NameRef = BufferName.toStringRef(NameBuf); size_t AlignedStringLen = alignTo(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16); size_t RealLen = AlignedStringLen + Size + 1; char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); if (!Mem) return nullptr; // The name is stored after the class itself. CopyStringRef(Mem + sizeof(MemoryBufferMem), NameRef); // The buffer begins after the name and must be aligned. char *Buf = Mem + AlignedStringLen; Buf[Size] = 0; // Null terminate buffer. auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true); return std::unique_ptr<MemoryBuffer>(Ret); }
bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) { assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size())); Error = SMDiagnostic( SM, SMLoc(), SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1, Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None); return true; }
void QualType::print(const Type *ty, Qualifiers qs, raw_ostream &OS, const PrintingPolicy &policy, const Twine &PlaceHolder) { SmallString<128> PHBuf; StringRef PH = PlaceHolder.toStringRef(PHBuf); TypePrinter(policy).print(ty, qs, OS, PH); }
ErrorOr<Status> RealFileSystem::status(const Twine &Path) { sys::fs::file_status RealStatus; if (error_code EC = sys::fs::status(Path, RealStatus)) return EC; Status Result(RealStatus); Result.setName(Path.str()); return Result; }
void llvm_report_error(const Twine &reason) { if (!ErrorHandler) { errs() << "LLVM ERROR: " << reason << "\n"; } else { ErrorHandler(ErrorHandlerUserData, reason.str()); } exit(1); }
static int getFD(const Twine& Filename, std::error_code& EC) { // Handle "-" as stdin. Note that when we do this, we consider ourself // the owner of stdin. This means that we can do things like close the // file descriptor when we're done and set the "binary" flag globally. if (Filename.isSingleStringRef() && Filename.getSingleStringRef() == "-") { EC = std::error_code(); return STDIN_FILENO; } int FD; EC = sys::fs::openFileForRead(Filename, FD); if (EC) return -1; EC = std::error_code(); return FD; }
static void DumpObjectFile(ObjectFile &Obj, Twine Filename) { std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); outs() << Filename.str() << ":\tfile format " << Obj.getFileFormatName() << "\n\n"; // Dump the complete DWARF structure. DICtx->dump(outs(), DumpType, false, SummarizeTypes); }
/// @brief Small string conversion via raw_string_stream. template <typename T> std::string operator+(Twine LHS, const T &RHS) { std::string Buf; raw_string_ostream fmt(Buf); fmt << RHS; fmt.flush(); return LHS.concat(Buf).str(); }
static void failIfError(std::error_code EC, Twine Context = "") { if (!EC) return; std::string ContextStr = Context.str(); if (ContextStr == "") fail(EC.message()); fail(Context + ": " + EC.message()); }
error_code RealFileSystem::openFileForRead(const Twine &Name, std::unique_ptr<File> &Result) { int FD; if (error_code EC = sys::fs::openFileForRead(Name, FD)) return EC; Result.reset(new RealFile(FD)); Result->setName(Name.str()); return error_code::success(); }