LLVM 23.0.0git
InstrProf.h
Go to the documentation of this file.
1//===- InstrProf.h - Instrumented profiling format support ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Instrumentation-based profiling data is generated by instrumented
10// binaries through library functions in compiler-rt, and read by the clang
11// frontend to feed PGO.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_PROFILEDATA_INSTRPROF_H
16#define LLVM_PROFILEDATA_INSTRPROF_H
17
18#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/StringSet.h"
25#include "llvm/IR/GlobalValue.h"
32#include "llvm/Support/Error.h"
34#include "llvm/Support/MD5.h"
39#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
43#include <cstring>
44#include <memory>
45#include <string>
46#include <system_error>
47#include <utility>
48#include <vector>
49
50namespace llvm {
51
52class Function;
53class GlobalVariable;
54struct InstrProfRecord;
55class InstrProfSymtab;
56class Instruction;
57class MDNode;
58class Module;
59
60// A struct to define how the data stream should be patched. For Indexed
61// profiling, only uint64_t data type is needed.
62struct PatchItem {
63 uint64_t Pos; // Where to patch.
64 ArrayRef<uint64_t> D; // An array of source data.
65};
66
67// A wrapper class to abstract writer stream with support of bytes
68// back patching.
70public:
73
74 [[nodiscard]] LLVM_ABI uint64_t tell() const;
79 // \c patch can only be called when all data is written and flushed.
80 // For raw_string_ostream, the patch is done on the target string
81 // directly and it won't be reflected in the stream's internal buffer.
83
84 // If \c OS is an instance of \c raw_fd_ostream, this field will be
85 // true. Otherwise, \c OS will be an raw_string_ostream.
89};
90
92#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
94};
96/// Return the max count value. We reserver a few large values for special use.
98 return std::numeric_limits<uint64_t>::max() - 2;
100
101/// Return the name of the profile section corresponding to \p IPSK.
102///
103/// The name of the section depends on the object format type \p OF. If
104/// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
105/// be added to the section name (this is the default).
108 bool AddSegmentInfo = true);
109
110/// Return the name profile runtime entry point to do value profiling
111/// for a given site.
116/// Return the name profile runtime entry point to do memop size value
117/// profiling.
121
122/// Return the prefix of the name of the variables to function as a filter.
123inline StringRef getInstrProfVarPrefix() { return "__prof"; }
124
125/// Return the name of the GPU wave-cooperative counter increment helper.
129
130/// Return the name prefix of variables containing instrumented function names.
131inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
132
133/// Return the name prefix of variables containing virtual table profile data.
134inline StringRef getInstrProfVTableVarPrefix() { return "__profvt_"; }
135
136/// Return the name prefix of variables containing per-function control data.
137inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
138
139/// Return the name prefix of profile counter variables.
140inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
141
142/// Return the name prefix of profile bitmap variables.
143inline StringRef getInstrProfBitmapVarPrefix() { return "__profbm_"; }
145/// Return the name prefix of value profile variables.
146inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
148/// Return the name of value profile node array variables:
149inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
150
151/// Return the name of the variable holding the strings (possibly compressed)
152/// of all function's PGO names.
153inline StringRef getInstrProfNamesVarName() { return "__llvm_prf_nm"; }
154
156 return "__llvm_prf_nm_postfix";
157}
158
159inline StringRef getInstrProfVTableNamesVarName() { return "__llvm_prf_vnm"; }
161/// Return the name of a covarage mapping variable (internal linkage)
162/// for each instrumented source module. Such variables are allocated
163/// in the __llvm_covmap section.
165 return "__llvm_coverage_mapping";
168/// Return the name of the internal variable recording the array
169/// of PGO name vars referenced by the coverage mapping. The owning
170/// functions of those names are not emitted by FE (e.g, unused inline
171/// functions.)
173 return "__llvm_coverage_names";
176/// Return the name of function that registers all the per-function control
177/// data at program startup time by calling __llvm_register_function. This
178/// function has internal linkage and is called by __llvm_profile_init
179/// runtime method. This function is not generated for these platforms:
180/// Darwin, Linux, and FreeBSD.
182 return "__llvm_profile_register_functions";
185/// Return the name of the runtime interface that registers per-function control
186/// data for one instrumented function.
188 return "__llvm_profile_register_function";
189}
190
191/// Return the name of the runtime interface that registers the PGO name
192/// strings.
194 return "__llvm_profile_register_names_function";
195}
196
197/// Return the name of the runtime initialization method that is generated by
198/// the compiler. The function calls __llvm_profile_register_functions and
199/// __llvm_profile_override_default_filename functions if needed. This function
200/// has internal linkage and invoked at startup time via init_array.
201inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
202
203/// Return the name of the hook variable defined in profile runtime library.
204/// A reference to the variable causes the linker to link in the runtime
205/// initialization module (which defines the hook variable).
209
210/// Return the name of the compiler generated function that references the
211/// runtime hook variable. The function is a weak global.
213 return "__llvm_profile_runtime_user";
214}
215
219
223
224/// Return the marker used to separate PGO names during serialization.
225inline StringRef getInstrProfNameSeparator() { return "\01"; }
226
227/// Determines whether module targets a GPU eligable for PGO
228/// instrumentation
229LLVM_ABI bool isGPUProfTarget(const Module &M);
230
231/// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
232/// for front-end (Clang, etc) instrumentation.
233/// Return the modified name for function \c F suitable to be
234/// used the key for profile lookup. Variable \c InLTO indicates if this
235/// is called in LTO optimization passes.
236LLVM_ABI std::string
237getPGOFuncName(const Function &F, bool InLTO = false,
239
240/// Return the modified name for a function suitable to be
241/// used the key for profile lookup. The function's original
242/// name is \c RawFuncName and has linkage of type \c Linkage.
243/// The function is defined in module \c FileName.
244LLVM_ABI std::string
246 StringRef FileName, uint64_t Version = INSTR_PROF_INDEX_VERSION);
247
248/// \return the modified name for function \c F suitable to be
249/// used as the key for IRPGO profile lookup. \c InLTO indicates if this is
250/// called from LTO optimization passes.
251LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO = false);
252
253/// \return the filename and the function name parsed from the output of
254/// \c getIRPGOFuncName()
255LLVM_ABI std::pair<StringRef, StringRef>
256getParsedIRPGOName(StringRef IRPGOName);
257
258/// Return the name of the global variable used to store a function
259/// name in PGO instrumentation. \c FuncName is the IRPGO function name
260/// (returned by \c getIRPGOFuncName) for LLVM IR instrumentation and PGO
261/// function name (returned by \c getPGOFuncName) for front-end instrumentation.
262LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName,
264
265/// Create and return the global variable for function name used in PGO
266/// instrumentation. \c FuncName is the IRPGO function name (returned by
267/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
268/// (returned by \c getPGOFuncName) for front-end instrumentation.
269LLVM_ABI GlobalVariable *createPGOFuncNameVar(Function &F,
270 StringRef PGOFuncName);
271
272/// Create and return the global variable for function name used in PGO
273/// instrumentation. \c FuncName is the IRPGO function name (returned by
274/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
275/// (returned by \c getPGOFuncName) for front-end instrumentation.
276LLVM_ABI GlobalVariable *createPGOFuncNameVar(Module &M,
278 StringRef PGOFuncName);
279
280/// Return the initializer in string of the PGO name var \c NameVar.
281LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
282
283/// Given a PGO function name, remove the filename prefix and return
284/// the original (static) function name.
285LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
286 StringRef FileName = "<unknown>");
287
288/// Given a vector of strings (names of global objects like functions or,
289/// virtual tables) \c NameStrs, the method generates a combined string \c
290/// Result that is ready to be serialized. The \c Result string is comprised of
291/// three fields: The first field is the length of the uncompressed strings, and
292/// the the second field is the length of the zlib-compressed string. Both
293/// fields are encoded in ULEB128. If \c doCompress is false, the
294/// third field is the uncompressed strings; otherwise it is the
295/// compressed string. When the string compression is off, the
296/// second field will have value zero.
297LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
298 bool doCompression,
299 std::string &Result);
300
301/// Produce \c Result string with the same format described above. The input
302/// is vector of PGO function name variables that are referenced.
303/// The global variable element in 'NameVars' is a string containing the pgo
304/// name of a function. See `createPGOFuncNameVar` that creates these global
305/// variables.
307 std::string &Result,
308 bool doCompression = true);
309
311 std::string &Result, bool doCompression);
312
313/// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
314/// set in IR PGO compilation.
315LLVM_ABI bool isIRPGOFlagSet(const Module *M);
316
317/// Check if we can safely rename this Comdat function. Instances of the same
318/// comdat function may have different control flows thus can not share the
319/// same counter variable.
320LLVM_ABI bool canRenameComdatFunc(const Function &F,
321 bool CheckAddressTaken = false);
322
324#define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
326};
327
328/// Get the value profile data for value site \p SiteIdx from \p InstrProfR
329/// and annotate the instruction \p Inst with the value profile meta data.
330/// Annotate up to \p MaxMDCount (default 3) number of records per value site.
332 const InstrProfRecord &InstrProfR,
333 InstrProfValueKind ValueKind, uint32_t SiteIndx,
334 uint32_t MaxMDCount = 3);
335
336/// Same as the above interface but using an ArrayRef, as well as \p Sum.
337/// This function will not annotate !prof metadata on the instruction if the
338/// referenced array is empty.
340 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
341 InstrProfValueKind ValueKind,
342 uint32_t MaxMDCount);
343
344// TODO: Unify metadata name 'PGOFuncName' and 'PGOName', by supporting read
345// of this metadata for backward compatibility and generating 'PGOName' only.
346/// Extract the value profile data from \p Inst and returns them if \p Inst is
347/// annotated with value profile data. Returns an empty vector otherwise.
350 uint32_t MaxNumValueData, uint64_t &TotalC,
351 bool GetNoICPValue = false);
352
353inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
354
355inline StringRef getPGONameMetadataName() { return "PGOName"; }
356
357/// Return the PGOFuncName meta data associated with a function.
358LLVM_ABI MDNode *getPGOFuncNameMetadata(const Function &F);
359
360LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO = false);
361
362/// Create the PGOFuncName meta data if PGOFuncName is different from
363/// function's raw name. This should only apply to internal linkage functions
364/// declared by users only.
365/// TODO: Update all callers to 'createPGONameMetadata' and deprecate this
366/// function.
367LLVM_ABI void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
368
369/// Create the PGOName metadata if a global object's PGO name is different from
370/// its mangled name. This should apply to local-linkage global objects only.
371LLVM_ABI void createPGONameMetadata(GlobalObject &GO, StringRef PGOName);
372
373/// Check if we can use Comdat for profile variables. This will eliminate
374/// the duplicated profile variables for Comdat functions.
375LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M);
376
377/// \c NameStrings is a string composed of one or more possibly encoded
378/// sub-strings. The substrings are separated by `\01` (returned by
379/// InstrProf.h:getInstrProfNameSeparator). This method decodes the string and
380/// calls `NameCallback` for each substring.
382 StringRef NameStrings, std::function<Error(StringRef)> NameCallback);
383
384/// An enum describing the attributes of an instrumented profile.
385enum class InstrProfKind {
386 Unknown = 0x0,
387 // A frontend clang profile, incompatible with other attrs.
389 // An IR-level profile (default when -fprofile-generate is used).
391 // A profile with entry basic block instrumentation.
393 // A context sensitive IR-level profile.
395 // Use single byte probes for coverage.
397 // Only instrument the function entry basic block.
399 // A memory profile collected using -fprofile=memory.
400 MemProf = 0x40,
401 // A temporal profile.
403 // A profile with loop entry basic blocks instrumentation.
406};
407
408LLVM_ABI const std::error_category &instrprof_category();
409
438
439/// An ordered list of functions identified by their NameRef found in
440/// INSTR_PROF_DATA
442 std::vector<uint64_t> FunctionNameRefs;
444 TemporalProfTraceTy(std::initializer_list<uint64_t> Trace = {},
445 uint64_t Weight = 1)
447
448 /// Use a set of temporal profile traces to create a list of balanced
449 /// partitioning function nodes used by BalancedPartitioning to generate a
450 /// function order that reduces page faults during startup
451 LLVM_ABI static void
453 std::vector<BPFunctionNode> &Nodes,
454 bool RemoveOutlierUNs = true);
455};
456
457inline std::error_code make_error_code(instrprof_error E) {
458 return std::error_code(static_cast<int>(E), instrprof_category());
459}
460
461class LLVM_ABI InstrProfError : public ErrorInfo<InstrProfError> {
462public:
464 : Err(Err), Msg(ErrStr.str()) {
465 assert(Err != instrprof_error::success && "Not an error");
466 }
467
468 std::string message() const override;
469
470 void log(raw_ostream &OS) const override { OS << message(); }
471
472 std::error_code convertToErrorCode() const override {
473 return make_error_code(Err);
474 }
475
476 instrprof_error get() const { return Err; }
477 const std::string &getMessage() const { return Msg; }
478
479 /// Consume an Error and return the raw enum value contained within it, and
480 /// the optional error message. The Error must either be a success value, or
481 /// contain a single InstrProfError.
482 static std::pair<instrprof_error, std::string> take(Error E) {
483 auto Err = instrprof_error::success;
484 std::string Msg = "";
485 handleAllErrors(std::move(E), [&Err, &Msg](const InstrProfError &IPE) {
486 assert(Err == instrprof_error::success && "Multiple errors encountered");
487 Err = IPE.get();
488 Msg = IPE.getMessage();
489 });
490 return {Err, Msg};
492
493 static char ID;
494
495private:
496 instrprof_error Err;
497 std::string Msg;
498};
499
500namespace object {
501
502class SectionRef;
503
504} // end namespace object
505
507
509
510} // end namespace IndexedInstrProf
511
512/// A symbol table used for function [IR]PGO name look-up with keys
513/// (such as pointers, md5hash values) to the function. A function's
514/// [IR]PGO name or name's md5hash are used in retrieving the profile
515/// data of the function. See \c getIRPGOFuncName() and \c getPGOFuncName
516/// methods for details how [IR]PGO name is formed.
518public:
519 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
520
521 // Returns the canonical name of the given PGOName. This shares the same
522 // logic of FunctionSamples::getCanonicalFnName() but only strips ".llvm."
523 // and ".part", and leaves out ".__uniq.".
525
526private:
527 using AddrIntervalMap =
529 StringRef Data;
530 uint64_t Address = 0;
531 // Unique name strings. Used to ensure entries in MD5NameMap (a vector that's
532 // going to be sorted) has unique MD5 keys in the first place.
533 StringSet<> NameTab;
534 // Records the unique virtual table names. This is used by InstrProfWriter to
535 // write out an on-disk chained hash table of virtual table names.
536 // InstrProfWriter stores per function profile data (keyed by function names)
537 // so it doesn't use a StringSet for function names.
538 StringSet<> VTableNames;
539 // A map from MD5 keys to function name strings.
540 mutable std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
541 // A map from MD5 keys to function define. We only populate this map
542 // when build the Symtab from a Module.
543 mutable std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
544 // A map from MD5 to the global variable. This map is only populated when
545 // building the symtab from a module. Use separate container instances for
546 // `MD5FuncMap` and `MD5VTableMap`.
547 // TODO: Unify the container type and the lambda function 'mapName' inside
548 // add{Func,VTable}WithName.
549 mutable DenseMap<uint64_t, GlobalVariable *> MD5VTableMap;
550 // A map from function runtime address to function name MD5 hash.
551 // This map is only populated and used by raw instr profile reader.
552 mutable AddrHashMap AddrToMD5Map;
553
554 AddrIntervalMap::Allocator VTableAddrMapAllocator;
555 // This map is only populated and used by raw instr profile reader.
556 AddrIntervalMap VTableAddrMap;
557
558 // "dirty" flag for the rest of the mutable state. lookup APIs (like
559 // getFunction) need the mutable state to be sorted.
560 mutable bool Sorted = false;
562 static StringRef getExternalSymbol() { return "** External Symbol **"; }
564 // Add the function into the symbol table, by creating the following
565 // map entries:
566 // name-set = {PGOFuncName} union {getCanonicalName(PGOFuncName)}
567 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
568 // - In MD5FuncMap: <MD5Hash(name), &F> for name in name-set
569 // The canonical name is only added if \c AddCanonical is true.
570 Error addFuncWithName(Function &F, StringRef PGOFuncName, bool AddCanonical);
571
572 // Add the vtable into the symbol table, by creating the following
573 // map entries:
574 // name-set = {PGOName} union {getCanonicalName(PGOName)}
575 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
576 // - In MD5VTableMap: <MD5Hash(name), name> for name in name-set
577 Error addVTableWithName(GlobalVariable &V, StringRef PGOVTableName);
578
579 // If the symtab is created by a series of calls to \c addFuncName, \c
580 // finalizeSymtab needs to be called before looking up function names.
581 // This is required because the underlying map is a vector (for space
582 // efficiency) which needs to be sorted. The API is `const` because it's part
583 // of the implementation detail of `const` APIs that need to first ensure this
584 // property of ordering on the other mutable state.
585 inline void finalizeSymtab() const;
586
587public:
588 InstrProfSymtab() : VTableAddrMap(VTableAddrMapAllocator) {}
589
590 // Not copyable or movable.
591 // Consider std::unique_ptr for move.
596
597 /// Create InstrProfSymtab from an object file section which
598 /// contains function PGO names. When section may contain raw
599 /// string data or string data in compressed form. This method
600 /// only initialize the symtab with reference to the data and
601 /// the section base address. The decompression will be delayed
602 /// until before it is used. See also \c create(StringRef) method.
604
605 /// \c NameStrings is a string composed of one of more sub-strings
606 /// encoded in the format described in \c collectPGOFuncNameStrings.
607 /// This method is a wrapper to \c readAndDecodeStrings method.
608 LLVM_ABI Error create(StringRef NameStrings);
609
610 /// Initialize symtab states with function names and vtable names. \c
611 /// FuncNameStrings is a string composed of one or more encoded function name
612 /// strings, and \c VTableNameStrings composes of one or more encoded vtable
613 /// names. This interface is solely used by raw profile reader.
614 LLVM_ABI Error create(StringRef FuncNameStrings, StringRef VTableNameStrings);
615
616 /// Initialize 'this' with the set of vtable names encoded in
617 /// \c CompressedVTableNames.
619 initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames);
620
621 /// This interface is used by reader of CoverageMapping test
622 /// format.
623 inline Error create(StringRef D, uint64_t BaseAddr);
624
625 /// A wrapper interface to populate the PGO symtab with functions
626 /// decls from module \c M. This interface is used by transformation
627 /// passes such as indirect function call promotion. Variable \c InLTO
628 /// indicates if this is called from LTO optimization passes.
629 /// A canonical name, removing non-__uniq suffixes, is added if
630 /// \c AddCanonical is true.
631 LLVM_ABI Error create(Module &M, bool InLTO = false,
632 bool AddCanonical = true);
633
634 /// Create InstrProfSymtab from a set of names iteratable from
635 /// \p IterRange. This interface is used by IndexedProfReader.
636 template <typename NameIterRange>
637 Error create(const NameIterRange &IterRange);
638
639 /// Create InstrProfSymtab from a set of function names and vtable
640 /// names iteratable from \p IterRange. This interface is used by
641 /// IndexedProfReader.
642 template <typename FuncNameIterRange, typename VTableNameIterRange>
643 Error create(const FuncNameIterRange &FuncIterRange,
644 const VTableNameIterRange &VTableIterRange);
645
646 // Map the MD5 of the symbol name to the name.
648 if (SymbolName.empty())
650 "symbol name is empty");
651
652 // Insert into NameTab so that MD5NameMap (a vector that will be sorted)
653 // won't have duplicated entries in the first place.
654 auto Ins = NameTab.insert(SymbolName);
655 if (Ins.second) {
656 MD5NameMap.push_back(std::make_pair(
657 IndexedInstrProf::ComputeHash(SymbolName), Ins.first->getKey()));
658 Sorted = false;
659 }
660 return Error::success();
661 }
662
663 /// The method name is kept since there are many callers.
664 /// It just forwards to 'addSymbolName'.
665 Error addFuncName(StringRef FuncName) { return addSymbolName(FuncName); }
666
667 /// Adds VTableName as a known symbol, and inserts it to a map that
668 /// tracks all vtable names.
670 if (Error E = addSymbolName(VTableName))
671 return E;
672
673 // Record VTableName. InstrProfWriter uses this set. The comment around
674 // class member explains why.
675 VTableNames.insert(VTableName);
676 return Error::success();
677 }
678
679 const std::vector<std::pair<uint64_t, Function *>> &getIDToNameMap() const {
680 return MD5FuncMap;
681 }
682
683 const StringSet<> &getVTableNames() const { return VTableNames; }
684
685 /// Map a function address to its name's MD5 hash. This interface
686 /// is only used by the raw profiler reader.
687 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
688 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
689 }
690
691 /// Map the address range (i.e., [start_address, end_address)) of a variable
692 /// to its names' MD5 hash. This interface is only used by the raw profile
693 /// reader.
694 void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val) {
695 VTableAddrMap.insert(StartAddr, EndAddr, MD5Val);
696 }
697
698 /// Return a function's hash, or 0, if the function isn't in this SymTab.
700
701 /// Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
703
704 /// Return function's PGO name from the function name's symbol
705 /// address in the object file. If an error occurs, return
706 /// an empty string.
707 LLVM_ABI StringRef getFuncName(uint64_t FuncNameAddress,
708 size_t NameSize) const;
709
710 /// Return name of functions or global variables from the name's md5 hash
711 /// value. If not found, return an empty string.
712 inline StringRef getFuncOrVarName(uint64_t ValMD5Hash) const;
713
714 /// Just like getFuncOrVarName, except that it will return literal string
715 /// 'External Symbol' if the function or global variable is external to
716 /// this symbol table.
717 inline StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash) const;
718
719 /// True if Symbol is the value used to represent external symbols.
720 static bool isExternalSymbol(const StringRef &Symbol) {
721 return Symbol == InstrProfSymtab::getExternalSymbol();
722 }
723
724 /// Return function from the name's md5 hash. Return nullptr if not found.
725 inline Function *getFunction(uint64_t FuncMD5Hash) const;
726
727 /// Return the global variable corresponding to md5 hash. Return nullptr if
728 /// not found.
730
731 /// Return the name section data.
732 inline StringRef getNameData() const { return Data; }
733
734 /// Dump the symbols in this table.
735 LLVM_ABI void dumpNames(raw_ostream &OS) const;
736};
737
739 Data = D;
740 Address = BaseAddr;
741 return Error::success();
742}
743
744template <typename NameIterRange>
745Error InstrProfSymtab::create(const NameIterRange &IterRange) {
746 for (auto Name : IterRange)
747 if (Error E = addFuncName(Name))
748 return E;
749
750 finalizeSymtab();
751 return Error::success();
752}
753
754template <typename FuncNameIterRange, typename VTableNameIterRange>
755Error InstrProfSymtab::create(const FuncNameIterRange &FuncIterRange,
756 const VTableNameIterRange &VTableIterRange) {
757 // Iterate elements by StringRef rather than by const reference.
758 // StringRef is small enough, so the loop is efficient whether
759 // element in the range is std::string or StringRef.
760 for (StringRef Name : FuncIterRange)
761 if (Error E = addFuncName(Name))
762 return E;
763
764 for (StringRef VTableName : VTableIterRange)
765 if (Error E = addVTableName(VTableName))
766 return E;
767
768 finalizeSymtab();
769 return Error::success();
770}
771
772void InstrProfSymtab::finalizeSymtab() const {
773 if (Sorted)
774 return;
775 llvm::sort(MD5NameMap, less_first());
776 llvm::stable_sort(MD5FuncMap, less_first());
777 llvm::sort(AddrToMD5Map, less_first());
778 AddrToMD5Map.erase(llvm::unique(AddrToMD5Map), AddrToMD5Map.end());
779 Sorted = true;
780}
781
784 if (Ret.empty())
785 return InstrProfSymtab::getExternalSymbol();
786 return Ret;
787}
788
790 finalizeSymtab();
791 auto Result = llvm::lower_bound(MD5NameMap, MD5Hash,
792 [](const std::pair<uint64_t, StringRef> &LHS,
793 uint64_t RHS) { return LHS.first < RHS; });
794 if (Result != MD5NameMap.end() && Result->first == MD5Hash)
795 return Result->second;
796 return StringRef();
797}
798
800 finalizeSymtab();
801 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
802 [](const std::pair<uint64_t, Function *> &LHS,
803 uint64_t RHS) { return LHS.first < RHS; });
804 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
805 return Result->second;
806 return nullptr;
807}
808
810 return MD5VTableMap.lookup(MD5Hash);
811}
812
813// To store the sums of profile count values, or the percentage of
814// the sums of the total count values.
817 double CountSum = 0.0f;
818 std::array<double, IPVK_Last - IPVK_First + 1> ValueCounts = {};
819 CountSumOrPercent() = default;
820 void reset() {
821 NumEntries = 0;
822 CountSum = 0.0f;
823 ValueCounts.fill(0.0f);
824 }
825};
826
827// Function level or program level overlap information.
830 // Sum of the total count values for the base profile.
832 // Sum of the total count values for the test profile.
834 // Overlap lap score. Should be in range of [0.0f to 1.0f].
839 const std::string *BaseFilename = nullptr;
840 const std::string *TestFilename = nullptr;
843 bool Valid = false;
844
846
847 LLVM_ABI void dump(raw_fd_ostream &OS) const;
848
849 void setFuncInfo(StringRef Name, uint64_t Hash) {
850 FuncName = Name;
851 FuncHash = Hash;
852 }
853
854 LLVM_ABI Error accumulateCounts(const std::string &BaseFilename,
855 const std::string &TestFilename, bool IsCS);
856 LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc);
857 LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc);
858
859 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
860 double Sum2) {
861 if (Sum1 < 1.0f || Sum2 < 1.0f)
862 return 0.0f;
863 return std::min(Val1 / Sum1, Val2 / Sum2);
864 }
865};
866
867// This is used to filter the functions whose overlap information
868// to be output.
873
875 /// Value profiling data pairs at a given value site.
876 std::vector<InstrProfValueData> ValueData;
877
879 InstrProfValueSiteRecord(std::vector<InstrProfValueData> &&VD)
880 : ValueData(VD) {}
881
882 /// Sort ValueData ascending by Value
885 [](const InstrProfValueData &L, const InstrProfValueData &R) {
886 return L.Value < R.Value;
887 });
888 }
889 /// Sort ValueData Descending by Count
890 inline void sortByCount();
891
892 /// Merge data from another InstrProfValueSiteRecord
893 /// Optionally scale merged counts by \p Weight.
895 function_ref<void(instrprof_error)> Warn);
896 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
898 function_ref<void(instrprof_error)> Warn);
899
900 /// Compute the overlap b/w this record and Input record.
902 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
903};
904
905/// Profiling information for a single function.
907 std::vector<uint64_t> Counts;
908 std::vector<uint8_t> BitmapBytes;
909 /// For AMDGPU offload profiling: raw or merged uniform counters. One uint64_t
910 /// per instrumented block, tracking entries where all lanes were active.
911 std::vector<uint64_t> UniformCounts;
912 /// For AMDGPU offload profiling: 1 bit per basic block indicating whether
913 /// the block is usually entered with all lanes active. Raw uniform counters
914 /// are reduced to these bits when profiles are written or merged.
915 std::vector<uint8_t> UniformityBits;
917
918 InstrProfRecord() = default;
919 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
920 InstrProfRecord(std::vector<uint64_t> Counts,
921 std::vector<uint8_t> BitmapBytes)
928 ValueData(RHS.ValueData
929 ? std::make_unique<ValueProfData>(*RHS.ValueData)
930 : nullptr) {}
933 Counts = RHS.Counts;
934 BitmapBytes = RHS.BitmapBytes;
935 UniformCounts = RHS.UniformCounts;
936 UniformityBits = RHS.UniformityBits;
937 OffloadDeviceWaveSize = RHS.OffloadDeviceWaveSize;
938 if (!RHS.ValueData) {
939 ValueData = nullptr;
940 return *this;
941 }
942 if (!ValueData)
943 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
944 else
945 *ValueData = *RHS.ValueData;
946 return *this;
947 }
948
949 /// Check if a basic block is entered via a wave-uniform branch.
950 /// Returns true if uniform (safe for PGO spill optimization) or if no
951 /// uniformity data is available (conservative default).
952 bool isBlockUniform(unsigned BlockIdx) const {
953 if (UniformityBits.empty())
954 return true; // No uniformity data, assume uniform (conservative)
955 if (BlockIdx / 8 >= UniformityBits.size())
956 return true; // Out of range, assume uniform
957 return (UniformityBits[BlockIdx / 8] >> (BlockIdx % 8)) & 1;
958 }
959
960 /// Recompute uniformity metadata from raw uniform counters, when present.
962
963 /// Return the number of value profile kinds with non-zero number
964 /// of profile sites.
965 inline uint32_t getNumValueKinds() const;
966 /// Return the number of instrumented sites for ValueKind.
967 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
968
969 /// Return the total number of ValueData for ValueKind.
970 inline uint32_t getNumValueData(uint32_t ValueKind) const;
971
972 /// Return the array of profiled values at \p Site.
974 uint32_t Site) const;
975
976 /// Reserve space for NumValueSites sites.
977 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
978
979 /// Add ValueData for ValueKind at value Site. We do not support adding sites
980 /// out of order. Site must go up from 0 one by one.
981 LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site,
983 InstrProfSymtab *SymTab);
984
985 /// Merge the counts in \p Other into this one.
986 /// Optionally scale merged counts by \p Weight.
988 function_ref<void(instrprof_error)> Warn);
989
990 /// Scale up profile counts (including value profile data) by
991 /// a factor of (N / D).
993 function_ref<void(instrprof_error)> Warn);
994
995 /// Sort value profile data (per site) by count.
997 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
998 for (auto &SR : getValueSitesForKind(Kind))
999 SR.sortByCount();
1000 }
1001
1002 /// Clear value data entries, edge counters, and uniformity data.
1003 void Clear() {
1004 Counts.clear();
1005 UniformCounts.clear();
1006 UniformityBits.clear();
1009 }
1010
1011 /// Clear value data entries
1012 void clearValueData() { ValueData = nullptr; }
1013
1014 /// Compute the sums of all counts and store in Sum.
1016
1017 /// Compute the overlap b/w this IntrprofRecord and Other.
1019 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
1020
1021 /// Compute the overlap of value profile counts.
1023 OverlapStats &Overlap,
1024 OverlapStats &FuncLevelOverlap);
1025
1036 uint64_t FirstCount = Counts[0];
1037 if (FirstCount == (uint64_t)HotFunctionVal)
1038 return PseudoHot;
1039 if (FirstCount == (uint64_t)WarmFunctionVal)
1040 return PseudoWarm;
1041 return NotPseudo;
1042 }
1044 if (Kind == PseudoHot)
1046 else if (Kind == PseudoWarm)
1048 }
1049
1050private:
1051 using ValueProfData = std::array<std::vector<InstrProfValueSiteRecord>,
1052 IPVK_Last - IPVK_First + 1>;
1053 std::unique_ptr<ValueProfData> ValueData;
1054
1056 getValueSitesForKind(uint32_t ValueKind) {
1057 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
1058 // implemented in LLVM) to call the const overload of this function, then
1059 // cast away the constness from the result.
1060 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
1061 ValueKind);
1062 return MutableArrayRef(
1063 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
1064 }
1066 getValueSitesForKind(uint32_t ValueKind) const {
1067 if (!ValueData)
1068 return {};
1069 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
1070 "Unknown value kind!");
1071 return (*ValueData)[ValueKind - IPVK_First];
1072 }
1073
1074 std::vector<InstrProfValueSiteRecord> &
1075 getOrCreateValueSitesForKind(uint32_t ValueKind) {
1076 if (!ValueData)
1077 ValueData = std::make_unique<ValueProfData>();
1078 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
1079 "Unknown value kind!");
1080 return (*ValueData)[ValueKind - IPVK_First];
1081 }
1082
1083 // Map indirect call target name hash to name string.
1084 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
1085 InstrProfSymtab *SymTab);
1086
1087 // Merge Value Profile data from Src record to this record for ValueKind.
1088 // Scale merged value counts by \p Weight.
1089 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
1090 uint64_t Weight,
1091 function_ref<void(instrprof_error)> Warn);
1092
1093 // Scale up value profile data count by N (Numerator) / D (Denominator).
1094 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
1095 function_ref<void(instrprof_error)> Warn);
1096};
1097
1101
1102 // We reserve the highest 4 bits as flags.
1103 static constexpr uint64_t FUNC_HASH_MASK = 0x0FFF'FFFF'FFFF'FFFF;
1104 // The 60th bit is for context sensitive profile record.
1105 static constexpr unsigned CS_FLAG_IN_FUNC_HASH = 60;
1106
1112 std::vector<uint64_t> Counts,
1113 std::vector<uint8_t> BitmapBytes)
1115 Hash(Hash) {}
1117 std::vector<uint64_t> Counts,
1118 std::vector<uint8_t> BitmapBytes,
1119 std::vector<uint8_t> UniformityBits)
1121 Hash(Hash) {
1122 this->UniformityBits = std::move(UniformityBits);
1123 }
1124
1126 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
1127 }
1131};
1132
1134 uint32_t NumValueKinds = 0;
1135 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1136 NumValueKinds += !(getValueSitesForKind(Kind).empty());
1137 return NumValueKinds;
1138}
1139
1141 uint32_t N = 0;
1142 for (const auto &SR : getValueSitesForKind(ValueKind))
1143 N += SR.ValueData.size();
1144 return N;
1145}
1146
1148 return getValueSitesForKind(ValueKind).size();
1149}
1150
1153 return getValueSitesForKind(ValueKind)[Site].ValueData;
1154}
1155
1157 if (!NumValueSites)
1158 return;
1159 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
1160}
1161
1162// Include definitions for value profile data
1163#define INSTR_PROF_VALUE_PROF_DATA
1165
1168 ValueData, [](const InstrProfValueData &L, const InstrProfValueData &R) {
1169 return L.Count > R.Count;
1170 });
1171 // Now truncate
1172 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
1173 if (ValueData.size() > max_s)
1174 ValueData.resize(max_s);
1175}
1176
1177namespace IndexedInstrProf {
1178
1179enum class HashT : uint32_t {
1182};
1183
1185 switch (Type) {
1186 case HashT::MD5:
1187 return MD5Hash(K);
1188 }
1189 llvm_unreachable("Unhandled hash type");
1190}
1191
1192const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
1193
1195 // Version 1 is the first version. In this version, the value of
1196 // a key/value pair can only include profile data of a single function.
1197 // Due to this restriction, the number of block counters for a given
1198 // function is not recorded but derived from the length of the value.
1200 // The version 2 format supports recording profile data of multiple
1201 // functions which share the same key in one value field. To support this,
1202 // the number block counters is recorded as an uint64_t field right after the
1203 // function structural hash.
1205 // Version 3 supports value profile data. The value profile data is expected
1206 // to follow the block counter profile data.
1208 // In this version, profile summary data \c IndexedInstrProf::Summary is
1209 // stored after the profile header.
1211 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1213 // In this version, the frontend PGO stable hash algorithm got fixed and
1214 // may produce hashes different from Version5.
1216 // An additional counter is added around logical operators.
1218 // An additional (optional) memory profile type is added.
1220 // Binary ids are added.
1222 // An additional (optional) temporal profile traces section is added.
1224 // An additional field is used for bitmap bytes.
1226 // VTable profiling, decision record and bitmap are modified for mcdc.
1228 // In this version, the frontend PGO stable hash algorithm defaults to V4.
1230 // UniformityBits added for AMDGPU offload profiling divergence detection.
1232 // The current version is 14.
1234};
1236
1238
1240
1241// This structure defines the file header of the LLVM profile
1242// data file in indexed-format. Please update llvm/docs/InstrProfileFormat.md
1243// as appropriate when updating the indexed profile format.
1244struct Header {
1246 // The lower 32 bits specify the version of the indexed profile.
1247 // The most significant 32 bits are reserved to specify the variant types of
1248 // the profile.
1250 uint64_t Unused = 0; // Becomes unused since version 4
1252 // This field records the offset of this hash table's metadata (i.e., the
1253 // number of buckets and entries), which follows right after the payload of
1254 // the entire hash table.
1260 // New fields should only be added at the end to ensure that the size
1261 // computation is correct. The methods below need to be updated to ensure that
1262 // the new field is read correctly.
1263
1264 // Reads a header struct from the buffer. Header fields are in machine native
1265 // endianness.
1266 LLVM_ABI static Expected<Header> readFromBuffer(const unsigned char *Buffer);
1267
1268 // Returns the size of the header in bytes for all valid fields based on the
1269 // version. I.e a older version header will return a smaller size.
1270 LLVM_ABI size_t size() const;
1271
1272 // Return the indexed profile version, i.e., the least significant 32 bits
1273 // in Header.Version.
1275};
1276
1277// Profile summary data recorded in the profile data file in indexed
1278// format. It is introduced in version 4. The summary data follows
1279// right after the profile file header.
1280struct Summary {
1281 struct Entry {
1282 uint64_t Cutoff; ///< The required percentile of total execution count.
1283 uint64_t
1284 MinBlockCount; ///< The minimum execution count for this percentile.
1285 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1286 };
1287 // The field kind enumerator to assigned value mapping should remain
1288 // unchanged when a new kind is added or an old kind gets deleted in
1289 // the future.
1291 /// The total number of functions instrumented.
1293 /// Total number of instrumented blocks/edges.
1295 /// The maximal execution count among all functions.
1296 /// This field does not exist for profile data from IR based
1297 /// instrumentation.
1299 /// Max block count of the program.
1301 /// Max internal block count of the program (excluding entry blocks).
1303 /// The sum of all instrumented block counts.
1306 };
1307
1308 // The number of summmary fields following the summary header.
1310 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1312
1313 Summary() = delete;
1314 Summary(uint32_t Size) { memset(this, 0, Size); }
1315
1316 void operator delete(void *ptr) { ::operator delete(ptr); }
1317
1319 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1320 NumSumFields * sizeof(uint64_t);
1321 }
1322
1324 return reinterpret_cast<const uint64_t *>(this + 1);
1325 }
1326
1328 return reinterpret_cast<uint64_t *>(this + 1);
1329 }
1330
1331 const Entry *getCutoffEntryBase() const {
1332 return reinterpret_cast<const Entry *>(
1334 }
1335
1337 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1338 }
1339
1341 return getSummaryDataBase()[K];
1342 }
1343
1345 getSummaryDataBase()[K] = V;
1346 }
1347
1348 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1349
1351 Entry &ER = getCutoffEntryBase()[I];
1352 ER.Cutoff = E.Cutoff;
1353 ER.MinBlockCount = E.MinCount;
1354 ER.NumBlocks = E.NumCounts;
1355 }
1356};
1357
1358inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1359 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1360 Summary(TotalSize));
1361}
1362
1363} // end namespace IndexedInstrProf
1364
1365namespace RawInstrProf {
1366
1367// Version 1: First version
1368// Version 2: Added value profile data section. Per-function control data
1369// struct has more fields to describe value profile information.
1370// Version 3: Compressed name section support. Function PGO name reference
1371// from control data struct is changed from raw pointer to Name's MD5 value.
1372// Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1373// raw header.
1374// Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1375// sensitive records.
1376// Version 6: Added binary id.
1377// Version 7: Reorder binary id and include version in signature.
1378// Version 8: Use relative counter pointer.
1379// Version 9: Added relative bitmap bytes pointer and count used by MC/DC.
1380// Version 10: Added vtable, a new type of value profile data.
1382
1383template <class IntPtrT> inline uint64_t getMagic();
1384template <> inline uint64_t getMagic<uint64_t>() {
1386}
1387
1388template <> inline uint64_t getMagic<uint32_t>() {
1390}
1391
1392// Per-function profile data header/control structure.
1393// The definition should match the structure defined in
1394// compiler-rt/lib/profile/InstrProfiling.h.
1395// It should also match the synthesized type in
1396// Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1397template <class IntPtrT> struct alignas(8) ProfileData {
1398#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1400};
1401
1402template <class IntPtrT> struct alignas(8) VTableProfileData {
1403#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Type Name;
1405};
1406
1407// File header structure of the LLVM profile data in raw format.
1408// The definition should match the header referenced in
1409// compiler-rt/lib/profile/InstrProfilingFile.c and
1410// InstrProfilingBuffer.c.
1411struct Header {
1412#define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1414};
1415
1416} // end namespace RawInstrProf
1417
1418// Create the variable for the profile file name.
1419LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1420
1421// Whether to compress function names in profile records, and filenames in
1422// code coverage mappings. Used by the Instrumentation library and unit tests.
1424
1425} // end namespace llvm
1426#endif // LLVM_PROFILEDATA_INSTRPROF_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
DXIL Finalize Linkage
This file defines the DenseMap class.
#define INSTR_PROF_QUOTE(x)
#define INSTR_PROF_INSTRUMENT_GPU_FUNC_STR
#define INSTR_PROF_RAW_MAGIC_32
#define INSTR_PROF_MAX_NUM_VAL_PER_SITE
#define INSTR_PROF_RAW_VERSION
#define INSTR_PROF_PROFILE_BITMAP_BIAS_VAR
#define INSTR_PROF_INDEX_VERSION
#define INSTR_PROF_PROFILE_COUNTER_BIAS_VAR
#define INSTR_PROF_VALUE_PROF_FUNC_STR
#define INSTR_PROF_RAW_MAGIC_64
#define INSTR_PROF_PROFILE_RUNTIME_VAR
#define INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR
This file implements a coalescing interval map for small objects.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
StringSet - A set-like wrapper for the StringMap.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for user error types.
Definition Error.h:354
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition InstrProf.h:470
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition InstrProf.h:482
const std::string & getMessage() const
Definition InstrProf.h:477
instrprof_error get() const
Definition InstrProf.h:476
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition InstrProf.h:472
std::string message() const override
Return the error message as a string.
InstrProfError(instrprof_error Err, const Twine &ErrStr=Twine())
Definition InstrProf.h:463
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:517
StringRef getFuncOrVarName(uint64_t ValMD5Hash) const
Return name of functions or global variables from the name's md5 hash value.
Definition InstrProf.h:789
static LLVM_ABI StringRef getCanonicalName(StringRef PGOName)
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition InstrProf.h:720
const std::vector< std::pair< uint64_t, Function * > > & getIDToNameMap() const
Definition InstrProf.h:679
Error addSymbolName(StringRef SymbolName)
Definition InstrProf.h:647
LLVM_ABI StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize) const
Return function's PGO name from the function name's symbol address in the object file.
InstrProfSymtab & operator=(InstrProfSymtab &&)=delete
GlobalVariable * getGlobalVariable(uint64_t MD5Hash) const
Return the global variable corresponding to md5 hash.
Definition InstrProf.h:809
StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash) const
Just like getFuncOrVarName, except that it will return literal string 'External Symbol' if the functi...
Definition InstrProf.h:782
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition InstrProf.h:687
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
Definition InstrProf.h:669
std::vector< std::pair< uint64_t, uint64_t > > AddrHashMap
Definition InstrProf.h:519
LLVM_ABI void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
StringRef getNameData() const
Return the name section data.
Definition InstrProf.h:732
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
The method name is kept since there are many callers.
Definition InstrProf.h:665
void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val)
Map the address range (i.e., [start_address, end_address)) of a variable to its names' MD5 hash.
Definition InstrProf.h:694
LLVM_ABI Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
const StringSet & getVTableNames() const
Definition InstrProf.h:683
LLVM_ABI uint64_t getVTableHashFromAddress(uint64_t Address) const
Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
Function * getFunction(uint64_t FuncMD5Hash) const
Return function from the name's md5 hash. Return nullptr if not found.
Definition InstrProf.h:799
InstrProfSymtab & operator=(const InstrProfSymtab &)=delete
InstrProfSymtab(InstrProfSymtab &&)=delete
InstrProfSymtab(const InstrProfSymtab &)=delete
LLVM_ABI uint64_t getFunctionHashFromAddress(uint64_t Address) const
Return a function's hash, or 0, if the function isn't in this SymTab.
Metadata node.
Definition Metadata.h:1069
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
raw_ostream & OS
Definition InstrProf.h:87
LLVM_ABI uint64_t tell() const
LLVM_ABI void writeByte(uint8_t V)
LLVM_ABI void patch(ArrayRef< PatchItem > P)
LLVM_ABI void write32(uint32_t V)
support::endian::Writer LE
Definition InstrProf.h:88
LLVM_ABI ProfOStream(raw_fd_ostream &FD)
LLVM_ABI void write(uint64_t V)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
An efficient, type-erasing, non-owning reference to a callable.
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
Definition InstrProf.h:1358
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1239
const uint64_t Version
Definition InstrProf.h:1235
const uint64_t Magic
Definition InstrProf.h:1192
uint64_t getMagic()
const uint64_t Version
Definition InstrProf.h:1381
uint64_t getMagic< uint32_t >()
Definition InstrProf.h:1388
uint64_t getMagic< uint64_t >()
Definition InstrProf.h:1384
constexpr size_t NameSize
Definition XCOFF.h:30
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
Definition STLExtras.h:2116
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition InstrProf.h:131
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOFuncName for LLVM IR instrumentation.
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition InstrProf.h:206
LLVM_ABI void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO=false)
std::error_code make_error_code(BitcodeError E)
StringRef getPGOFuncNameMetadataName()
Definition InstrProf.h:353
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
Definition InstrProf.h:164
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition InstrProf.h:143
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
LLVM_ABI void createPGONameMetadata(GlobalObject &GO, StringRef PGOName)
Create the PGOName metadata if a global object's PGO name is different from its mangled name.
StringRef getInstrProfVTableNamesVarName()
Definition InstrProf.h:159
LLVM_ABI std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2134
LLVM_ABI MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition InstrProf.h:137
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition InstrProf.h:172
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition InstrProf.h:97
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
FuncHash
Definition InstrProf.h:78
LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition InstrProf.h:201
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition InstrProf.h:146
StringRef getInstrProfCounterBiasVarName()
Definition InstrProf.h:216
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition InstrProf.h:212
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition InstrProf.h:181
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
InstrProfSectKind
Definition InstrProf.h:91
LLVM_ABI Error readAndDecodeStrings(StringRef NameStrings, std::function< Error(StringRef)> NameCallback)
NameStrings is a string composed of one or more possibly encoded sub-strings.
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition InstrProf.h:140
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
StringRef getInstrProfBitmapBiasVarName()
Definition InstrProf.h:220
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition InstrProf.h:225
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition InstrProf.h:118
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Other
Any other memory.
Definition ModRef.h:68
instrprof_error
Definition InstrProf.h:410
InstrProfValueKind
Definition InstrProf.h:323
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition InstrProf.h:193
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2052
LLVM_ABI const std::error_category & instrprof_category()
StringRef getInstrProfVarPrefix()
Return the prefix of the name of the variables to function as a filter.
Definition InstrProf.h:123
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
StringRef getInstrProfNamesVarPostfixVarName()
Definition InstrProf.h:155
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
StringRef getInstrProfInstrumentGPUFuncName()
Return the name of the GPU wave-cooperative counter increment helper.
Definition InstrProf.h:126
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition InstrProf.h:112
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition InstrProf.h:187
LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
Definition InstrProf.h:153
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
StringRef getPGONameMetadataName()
Definition InstrProf.h:355
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition InstrProf.h:149
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition InstrProf.h:134
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition InstrProf.h:385
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
#define N
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Definition InstrProf.h:818
LLVM_ABI uint64_t getIndexedProfileVersion() const
LLVM_ABI size_t size() const
static LLVM_ABI Expected< Header > readFromBuffer(const unsigned char *Buffer)
uint64_t Cutoff
The required percentile of total execution count.
Definition InstrProf.h:1282
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition InstrProf.h:1285
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition InstrProf.h:1284
const Entry * getCutoffEntryBase() const
Definition InstrProf.h:1331
uint64_t get(SummaryFieldKind K) const
Definition InstrProf.h:1340
void set(SummaryFieldKind K, uint64_t V)
Definition InstrProf.h:1344
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
Definition InstrProf.h:1350
@ TotalNumFunctions
The total number of functions instrumented.
Definition InstrProf.h:1292
@ TotalNumBlocks
Total number of instrumented blocks/edges.
Definition InstrProf.h:1294
@ MaxFunctionCount
The maximal execution count among all functions.
Definition InstrProf.h:1298
@ TotalBlockCount
The sum of all instrumented block counts.
Definition InstrProf.h:1304
@ MaxBlockCount
Max block count of the program.
Definition InstrProf.h:1300
@ MaxInternalBlockCount
Max internal block count of the program (excluding entry blocks).
Definition InstrProf.h:1302
const uint64_t * getSummaryDataBase() const
Definition InstrProf.h:1323
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition InstrProf.h:1318
const Entry & getEntry(uint32_t I) const
Definition InstrProf.h:1348
Profiling information for a single function.
Definition InstrProf.h:906
LLVM_ABI void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
bool isBlockUniform(unsigned BlockIdx) const
Check if a basic block is entered via a wave-uniform branch.
Definition InstrProf.h:952
std::vector< uint64_t > Counts
Definition InstrProf.h:907
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
Definition InstrProf.h:1152
uint16_t OffloadDeviceWaveSize
Definition InstrProf.h:916
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:1035
InstrProfRecord(std::vector< uint64_t > Counts)
Definition InstrProf.h:919
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1147
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
Definition InstrProf.h:1133
std::vector< uint64_t > UniformCounts
For AMDGPU offload profiling: raw or merged uniform counters.
Definition InstrProf.h:911
void setPseudoCount(CountPseudoKind Kind)
Definition InstrProf.h:1043
InstrProfRecord(InstrProfRecord &&)=default
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
Definition InstrProf.h:1140
LLVM_ABI void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site, ArrayRef< InstrProfValueData > VData, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
InstrProfRecord & operator=(const InstrProfRecord &RHS)
Definition InstrProf.h:932
void clearValueData()
Clear value data entries.
Definition InstrProf.h:1012
InstrProfRecord(const InstrProfRecord &RHS)
Definition InstrProf.h:924
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
Definition InstrProf.h:915
InstrProfRecord(std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition InstrProf.h:920
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition InstrProf.h:1156
LLVM_ABI void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
void sortValueData()
Sort value profile data (per site) by count.
Definition InstrProf.h:996
std::vector< uint8_t > BitmapBytes
Definition InstrProf.h:908
InstrProfRecord & operator=(InstrProfRecord &&)=default
void Clear()
Clear value data entries, edge counters, and uniformity data.
Definition InstrProf.h:1003
LLVM_ABI void computeBlockUniformity()
Recompute uniformity metadata from raw uniform counters, when present.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
void sortByCount()
Sort ValueData Descending by Count.
Definition InstrProf.h:1166
InstrProfValueSiteRecord(std::vector< InstrProfValueData > &&VD)
Definition InstrProf.h:879
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition InstrProf.h:883
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition InstrProf.h:876
LLVM_ABI void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
LLVM_ABI void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition InstrProf.h:1125
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
Definition InstrProf.h:1108
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition InstrProf.h:1111
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes, std::vector< uint8_t > UniformityBits)
Definition InstrProf.h:1116
static void setCSFlagInHash(uint64_t &FuncHash)
Definition InstrProf.h:1128
static constexpr uint64_t FUNC_HASH_MASK
Definition InstrProf.h:1103
static constexpr unsigned CS_FLAG_IN_FUNC_HASH
Definition InstrProf.h:1105
const std::string NameFilter
Definition InstrProf.h:871
LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition InstrProf.h:859
LLVM_ABI Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
LLVM_ABI void dump(raw_fd_ostream &OS) const
CountSumOrPercent Overlap
Definition InstrProf.h:835
CountSumOrPercent Base
Definition InstrProf.h:831
LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc)
const std::string * BaseFilename
Definition InstrProf.h:839
const std::string * TestFilename
Definition InstrProf.h:840
void setFuncInfo(StringRef Name, uint64_t Hash)
Definition InstrProf.h:849
CountSumOrPercent Unique
Definition InstrProf.h:837
CountSumOrPercent Mismatch
Definition InstrProf.h:836
StringRef FuncName
Definition InstrProf.h:841
OverlapStatsLevel Level
Definition InstrProf.h:838
OverlapStats(OverlapStatsLevel L=ProgramLevel)
Definition InstrProf.h:845
CountSumOrPercent Test
Definition InstrProf.h:833
uint64_t Pos
Definition InstrProf.h:63
ArrayRef< uint64_t > D
Definition InstrProf.h:64
static LLVM_ABI void createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces, std::vector< BPFunctionNode > &Nodes, bool RemoveOutlierUNs=true)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
std::vector< uint64_t > FunctionNameRefs
Definition InstrProf.h:442
TemporalProfTraceTy(std::initializer_list< uint64_t > Trace={}, uint64_t Weight=1)
Definition InstrProf.h:444
This is the header of the data structure that defines the on-disk layout of the value profile data of...
Definition InstrProf.h:477
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439
Adapter to write values to a stream in a particular byte order.