1 //===- InstrProfWriter.h - Instrumented profiling writer --------*- 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 // This file contains support for writing profiling data for instrumentation
10 // based PGO and coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_PROFILEDATA_INSTRPROFWRITER_H
15 #define LLVM_PROFILEDATA_INSTRPROFWRITER_H
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ProfileData/InstrProf.h"
20 #include "llvm/ProfileData/MemProf.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/Error.h"
23 #include <cstdint>
24 #include <memory>
25 
26 namespace llvm {
27 
28 /// Writer for instrumentation based profile data.
29 class InstrProfRecordWriterTrait;
30 class ProfOStream;
31 class MemoryBuffer;
32 class raw_fd_ostream;
33 
34 class InstrProfWriter {
35 public:
36   using ProfilingData = SmallDenseMap<uint64_t, InstrProfRecord>;
37 
38 private:
39   bool Sparse;
40   StringMap<ProfilingData> FunctionData;
41 
42   // A map to hold memprof data per function. The lower 64 bits obtained from
43   // the md5 hash of the function name is used to index into the map.
44   memprof::FunctionMemProfMap MemProfData;
45 
46   // An enum describing the attributes of the profile.
47   InstrProfKind ProfileKind = InstrProfKind::Unknown;
48   // Use raw pointer here for the incomplete type object.
49   InstrProfRecordWriterTrait *InfoObj;
50 
51 public:
52   InstrProfWriter(bool Sparse = false);
53   ~InstrProfWriter();
54 
55   StringMap<ProfilingData> &getProfileData() { return FunctionData; }
56 
57   /// Add function counts for the given function. If there are already counts
58   /// for this function and the hash and number of counts match, each counter is
59   /// summed. Optionally scale counts by \p Weight.
60   void addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
61                  function_ref<void(Error)> Warn);
62   void addRecord(NamedInstrProfRecord &&I, function_ref<void(Error)> Warn) {
63     addRecord(std::move(I), 1, Warn);
64   }
65 
66   void addRecord(const ::llvm::memprof::MemProfRecord &MR,
67                  function_ref<void(Error)> Warn);
68 
69   /// Merge existing function counts from the given writer.
70   void mergeRecordsFromWriter(InstrProfWriter &&IPW,
71                               function_ref<void(Error)> Warn);
72 
73   /// Write the profile to \c OS
74   Error write(raw_fd_ostream &OS);
75 
76   /// Write the profile in text format to \c OS
77   Error writeText(raw_fd_ostream &OS);
78 
79   Error validateRecord(const InstrProfRecord &Func);
80 
81   /// Write \c Record in text format to \c OS
82   static void writeRecordInText(StringRef Name, uint64_t Hash,
83                                 const InstrProfRecord &Counters,
84                                 InstrProfSymtab &Symtab, raw_fd_ostream &OS);
85 
86   /// Write the profile, returning the raw data. For testing.
87   std::unique_ptr<MemoryBuffer> writeBuffer();
88 
89   /// Update the attributes of the current profile from the attributes
90   /// specified. An error is returned if IR and FE profiles are mixed.
91   Error mergeProfileKind(const InstrProfKind Other) {
92     // If the kind is unset, this is the first profile we are merging so just
93     // set it to the given type.
94     if (ProfileKind == InstrProfKind::Unknown) {
95       ProfileKind = Other;
96       return Error::success();
97     }
98 
99     // Returns true if merging is should fail assuming A and B are incompatible.
100     auto testIncompatible = [&](InstrProfKind A, InstrProfKind B) {
101       return (static_cast<bool>(ProfileKind & A) &&
102               static_cast<bool>(Other & B)) ||
103              (static_cast<bool>(ProfileKind & B) &&
104               static_cast<bool>(Other & A));
105     };
106 
107     // Check if the profiles are in-compatible. Clang frontend profiles can't be
108     // merged with other profile types.
109     if (static_cast<bool>(
110             (ProfileKind & InstrProfKind::FrontendInstrumentation) ^
111             (Other & InstrProfKind::FrontendInstrumentation))) {
112       return make_error<InstrProfError>(instrprof_error::unsupported_version);
113     }
114     if (testIncompatible(InstrProfKind::FunctionEntryOnly,
115                          InstrProfKind::FunctionEntryInstrumentation)) {
116       return make_error<InstrProfError>(
117           instrprof_error::unsupported_version,
118           "cannot merge FunctionEntryOnly profiles and BB profiles together");
119     }
120 
121     // Now we update the profile type with the bits that are set.
122     ProfileKind |= Other;
123     return Error::success();
124   }
125 
126   InstrProfKind getProfileKind() const { return ProfileKind; }
127 
128   // Internal interface for testing purpose only.
129   void setValueProfDataEndianness(support::endianness Endianness);
130   void setOutputSparse(bool Sparse);
131   // Compute the overlap b/w this object and Other. Program level result is
132   // stored in Overlap and function level result is stored in FuncLevelOverlap.
133   void overlapRecord(NamedInstrProfRecord &&Other, OverlapStats &Overlap,
134                      OverlapStats &FuncLevelOverlap,
135                      const OverlapFuncFilters &FuncFilter);
136 
137 private:
138   void addRecord(StringRef Name, uint64_t Hash, InstrProfRecord &&I,
139                  uint64_t Weight, function_ref<void(Error)> Warn);
140   bool shouldEncodeData(const ProfilingData &PD);
141 
142   Error writeImpl(ProfOStream &OS);
143 };
144 
145 } // end namespace llvm
146 
147 #endif // LLVM_PROFILEDATA_INSTRPROFWRITER_H
148