InstrProf: Support for value profiling in the indexed profile format
[oota-llvm.git] / lib / ProfileData / InstrProfWriter.cpp
1 //=-- InstrProfWriter.cpp - Instrumented profiling writer -------------------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing profiling data for clang's
11 // instrumentation based PGO and coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ProfileData/InstrProfWriter.h"
16 #include "InstrProfIndexed.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/EndianStream.h"
19 #include "llvm/Support/OnDiskHashTable.h"
20
21 using namespace llvm;
22
23 namespace {
24 class InstrProfRecordTrait {
25 public:
26   typedef StringRef key_type;
27   typedef StringRef key_type_ref;
28
29   typedef const InstrProfWriter::ProfilingData *const data_type;
30   typedef const InstrProfWriter::ProfilingData *const data_type_ref;
31
32   typedef uint64_t hash_value_type;
33   typedef uint64_t offset_type;
34
35   static hash_value_type ComputeHash(key_type_ref K) {
36     return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType, K);
37   }
38
39   static std::pair<offset_type, offset_type>
40   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
41     using namespace llvm::support;
42     endian::Writer<little> LE(Out);
43
44     offset_type N = K.size();
45     LE.write<offset_type>(N);
46
47     offset_type M = 0;
48     for (const auto &ProfileData : *V) {
49       M += sizeof(uint64_t); // The function hash
50       M += sizeof(uint64_t); // The size of the Counts vector
51       M += ProfileData.second.Counts.size() * sizeof(uint64_t);
52
53       // Value data
54       M += sizeof(uint64_t); // Number of value kinds with value sites.
55       for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
56         const std::vector<InstrProfValueSiteRecord> &ValueSites =
57             ProfileData.second.getValueSitesForKind(Kind);
58         if (ValueSites.empty())
59           continue;
60         M += sizeof(uint64_t); // Value kind
61         M += sizeof(uint64_t); // The number of value sites for given value kind
62         for (InstrProfValueSiteRecord I : ValueSites) {
63           M += sizeof(uint64_t); // Number of value data pairs at a value site
64           M += 2 * sizeof(uint64_t) * I.ValueData.size(); // Value data pairs
65         }
66       }
67     }
68     LE.write<offset_type>(M);
69
70     return std::make_pair(N, M);
71   }
72
73   static void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N){
74     Out.write(K.data(), N);
75   }
76
77   static void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V,
78                        offset_type) {
79     using namespace llvm::support;
80     endian::Writer<little> LE(Out);
81     for (const auto &ProfileData : *V) {
82       LE.write<uint64_t>(ProfileData.first); // Function hash
83       LE.write<uint64_t>(ProfileData.second.Counts.size());
84       for (uint64_t I : ProfileData.second.Counts)
85         LE.write<uint64_t>(I);
86
87       // Compute the number of value kinds with value sites.
88       uint64_t NumValueKinds = 0;
89       for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
90         NumValueKinds +=
91             !(ProfileData.second.getValueSitesForKind(Kind).empty());
92       LE.write<uint64_t>(NumValueKinds);
93
94       // Write value data
95       for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
96         const std::vector<InstrProfValueSiteRecord> &ValueSites =
97             ProfileData.second.getValueSitesForKind(Kind);
98         if (ValueSites.empty())
99           continue;
100         LE.write<uint64_t>(Kind); // Write value kind
101         // Write number of value sites for current value kind
102         LE.write<uint64_t>(ValueSites.size());
103         for (InstrProfValueSiteRecord I : ValueSites) {
104           // Write number of value data pairs at this value site
105           LE.write<uint64_t>(I.ValueData.size());
106           for (auto V : I.ValueData) {
107             if (Kind == IPVK_IndirectCallTarget)
108               LE.write<uint64_t>(ComputeHash((const char *)V.first));
109             else
110               LE.write<uint64_t>(V.first);
111             LE.write<uint64_t>(V.second);
112           }
113         }
114       }
115     }
116   }
117 };
118 }
119
120 static std::error_code combineInstrProfRecords(InstrProfRecord &Dest,
121                                                InstrProfRecord &Source,
122                                                uint64_t &MaxFunctionCount) {
123   // If the number of counters doesn't match we either have bad data
124   // or a hash collision.
125   if (Dest.Counts.size() != Source.Counts.size())
126     return instrprof_error::count_mismatch;
127
128   for (size_t I = 0, E = Source.Counts.size(); I < E; ++I) {
129     if (Dest.Counts[I] + Source.Counts[I] < Dest.Counts[I])
130       return instrprof_error::counter_overflow;
131     Dest.Counts[I] += Source.Counts[I];
132   }
133
134   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
135
136     std::vector<InstrProfValueSiteRecord> &SourceValueSites =
137         Source.getValueSitesForKind(Kind);
138     if (SourceValueSites.empty())
139       continue;
140
141     std::vector<InstrProfValueSiteRecord> &DestValueSites =
142         Dest.getValueSitesForKind(Kind);
143
144     if (DestValueSites.empty()) {
145       DestValueSites.swap(SourceValueSites);
146       continue;
147     }
148
149     if (DestValueSites.size() != SourceValueSites.size())
150       return instrprof_error::value_site_count_mismatch;
151     for (size_t I = 0, E = SourceValueSites.size(); I < E; ++I)
152       DestValueSites[I].mergeValueData(SourceValueSites[I]);
153   }
154
155   // We keep track of the max function count as we go for simplicity.
156   if (Dest.Counts[0] > MaxFunctionCount)
157     MaxFunctionCount = Dest.Counts[0];
158
159   return instrprof_error::success;
160 }
161
162 void InstrProfWriter::updateStringTableReferences(InstrProfRecord &I) {
163   I.Name = StringTable.insertString(I.Name);
164   for (auto &VSite : I.IndirectCallSites)
165     for (auto &VData : VSite.ValueData)
166       VData.first =
167           (uint64_t)StringTable.insertString((const char *)VData.first);
168 }
169
170 std::error_code InstrProfWriter::addRecord(InstrProfRecord &&I) {
171   updateStringTableReferences(I);
172   auto &ProfileDataMap = FunctionData[I.Name];
173
174   auto Where = ProfileDataMap.find(I.Hash);
175   if (Where == ProfileDataMap.end()) {
176     // We've never seen a function with this name and hash, add it.
177     ProfileDataMap[I.Hash] = I;
178
179     // We keep track of the max function count as we go for simplicity.
180     if (I.Counts[0] > MaxFunctionCount)
181       MaxFunctionCount = I.Counts[0];
182     return instrprof_error::success;
183   }
184
185   // We're updating a function we've seen before.
186   return combineInstrProfRecords(Where->second, I, MaxFunctionCount);
187 }
188
189 std::pair<uint64_t, uint64_t> InstrProfWriter::writeImpl(raw_ostream &OS) {
190   OnDiskChainedHashTableGenerator<InstrProfRecordTrait> Generator;
191
192   // Populate the hash table generator.
193   for (const auto &I : FunctionData)
194     Generator.insert(I.getKey(), &I.getValue());
195
196   using namespace llvm::support;
197   endian::Writer<little> LE(OS);
198
199   // Write the header.
200   LE.write<uint64_t>(IndexedInstrProf::Magic);
201   LE.write<uint64_t>(IndexedInstrProf::Version);
202   LE.write<uint64_t>(MaxFunctionCount);
203   LE.write<uint64_t>(static_cast<uint64_t>(IndexedInstrProf::HashType));
204
205   // Save a space to write the hash table start location.
206   uint64_t HashTableStartLoc = OS.tell();
207   LE.write<uint64_t>(0);
208   // Write the hash table.
209   uint64_t HashTableStart = Generator.Emit(OS);
210
211   return std::make_pair(HashTableStartLoc, HashTableStart);
212 }
213
214 void InstrProfWriter::write(raw_fd_ostream &OS) {
215   // Write the hash table.
216   auto TableStart = writeImpl(OS);
217
218   // Go back and fill in the hash table start.
219   using namespace support;
220   OS.seek(TableStart.first);
221   endian::Writer<little>(OS).write<uint64_t>(TableStart.second);
222 }
223
224 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
225   std::string Data;
226   llvm::raw_string_ostream OS(Data);
227   // Write the hash table.
228   auto TableStart = writeImpl(OS);
229   OS.flush();
230
231   // Go back and fill in the hash table start.
232   using namespace support;
233   uint64_t Bytes = endian::byte_swap<uint64_t, little>(TableStart.second);
234   Data.replace(TableStart.first, sizeof(uint64_t), (const char *)&Bytes,
235                sizeof(uint64_t));
236
237   // Return this in an aligned memory buffer.
238   return MemoryBuffer::getMemBufferCopy(Data);
239 }