OSDN Git Service

c0b067a490ef196617b0eb75da7bf78bee7ebb82
[android-x86/external-llvm.git] / lib / ProfileData / InstrProf.cpp
1 //===- InstrProf.cpp - Instrumented profiling format support --------------===//
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 clang's instrumentation based PGO and
10 // coverage.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ProfileData/InstrProf.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instruction.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/MDBuilder.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/ProfileData/InstrProfReader.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Error.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SwapByteOrder.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstddef>
48 #include <cstdint>
49 #include <cstring>
50 #include <memory>
51 #include <string>
52 #include <system_error>
53 #include <utility>
54 #include <vector>
55
56 using namespace llvm;
57
58 static cl::opt<bool> StaticFuncFullModulePrefix(
59     "static-func-full-module-prefix", cl::init(true), cl::Hidden,
60     cl::desc("Use full module build paths in the profile counter names for "
61              "static functions."));
62
63 // This option is tailored to users that have different top-level directory in
64 // profile-gen and profile-use compilation. Users need to specific the number
65 // of levels to strip. A value larger than the number of directories in the
66 // source file will strip all the directory names and only leave the basename.
67 //
68 // Note current ThinLTO module importing for the indirect-calls assumes
69 // the source directory name not being stripped. A non-zero option value here
70 // can potentially prevent some inter-module indirect-call-promotions.
71 static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
72     "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
73     cl::desc("Strip specified level of directory name from source path in "
74              "the profile counter name for static functions."));
75
76 static std::string getInstrProfErrString(instrprof_error Err) {
77   switch (Err) {
78   case instrprof_error::success:
79     return "Success";
80   case instrprof_error::eof:
81     return "End of File";
82   case instrprof_error::unrecognized_format:
83     return "Unrecognized instrumentation profile encoding format";
84   case instrprof_error::bad_magic:
85     return "Invalid instrumentation profile data (bad magic)";
86   case instrprof_error::bad_header:
87     return "Invalid instrumentation profile data (file header is corrupt)";
88   case instrprof_error::unsupported_version:
89     return "Unsupported instrumentation profile format version";
90   case instrprof_error::unsupported_hash_type:
91     return "Unsupported instrumentation profile hash type";
92   case instrprof_error::too_large:
93     return "Too much profile data";
94   case instrprof_error::truncated:
95     return "Truncated profile data";
96   case instrprof_error::malformed:
97     return "Malformed instrumentation profile data";
98   case instrprof_error::unknown_function:
99     return "No profile data available for function";
100   case instrprof_error::hash_mismatch:
101     return "Function control flow change detected (hash mismatch)";
102   case instrprof_error::count_mismatch:
103     return "Function basic block count change detected (counter mismatch)";
104   case instrprof_error::counter_overflow:
105     return "Counter overflow";
106   case instrprof_error::value_site_count_mismatch:
107     return "Function value site count change detected (counter mismatch)";
108   case instrprof_error::compress_failed:
109     return "Failed to compress data (zlib)";
110   case instrprof_error::uncompress_failed:
111     return "Failed to uncompress data (zlib)";
112   case instrprof_error::empty_raw_profile:
113     return "Empty raw profile file";
114   case instrprof_error::zlib_unavailable:
115     return "Profile uses zlib compression but the profile reader was built without zlib support";
116   }
117   llvm_unreachable("A value of instrprof_error has no message.");
118 }
119
120 namespace {
121
122 // FIXME: This class is only here to support the transition to llvm::Error. It
123 // will be removed once this transition is complete. Clients should prefer to
124 // deal with the Error value directly, rather than converting to error_code.
125 class InstrProfErrorCategoryType : public std::error_category {
126   const char *name() const noexcept override { return "llvm.instrprof"; }
127
128   std::string message(int IE) const override {
129     return getInstrProfErrString(static_cast<instrprof_error>(IE));
130   }
131 };
132
133 } // end anonymous namespace
134
135 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
136
137 const std::error_category &llvm::instrprof_category() {
138   return *ErrorCategory;
139 }
140
141 namespace {
142
143 const char *InstrProfSectNameCommon[] = {
144 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
145   SectNameCommon,
146 #include "llvm/ProfileData/InstrProfData.inc"
147 };
148
149 const char *InstrProfSectNameCoff[] = {
150 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
151   SectNameCoff,
152 #include "llvm/ProfileData/InstrProfData.inc"
153 };
154
155 const char *InstrProfSectNamePrefix[] = {
156 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
157   Prefix,
158 #include "llvm/ProfileData/InstrProfData.inc"
159 };
160
161 } // namespace
162
163 namespace llvm {
164
165 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
166                                     Triple::ObjectFormatType OF,
167                                     bool AddSegmentInfo) {
168   std::string SectName;
169
170   if (OF == Triple::MachO && AddSegmentInfo)
171     SectName = InstrProfSectNamePrefix[IPSK];
172
173   if (OF == Triple::COFF)
174     SectName += InstrProfSectNameCoff[IPSK];
175   else
176     SectName += InstrProfSectNameCommon[IPSK];
177
178   if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
179     SectName += ",regular,live_support";
180
181   return SectName;
182 }
183
184 void SoftInstrProfErrors::addError(instrprof_error IE) {
185   if (IE == instrprof_error::success)
186     return;
187
188   if (FirstError == instrprof_error::success)
189     FirstError = IE;
190
191   switch (IE) {
192   case instrprof_error::hash_mismatch:
193     ++NumHashMismatches;
194     break;
195   case instrprof_error::count_mismatch:
196     ++NumCountMismatches;
197     break;
198   case instrprof_error::counter_overflow:
199     ++NumCounterOverflows;
200     break;
201   case instrprof_error::value_site_count_mismatch:
202     ++NumValueSiteCountMismatches;
203     break;
204   default:
205     llvm_unreachable("Not a soft error");
206   }
207 }
208
209 std::string InstrProfError::message() const {
210   return getInstrProfErrString(Err);
211 }
212
213 char InstrProfError::ID = 0;
214
215 std::string getPGOFuncName(StringRef RawFuncName,
216                            GlobalValue::LinkageTypes Linkage,
217                            StringRef FileName,
218                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
219   return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
220 }
221
222 // Strip NumPrefix level of directory name from PathNameStr. If the number of
223 // directory separators is less than NumPrefix, strip all the directories and
224 // leave base file name only.
225 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
226   uint32_t Count = NumPrefix;
227   uint32_t Pos = 0, LastPos = 0;
228   for (auto & CI : PathNameStr) {
229     ++Pos;
230     if (llvm::sys::path::is_separator(CI)) {
231       LastPos = Pos;
232       --Count;
233     }
234     if (Count == 0)
235       break;
236   }
237   return PathNameStr.substr(LastPos);
238 }
239
240 // Return the PGOFuncName. This function has some special handling when called
241 // in LTO optimization. The following only applies when calling in LTO passes
242 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
243 // symbols. This happens after value profile annotation, but those internal
244 // linkage functions should not have a source prefix.
245 // Additionally, for ThinLTO mode, exported internal functions are promoted
246 // and renamed. We need to ensure that the original internal PGO name is
247 // used when computing the GUID that is compared against the profiled GUIDs.
248 // To differentiate compiler generated internal symbols from original ones,
249 // PGOFuncName meta data are created and attached to the original internal
250 // symbols in the value profile annotation step
251 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
252 // data, its original linkage must be non-internal.
253 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
254   if (!InLTO) {
255     StringRef FileName(F.getParent()->getSourceFileName());
256     uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
257     if (StripLevel < StaticFuncStripDirNamePrefix)
258       StripLevel = StaticFuncStripDirNamePrefix;
259     if (StripLevel)
260       FileName = stripDirPrefix(FileName, StripLevel);
261     return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
262   }
263
264   // In LTO mode (when InLTO is true), first check if there is a meta data.
265   if (MDNode *MD = getPGOFuncNameMetadata(F)) {
266     StringRef S = cast<MDString>(MD->getOperand(0))->getString();
267     return S.str();
268   }
269
270   // If there is no meta data, the function must be a global before the value
271   // profile annotation pass. Its current linkage may be internal if it is
272   // internalized in LTO mode.
273   return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
274 }
275
276 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
277   if (FileName.empty())
278     return PGOFuncName;
279   // Drop the file name including ':'. See also getPGOFuncName.
280   if (PGOFuncName.startswith(FileName))
281     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
282   return PGOFuncName;
283 }
284
285 // \p FuncName is the string used as profile lookup key for the function. A
286 // symbol is created to hold the name. Return the legalized symbol name.
287 std::string getPGOFuncNameVarName(StringRef FuncName,
288                                   GlobalValue::LinkageTypes Linkage) {
289   std::string VarName = getInstrProfNameVarPrefix();
290   VarName += FuncName;
291
292   if (!GlobalValue::isLocalLinkage(Linkage))
293     return VarName;
294
295   // Now fix up illegal chars in local VarName that may upset the assembler.
296   const char *InvalidChars = "-:<>/\"'";
297   size_t found = VarName.find_first_of(InvalidChars);
298   while (found != std::string::npos) {
299     VarName[found] = '_';
300     found = VarName.find_first_of(InvalidChars, found + 1);
301   }
302   return VarName;
303 }
304
305 GlobalVariable *createPGOFuncNameVar(Module &M,
306                                      GlobalValue::LinkageTypes Linkage,
307                                      StringRef PGOFuncName) {
308   // We generally want to match the function's linkage, but available_externally
309   // and extern_weak both have the wrong semantics, and anything that doesn't
310   // need to link across compilation units doesn't need to be visible at all.
311   if (Linkage == GlobalValue::ExternalWeakLinkage)
312     Linkage = GlobalValue::LinkOnceAnyLinkage;
313   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
314     Linkage = GlobalValue::LinkOnceODRLinkage;
315   else if (Linkage == GlobalValue::InternalLinkage ||
316            Linkage == GlobalValue::ExternalLinkage)
317     Linkage = GlobalValue::PrivateLinkage;
318
319   auto *Value =
320       ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
321   auto FuncNameVar =
322       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
323                          getPGOFuncNameVarName(PGOFuncName, Linkage));
324
325   // Hide the symbol so that we correctly get a copy for each executable.
326   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
327     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
328
329   return FuncNameVar;
330 }
331
332 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
333   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
334 }
335
336 Error InstrProfSymtab::create(Module &M, bool InLTO) {
337   for (Function &F : M) {
338     // Function may not have a name: like using asm("") to overwrite the name.
339     // Ignore in this case.
340     if (!F.hasName())
341       continue;
342     const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
343     if (Error E = addFuncName(PGOFuncName))
344       return E;
345     MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
346     // In ThinLTO, local function may have been promoted to global and have
347     // suffix added to the function name. We need to add the stripped function
348     // name to the symbol table so that we can find a match from profile.
349     if (InLTO) {
350       auto pos = PGOFuncName.find('.');
351       if (pos != std::string::npos) {
352         const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
353         if (Error E = addFuncName(OtherFuncName))
354           return E;
355         MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
356       }
357     }
358   }
359   Sorted = false;
360   finalizeSymtab();
361   return Error::success();
362 }
363
364 uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
365   finalizeSymtab();
366   auto Result =
367       llvm::bsearch(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
368         return Address <= A.first;
369       });
370   // Raw function pointer collected by value profiler may be from
371   // external functions that are not instrumented. They won't have
372   // mapping data to be used by the deserializer. Force the value to
373   // be 0 in this case.
374   if (Result != AddrToMD5Map.end() && Result->first == Address)
375     return (uint64_t)Result->second;
376   return 0;
377 }
378
379 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
380                                 bool doCompression, std::string &Result) {
381   assert(!NameStrs.empty() && "No name data to emit");
382
383   uint8_t Header[16], *P = Header;
384   std::string UncompressedNameStrings =
385       join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
386
387   assert(StringRef(UncompressedNameStrings)
388                  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
389          "PGO name is invalid (contains separator token)");
390
391   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
392   P += EncLen;
393
394   auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
395     EncLen = encodeULEB128(CompressedLen, P);
396     P += EncLen;
397     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
398     unsigned HeaderLen = P - &Header[0];
399     Result.append(HeaderStr, HeaderLen);
400     Result += InputStr;
401     return Error::success();
402   };
403
404   if (!doCompression) {
405     return WriteStringToResult(0, UncompressedNameStrings);
406   }
407
408   SmallString<128> CompressedNameStrings;
409   Error E = zlib::compress(StringRef(UncompressedNameStrings),
410                            CompressedNameStrings, zlib::BestSizeCompression);
411   if (E) {
412     consumeError(std::move(E));
413     return make_error<InstrProfError>(instrprof_error::compress_failed);
414   }
415
416   return WriteStringToResult(CompressedNameStrings.size(),
417                              CompressedNameStrings);
418 }
419
420 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
421   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
422   StringRef NameStr =
423       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
424   return NameStr;
425 }
426
427 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
428                                 std::string &Result, bool doCompression) {
429   std::vector<std::string> NameStrs;
430   for (auto *NameVar : NameVars) {
431     NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
432   }
433   return collectPGOFuncNameStrings(
434       NameStrs, zlib::isAvailable() && doCompression, Result);
435 }
436
437 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
438   const uint8_t *P = NameStrings.bytes_begin();
439   const uint8_t *EndP = NameStrings.bytes_end();
440   while (P < EndP) {
441     uint32_t N;
442     uint64_t UncompressedSize = decodeULEB128(P, &N);
443     P += N;
444     uint64_t CompressedSize = decodeULEB128(P, &N);
445     P += N;
446     bool isCompressed = (CompressedSize != 0);
447     SmallString<128> UncompressedNameStrings;
448     StringRef NameStrings;
449     if (isCompressed) {
450       if (!llvm::zlib::isAvailable())
451         return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
452
453       StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
454                                       CompressedSize);
455       if (Error E =
456               zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
457                                UncompressedSize)) {
458         consumeError(std::move(E));
459         return make_error<InstrProfError>(instrprof_error::uncompress_failed);
460       }
461       P += CompressedSize;
462       NameStrings = StringRef(UncompressedNameStrings.data(),
463                               UncompressedNameStrings.size());
464     } else {
465       NameStrings =
466           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
467       P += UncompressedSize;
468     }
469     // Now parse the name strings.
470     SmallVector<StringRef, 0> Names;
471     NameStrings.split(Names, getInstrProfNameSeparator());
472     for (StringRef &Name : Names)
473       if (Error E = Symtab.addFuncName(Name))
474         return E;
475
476     while (P < EndP && *P == 0)
477       P++;
478   }
479   return Error::success();
480 }
481
482 void InstrProfRecord::accumuateCounts(CountSumOrPercent &Sum) const {
483   uint64_t FuncSum = 0;
484   Sum.NumEntries += Counts.size();
485   for (size_t F = 0, E = Counts.size(); F < E; ++F)
486     FuncSum += Counts[F];
487   Sum.CountSum += FuncSum;
488
489   for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
490     uint64_t KindSum = 0;
491     uint32_t NumValueSites = getNumValueSites(VK);
492     for (size_t I = 0; I < NumValueSites; ++I) {
493       uint32_t NV = getNumValueDataForSite(VK, I);
494       std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
495       for (uint32_t V = 0; V < NV; V++)
496         KindSum += VD[V].Count;
497     }
498     Sum.ValueCounts[VK] += KindSum;
499   }
500 }
501
502 void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
503                                        uint32_t ValueKind,
504                                        OverlapStats &Overlap,
505                                        OverlapStats &FuncLevelOverlap) {
506   this->sortByTargetValues();
507   Input.sortByTargetValues();
508   double Score = 0.0f, FuncLevelScore = 0.0f;
509   auto I = ValueData.begin();
510   auto IE = ValueData.end();
511   auto J = Input.ValueData.begin();
512   auto JE = Input.ValueData.end();
513   while (I != IE && J != JE) {
514     if (I->Value == J->Value) {
515       Score += OverlapStats::score(I->Count, J->Count,
516                                    Overlap.Base.ValueCounts[ValueKind],
517                                    Overlap.Test.ValueCounts[ValueKind]);
518       FuncLevelScore += OverlapStats::score(
519           I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
520           FuncLevelOverlap.Test.ValueCounts[ValueKind]);
521       ++I;
522     } else if (I->Value < J->Value) {
523       ++I;
524       continue;
525     }
526     ++J;
527   }
528   Overlap.Overlap.ValueCounts[ValueKind] += Score;
529   FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
530 }
531
532 // Return false on mismatch.
533 void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
534                                            InstrProfRecord &Other,
535                                            OverlapStats &Overlap,
536                                            OverlapStats &FuncLevelOverlap) {
537   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
538   assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
539   if (!ThisNumValueSites)
540     return;
541
542   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
543       getOrCreateValueSitesForKind(ValueKind);
544   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
545       Other.getValueSitesForKind(ValueKind);
546   for (uint32_t I = 0; I < ThisNumValueSites; I++)
547     ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
548                                FuncLevelOverlap);
549 }
550
551 void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
552                               OverlapStats &FuncLevelOverlap,
553                               uint64_t ValueCutoff) {
554   // FuncLevel CountSum for other should already computed and nonzero.
555   assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
556   accumuateCounts(FuncLevelOverlap.Base);
557   bool Mismatch = (Counts.size() != Other.Counts.size());
558
559   // Check if the value profiles mismatch.
560   if (!Mismatch) {
561     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
562       uint32_t ThisNumValueSites = getNumValueSites(Kind);
563       uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
564       if (ThisNumValueSites != OtherNumValueSites) {
565         Mismatch = true;
566         break;
567       }
568     }
569   }
570   if (Mismatch) {
571     Overlap.addOneMismatch(FuncLevelOverlap.Test);
572     return;
573   }
574
575   // Compute overlap for value counts.
576   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
577     overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
578
579   double Score = 0.0;
580   uint64_t MaxCount = 0;
581   // Compute overlap for edge counts.
582   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
583     Score += OverlapStats::score(Counts[I], Other.Counts[I],
584                                  Overlap.Base.CountSum, Overlap.Test.CountSum);
585     MaxCount = std::max(Other.Counts[I], MaxCount);
586   }
587   Overlap.Overlap.CountSum += Score;
588   Overlap.Overlap.NumEntries += 1;
589
590   if (MaxCount >= ValueCutoff) {
591     double FuncScore = 0.0;
592     for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
593       FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
594                                        FuncLevelOverlap.Base.CountSum,
595                                        FuncLevelOverlap.Test.CountSum);
596     FuncLevelOverlap.Overlap.CountSum = FuncScore;
597     FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
598     FuncLevelOverlap.Valid = true;
599   }
600 }
601
602 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
603                                      uint64_t Weight,
604                                      function_ref<void(instrprof_error)> Warn) {
605   this->sortByTargetValues();
606   Input.sortByTargetValues();
607   auto I = ValueData.begin();
608   auto IE = ValueData.end();
609   for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
610        ++J) {
611     while (I != IE && I->Value < J->Value)
612       ++I;
613     if (I != IE && I->Value == J->Value) {
614       bool Overflowed;
615       I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
616       if (Overflowed)
617         Warn(instrprof_error::counter_overflow);
618       ++I;
619       continue;
620     }
621     ValueData.insert(I, *J);
622   }
623 }
624
625 void InstrProfValueSiteRecord::scale(uint64_t Weight,
626                                      function_ref<void(instrprof_error)> Warn) {
627   for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
628     bool Overflowed;
629     I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
630     if (Overflowed)
631       Warn(instrprof_error::counter_overflow);
632   }
633 }
634
635 // Merge Value Profile data from Src record to this record for ValueKind.
636 // Scale merged value counts by \p Weight.
637 void InstrProfRecord::mergeValueProfData(
638     uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
639     function_ref<void(instrprof_error)> Warn) {
640   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
641   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
642   if (ThisNumValueSites != OtherNumValueSites) {
643     Warn(instrprof_error::value_site_count_mismatch);
644     return;
645   }
646   if (!ThisNumValueSites)
647     return;
648   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
649       getOrCreateValueSitesForKind(ValueKind);
650   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
651       Src.getValueSitesForKind(ValueKind);
652   for (uint32_t I = 0; I < ThisNumValueSites; I++)
653     ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
654 }
655
656 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
657                             function_ref<void(instrprof_error)> Warn) {
658   // If the number of counters doesn't match we either have bad data
659   // or a hash collision.
660   if (Counts.size() != Other.Counts.size()) {
661     Warn(instrprof_error::count_mismatch);
662     return;
663   }
664
665   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
666     bool Overflowed;
667     Counts[I] =
668         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
669     if (Overflowed)
670       Warn(instrprof_error::counter_overflow);
671   }
672
673   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
674     mergeValueProfData(Kind, Other, Weight, Warn);
675 }
676
677 void InstrProfRecord::scaleValueProfData(
678     uint32_t ValueKind, uint64_t Weight,
679     function_ref<void(instrprof_error)> Warn) {
680   for (auto &R : getValueSitesForKind(ValueKind))
681     R.scale(Weight, Warn);
682 }
683
684 void InstrProfRecord::scale(uint64_t Weight,
685                             function_ref<void(instrprof_error)> Warn) {
686   for (auto &Count : this->Counts) {
687     bool Overflowed;
688     Count = SaturatingMultiply(Count, Weight, &Overflowed);
689     if (Overflowed)
690       Warn(instrprof_error::counter_overflow);
691   }
692   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
693     scaleValueProfData(Kind, Weight, Warn);
694 }
695
696 // Map indirect call target name hash to name string.
697 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
698                                      InstrProfSymtab *SymTab) {
699   if (!SymTab)
700     return Value;
701
702   if (ValueKind == IPVK_IndirectCallTarget)
703     return SymTab->getFunctionHashFromAddress(Value);
704
705   return Value;
706 }
707
708 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
709                                    InstrProfValueData *VData, uint32_t N,
710                                    InstrProfSymtab *ValueMap) {
711   for (uint32_t I = 0; I < N; I++) {
712     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
713   }
714   std::vector<InstrProfValueSiteRecord> &ValueSites =
715       getOrCreateValueSitesForKind(ValueKind);
716   if (N == 0)
717     ValueSites.emplace_back();
718   else
719     ValueSites.emplace_back(VData, VData + N);
720 }
721
722 #define INSTR_PROF_COMMON_API_IMPL
723 #include "llvm/ProfileData/InstrProfData.inc"
724
725 /*!
726  * ValueProfRecordClosure Interface implementation for  InstrProfRecord
727  *  class. These C wrappers are used as adaptors so that C++ code can be
728  *  invoked as callbacks.
729  */
730 uint32_t getNumValueKindsInstrProf(const void *Record) {
731   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
732 }
733
734 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
735   return reinterpret_cast<const InstrProfRecord *>(Record)
736       ->getNumValueSites(VKind);
737 }
738
739 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
740   return reinterpret_cast<const InstrProfRecord *>(Record)
741       ->getNumValueData(VKind);
742 }
743
744 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
745                                          uint32_t S) {
746   return reinterpret_cast<const InstrProfRecord *>(R)
747       ->getNumValueDataForSite(VK, S);
748 }
749
750 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
751                               uint32_t K, uint32_t S) {
752   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
753 }
754
755 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
756   ValueProfData *VD =
757       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
758   memset(VD, 0, TotalSizeInBytes);
759   return VD;
760 }
761
762 static ValueProfRecordClosure InstrProfRecordClosure = {
763     nullptr,
764     getNumValueKindsInstrProf,
765     getNumValueSitesInstrProf,
766     getNumValueDataInstrProf,
767     getNumValueDataForSiteInstrProf,
768     nullptr,
769     getValueForSiteInstrProf,
770     allocValueProfDataInstrProf};
771
772 // Wrapper implementation using the closure mechanism.
773 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
774   auto Closure = InstrProfRecordClosure;
775   Closure.Record = &Record;
776   return getValueProfDataSize(&Closure);
777 }
778
779 // Wrapper implementation using the closure mechanism.
780 std::unique_ptr<ValueProfData>
781 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
782   InstrProfRecordClosure.Record = &Record;
783
784   std::unique_ptr<ValueProfData> VPD(
785       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
786   return VPD;
787 }
788
789 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
790                                     InstrProfSymtab *SymTab) {
791   Record.reserveSites(Kind, NumValueSites);
792
793   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
794   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
795     uint8_t ValueDataCount = this->SiteCountArray[VSite];
796     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
797     ValueData += ValueDataCount;
798   }
799 }
800
801 // For writing/serializing,  Old is the host endianness, and  New is
802 // byte order intended on disk. For Reading/deserialization, Old
803 // is the on-disk source endianness, and New is the host endianness.
804 void ValueProfRecord::swapBytes(support::endianness Old,
805                                 support::endianness New) {
806   using namespace support;
807
808   if (Old == New)
809     return;
810
811   if (getHostEndianness() != Old) {
812     sys::swapByteOrder<uint32_t>(NumValueSites);
813     sys::swapByteOrder<uint32_t>(Kind);
814   }
815   uint32_t ND = getValueProfRecordNumValueData(this);
816   InstrProfValueData *VD = getValueProfRecordValueData(this);
817
818   // No need to swap byte array: SiteCountArrray.
819   for (uint32_t I = 0; I < ND; I++) {
820     sys::swapByteOrder<uint64_t>(VD[I].Value);
821     sys::swapByteOrder<uint64_t>(VD[I].Count);
822   }
823   if (getHostEndianness() == Old) {
824     sys::swapByteOrder<uint32_t>(NumValueSites);
825     sys::swapByteOrder<uint32_t>(Kind);
826   }
827 }
828
829 void ValueProfData::deserializeTo(InstrProfRecord &Record,
830                                   InstrProfSymtab *SymTab) {
831   if (NumValueKinds == 0)
832     return;
833
834   ValueProfRecord *VR = getFirstValueProfRecord(this);
835   for (uint32_t K = 0; K < NumValueKinds; K++) {
836     VR->deserializeTo(Record, SymTab);
837     VR = getValueProfRecordNext(VR);
838   }
839 }
840
841 template <class T>
842 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
843   using namespace support;
844
845   if (Orig == little)
846     return endian::readNext<T, little, unaligned>(D);
847   else
848     return endian::readNext<T, big, unaligned>(D);
849 }
850
851 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
852   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
853                                             ValueProfData());
854 }
855
856 Error ValueProfData::checkIntegrity() {
857   if (NumValueKinds > IPVK_Last + 1)
858     return make_error<InstrProfError>(instrprof_error::malformed);
859   // Total size needs to be mulltiple of quadword size.
860   if (TotalSize % sizeof(uint64_t))
861     return make_error<InstrProfError>(instrprof_error::malformed);
862
863   ValueProfRecord *VR = getFirstValueProfRecord(this);
864   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
865     if (VR->Kind > IPVK_Last)
866       return make_error<InstrProfError>(instrprof_error::malformed);
867     VR = getValueProfRecordNext(VR);
868     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
869       return make_error<InstrProfError>(instrprof_error::malformed);
870   }
871   return Error::success();
872 }
873
874 Expected<std::unique_ptr<ValueProfData>>
875 ValueProfData::getValueProfData(const unsigned char *D,
876                                 const unsigned char *const BufferEnd,
877                                 support::endianness Endianness) {
878   using namespace support;
879
880   if (D + sizeof(ValueProfData) > BufferEnd)
881     return make_error<InstrProfError>(instrprof_error::truncated);
882
883   const unsigned char *Header = D;
884   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
885   if (D + TotalSize > BufferEnd)
886     return make_error<InstrProfError>(instrprof_error::too_large);
887
888   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
889   memcpy(VPD.get(), D, TotalSize);
890   // Byte swap.
891   VPD->swapBytesToHost(Endianness);
892
893   Error E = VPD->checkIntegrity();
894   if (E)
895     return std::move(E);
896
897   return std::move(VPD);
898 }
899
900 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
901   using namespace support;
902
903   if (Endianness == getHostEndianness())
904     return;
905
906   sys::swapByteOrder<uint32_t>(TotalSize);
907   sys::swapByteOrder<uint32_t>(NumValueKinds);
908
909   ValueProfRecord *VR = getFirstValueProfRecord(this);
910   for (uint32_t K = 0; K < NumValueKinds; K++) {
911     VR->swapBytes(Endianness, getHostEndianness());
912     VR = getValueProfRecordNext(VR);
913   }
914 }
915
916 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
917   using namespace support;
918
919   if (Endianness == getHostEndianness())
920     return;
921
922   ValueProfRecord *VR = getFirstValueProfRecord(this);
923   for (uint32_t K = 0; K < NumValueKinds; K++) {
924     ValueProfRecord *NVR = getValueProfRecordNext(VR);
925     VR->swapBytes(getHostEndianness(), Endianness);
926     VR = NVR;
927   }
928   sys::swapByteOrder<uint32_t>(TotalSize);
929   sys::swapByteOrder<uint32_t>(NumValueKinds);
930 }
931
932 void annotateValueSite(Module &M, Instruction &Inst,
933                        const InstrProfRecord &InstrProfR,
934                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
935                        uint32_t MaxMDCount) {
936   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
937   if (!NV)
938     return;
939
940   uint64_t Sum = 0;
941   std::unique_ptr<InstrProfValueData[]> VD =
942       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
943
944   ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
945   annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
946 }
947
948 void annotateValueSite(Module &M, Instruction &Inst,
949                        ArrayRef<InstrProfValueData> VDs,
950                        uint64_t Sum, InstrProfValueKind ValueKind,
951                        uint32_t MaxMDCount) {
952   LLVMContext &Ctx = M.getContext();
953   MDBuilder MDHelper(Ctx);
954   SmallVector<Metadata *, 3> Vals;
955   // Tag
956   Vals.push_back(MDHelper.createString("VP"));
957   // Value Kind
958   Vals.push_back(MDHelper.createConstant(
959       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
960   // Total Count
961   Vals.push_back(
962       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
963
964   // Value Profile Data
965   uint32_t MDCount = MaxMDCount;
966   for (auto &VD : VDs) {
967     Vals.push_back(MDHelper.createConstant(
968         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
969     Vals.push_back(MDHelper.createConstant(
970         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
971     if (--MDCount == 0)
972       break;
973   }
974   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
975 }
976
977 bool getValueProfDataFromInst(const Instruction &Inst,
978                               InstrProfValueKind ValueKind,
979                               uint32_t MaxNumValueData,
980                               InstrProfValueData ValueData[],
981                               uint32_t &ActualNumValueData, uint64_t &TotalC) {
982   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
983   if (!MD)
984     return false;
985
986   unsigned NOps = MD->getNumOperands();
987
988   if (NOps < 5)
989     return false;
990
991   // Operand 0 is a string tag "VP":
992   MDString *Tag = cast<MDString>(MD->getOperand(0));
993   if (!Tag)
994     return false;
995
996   if (!Tag->getString().equals("VP"))
997     return false;
998
999   // Now check kind:
1000   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
1001   if (!KindInt)
1002     return false;
1003   if (KindInt->getZExtValue() != ValueKind)
1004     return false;
1005
1006   // Get total count
1007   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
1008   if (!TotalCInt)
1009     return false;
1010   TotalC = TotalCInt->getZExtValue();
1011
1012   ActualNumValueData = 0;
1013
1014   for (unsigned I = 3; I < NOps; I += 2) {
1015     if (ActualNumValueData >= MaxNumValueData)
1016       break;
1017     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
1018     ConstantInt *Count =
1019         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
1020     if (!Value || !Count)
1021       return false;
1022     ValueData[ActualNumValueData].Value = Value->getZExtValue();
1023     ValueData[ActualNumValueData].Count = Count->getZExtValue();
1024     ActualNumValueData++;
1025   }
1026   return true;
1027 }
1028
1029 MDNode *getPGOFuncNameMetadata(const Function &F) {
1030   return F.getMetadata(getPGOFuncNameMetadataName());
1031 }
1032
1033 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
1034   // Only for internal linkage functions.
1035   if (PGOFuncName == F.getName())
1036       return;
1037   // Don't create duplicated meta-data.
1038   if (getPGOFuncNameMetadata(F))
1039     return;
1040   LLVMContext &C = F.getContext();
1041   MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
1042   F.setMetadata(getPGOFuncNameMetadataName(), N);
1043 }
1044
1045 bool needsComdatForCounter(const Function &F, const Module &M) {
1046   if (F.hasComdat())
1047     return true;
1048
1049   if (!Triple(M.getTargetTriple()).supportsCOMDAT())
1050     return false;
1051
1052   // See createPGOFuncNameVar for more details. To avoid link errors, profile
1053   // counters for function with available_externally linkage needs to be changed
1054   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1055   // created. Without using comdat, duplicate entries won't be removed by the
1056   // linker leading to increased data segement size and raw profile size. Even
1057   // worse, since the referenced counter from profile per-function data object
1058   // will be resolved to the common strong definition, the profile counts for
1059   // available_externally functions will end up being duplicated in raw profile
1060   // data. This can result in distorted profile as the counts of those dups
1061   // will be accumulated by the profile merger.
1062   GlobalValue::LinkageTypes Linkage = F.getLinkage();
1063   if (Linkage != GlobalValue::ExternalWeakLinkage &&
1064       Linkage != GlobalValue::AvailableExternallyLinkage)
1065     return false;
1066
1067   return true;
1068 }
1069
1070 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1071 bool isIRPGOFlagSet(const Module *M) {
1072   auto IRInstrVar =
1073       M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1074   if (!IRInstrVar || IRInstrVar->isDeclaration() ||
1075       IRInstrVar->hasLocalLinkage())
1076     return false;
1077
1078   // Check if the flag is set.
1079   if (!IRInstrVar->hasInitializer())
1080     return false;
1081
1082   const Constant *InitVal = IRInstrVar->getInitializer();
1083   if (!InitVal)
1084     return false;
1085
1086   return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
1087           VARIANT_MASK_IR_PROF) != 0;
1088 }
1089
1090 // Check if we can safely rename this Comdat function.
1091 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1092   if (F.getName().empty())
1093     return false;
1094   if (!needsComdatForCounter(F, *(F.getParent())))
1095     return false;
1096   // Unsafe to rename the address-taken function (which can be used in
1097   // function comparison).
1098   if (CheckAddressTaken && F.hasAddressTaken())
1099     return false;
1100   // Only safe to do if this function may be discarded if it is not used
1101   // in the compilation unit.
1102   if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1103     return false;
1104
1105   // For AvailableExternallyLinkage functions.
1106   if (!F.hasComdat()) {
1107     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1108     return true;
1109   }
1110   return true;
1111 }
1112
1113 // Parse the value profile options.
1114 void getMemOPSizeRangeFromOption(StringRef MemOPSizeRange, int64_t &RangeStart,
1115                                  int64_t &RangeLast) {
1116   static const int64_t DefaultMemOPSizeRangeStart = 0;
1117   static const int64_t DefaultMemOPSizeRangeLast = 8;
1118   RangeStart = DefaultMemOPSizeRangeStart;
1119   RangeLast = DefaultMemOPSizeRangeLast;
1120
1121   if (!MemOPSizeRange.empty()) {
1122     auto Pos = MemOPSizeRange.find(':');
1123     if (Pos != std::string::npos) {
1124       if (Pos > 0)
1125         MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
1126       if (Pos < MemOPSizeRange.size() - 1)
1127         MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
1128     } else
1129       MemOPSizeRange.getAsInteger(10, RangeLast);
1130   }
1131   assert(RangeLast >= RangeStart);
1132 }
1133
1134 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1135 // aware this is an ir_level profile so it can set the version flag.
1136 void createIRLevelProfileFlagVar(Module &M, bool IsCS) {
1137   const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1138   Type *IntTy64 = Type::getInt64Ty(M.getContext());
1139   uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1140   if (IsCS)
1141     ProfileVersion |= VARIANT_MASK_CSIR_PROF;
1142   auto IRLevelVersionVariable = new GlobalVariable(
1143       M, IntTy64, true, GlobalValue::WeakAnyLinkage,
1144       Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
1145   IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1146   Triple TT(M.getTargetTriple());
1147   if (TT.supportsCOMDAT()) {
1148     IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
1149     IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
1150   }
1151 }
1152
1153 // Create the variable for the profile file name.
1154 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1155   if (InstrProfileOutput.empty())
1156     return;
1157   Constant *ProfileNameConst =
1158       ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1159   GlobalVariable *ProfileNameVar = new GlobalVariable(
1160       M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1161       ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1162   Triple TT(M.getTargetTriple());
1163   if (TT.supportsCOMDAT()) {
1164     ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
1165     ProfileNameVar->setComdat(M.getOrInsertComdat(
1166         StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1167   }
1168 }
1169
1170 Error OverlapStats::accumuateCounts(const std::string &BaseFilename,
1171                                     const std::string &TestFilename,
1172                                     bool IsCS) {
1173   auto getProfileSum = [IsCS](const std::string &Filename,
1174                               CountSumOrPercent &Sum) -> Error {
1175     auto ReaderOrErr = InstrProfReader::create(Filename);
1176     if (Error E = ReaderOrErr.takeError()) {
1177       return E;
1178     }
1179     auto Reader = std::move(ReaderOrErr.get());
1180     Reader->accumuateCounts(Sum, IsCS);
1181     return Error::success();
1182   };
1183   auto Ret = getProfileSum(BaseFilename, Base);
1184   if (Ret)
1185     return Ret;
1186   Ret = getProfileSum(TestFilename, Test);
1187   if (Ret)
1188     return Ret;
1189   this->BaseFilename = &BaseFilename;
1190   this->TestFilename = &TestFilename;
1191   Valid = true;
1192   return Error::success();
1193 }
1194
1195 void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
1196   Mismatch.NumEntries += 1;
1197   Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1198   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1199     if (Test.ValueCounts[I] >= 1.0f)
1200       Mismatch.ValueCounts[I] +=
1201           MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1202   }
1203 }
1204
1205 void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
1206   Unique.NumEntries += 1;
1207   Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1208   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1209     if (Test.ValueCounts[I] >= 1.0f)
1210       Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1211   }
1212 }
1213
1214 void OverlapStats::dump(raw_fd_ostream &OS) const {
1215   if (!Valid)
1216     return;
1217
1218   const char *EntryName =
1219       (Level == ProgramLevel ? "functions" : "edge counters");
1220   if (Level == ProgramLevel) {
1221     OS << "Profile overlap infomation for base_profile: " << *BaseFilename
1222        << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1223   } else {
1224     OS << "Function level:\n"
1225        << "  Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1226   }
1227
1228   OS << "  # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1229   if (Mismatch.NumEntries)
1230     OS << "  # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1231        << "\n";
1232   if (Unique.NumEntries)
1233     OS << "  # of " << EntryName
1234        << " only in test_profile: " << Unique.NumEntries << "\n";
1235
1236   OS << "  Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1237      << "\n";
1238   if (Mismatch.NumEntries)
1239     OS << "  Mismatched count percentage (Edge): "
1240        << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1241   if (Unique.NumEntries)
1242     OS << "  Percentage of Edge profile only in test_profile: "
1243        << format("%.3f%%", Unique.CountSum * 100) << "\n";
1244   OS << "  Edge profile base count sum: " << format("%.0f", Base.CountSum)
1245      << "\n"
1246      << "  Edge profile test count sum: " << format("%.0f", Test.CountSum)
1247      << "\n";
1248
1249   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1250     if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1251       continue;
1252     char ProfileKindName[20];
1253     switch (I) {
1254     case IPVK_IndirectCallTarget:
1255       strncpy(ProfileKindName, "IndirectCall", 19);
1256       break;
1257     case IPVK_MemOPSize:
1258       strncpy(ProfileKindName, "MemOP", 19);
1259       break;
1260     default:
1261       snprintf(ProfileKindName, 19, "VP[%d]", I);
1262       break;
1263     }
1264     OS << "  " << ProfileKindName
1265        << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1266        << "\n";
1267     if (Mismatch.NumEntries)
1268       OS << "  Mismatched count percentage (" << ProfileKindName
1269          << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1270     if (Unique.NumEntries)
1271       OS << "  Percentage of " << ProfileKindName
1272          << " profile only in test_profile: "
1273          << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1274     OS << "  " << ProfileKindName
1275        << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1276        << "\n"
1277        << "  " << ProfileKindName
1278        << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1279        << "\n";
1280   }
1281 }
1282
1283 } // end namespace llvm