1 //===- InstrProf.cpp - Instrumented profiling format support --------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains support for clang's instrumentation based PGO and
12 //===----------------------------------------------------------------------===//
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"
52 #include <system_error>
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."));
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.
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."));
76 static std::string
getInstrProfErrString(instrprof_error Err
) {
78 case instrprof_error::success
:
80 case instrprof_error::eof
:
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";
117 llvm_unreachable("A value of instrprof_error has no message.");
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"; }
128 std::string
message(int IE
) const override
{
129 return getInstrProfErrString(static_cast<instrprof_error
>(IE
));
133 } // end anonymous namespace
135 static ManagedStatic
<InstrProfErrorCategoryType
> ErrorCategory
;
137 const std::error_category
&llvm::instrprof_category() {
138 return *ErrorCategory
;
143 const char *InstrProfSectNameCommon
[] = {
144 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
146 #include "llvm/ProfileData/InstrProfData.inc"
149 const char *InstrProfSectNameCoff
[] = {
150 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
152 #include "llvm/ProfileData/InstrProfData.inc"
155 const char *InstrProfSectNamePrefix
[] = {
156 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
158 #include "llvm/ProfileData/InstrProfData.inc"
165 std::string
getInstrProfSectionName(InstrProfSectKind IPSK
,
166 Triple::ObjectFormatType OF
,
167 bool AddSegmentInfo
) {
168 std::string SectName
;
170 if (OF
== Triple::MachO
&& AddSegmentInfo
)
171 SectName
= InstrProfSectNamePrefix
[IPSK
];
173 if (OF
== Triple::COFF
)
174 SectName
+= InstrProfSectNameCoff
[IPSK
];
176 SectName
+= InstrProfSectNameCommon
[IPSK
];
178 if (OF
== Triple::MachO
&& IPSK
== IPSK_data
&& AddSegmentInfo
)
179 SectName
+= ",regular,live_support";
184 void SoftInstrProfErrors::addError(instrprof_error IE
) {
185 if (IE
== instrprof_error::success
)
188 if (FirstError
== instrprof_error::success
)
192 case instrprof_error::hash_mismatch
:
195 case instrprof_error::count_mismatch
:
196 ++NumCountMismatches
;
198 case instrprof_error::counter_overflow
:
199 ++NumCounterOverflows
;
201 case instrprof_error::value_site_count_mismatch
:
202 ++NumValueSiteCountMismatches
;
205 llvm_unreachable("Not a soft error");
209 std::string
InstrProfError::message() const {
210 return getInstrProfErrString(Err
);
213 char InstrProfError::ID
= 0;
215 std::string
getPGOFuncName(StringRef RawFuncName
,
216 GlobalValue::LinkageTypes Linkage
,
218 uint64_t Version LLVM_ATTRIBUTE_UNUSED
) {
219 return GlobalValue::getGlobalIdentifier(RawFuncName
, Linkage
, FileName
);
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
) {
230 if (llvm::sys::path::is_separator(CI
)) {
237 return PathNameStr
.substr(LastPos
);
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
) {
255 StringRef
FileName(F
.getParent()->getSourceFileName());
256 uint32_t StripLevel
= StaticFuncFullModulePrefix
? 0 : (uint32_t)-1;
257 if (StripLevel
< StaticFuncStripDirNamePrefix
)
258 StripLevel
= StaticFuncStripDirNamePrefix
;
260 FileName
= stripDirPrefix(FileName
, StripLevel
);
261 return getPGOFuncName(F
.getName(), F
.getLinkage(), FileName
, Version
);
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();
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
, "");
276 StringRef
getFuncNameWithoutPrefix(StringRef PGOFuncName
, StringRef FileName
) {
277 if (FileName
.empty())
279 // Drop the file name including ':'. See also getPGOFuncName.
280 if (PGOFuncName
.startswith(FileName
))
281 PGOFuncName
= PGOFuncName
.drop_front(FileName
.size() + 1);
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();
292 if (!GlobalValue::isLocalLinkage(Linkage
))
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);
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
;
320 ConstantDataArray::getString(M
.getContext(), PGOFuncName
, false);
322 new GlobalVariable(M
, Value
->getType(), true, Linkage
, Value
,
323 getPGOFuncNameVarName(PGOFuncName
, Linkage
));
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
);
332 GlobalVariable
*createPGOFuncNameVar(Function
&F
, StringRef PGOFuncName
) {
333 return createPGOFuncNameVar(*F
.getParent(), F
.getLinkage(), PGOFuncName
);
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.
342 const std::string
&PGOFuncName
= getPGOFuncName(F
, InLTO
);
343 if (Error E
= addFuncName(PGOFuncName
))
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.
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
))
355 MD5FuncMap
.emplace_back(Function::getGUID(OtherFuncName
), &F
);
361 return Error::success();
364 uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address
) {
366 auto It
= partition_point(AddrToMD5Map
, [=](std::pair
<uint64_t, uint64_t> A
) {
367 return A
.first
< Address
;
369 // Raw function pointer collected by value profiler may be from
370 // external functions that are not instrumented. They won't have
371 // mapping data to be used by the deserializer. Force the value to
372 // be 0 in this case.
373 if (It
!= AddrToMD5Map
.end() && It
->first
== Address
)
374 return (uint64_t)It
->second
;
378 Error
collectPGOFuncNameStrings(ArrayRef
<std::string
> NameStrs
,
379 bool doCompression
, std::string
&Result
) {
380 assert(!NameStrs
.empty() && "No name data to emit");
382 uint8_t Header
[16], *P
= Header
;
383 std::string UncompressedNameStrings
=
384 join(NameStrs
.begin(), NameStrs
.end(), getInstrProfNameSeparator());
386 assert(StringRef(UncompressedNameStrings
)
387 .count(getInstrProfNameSeparator()) == (NameStrs
.size() - 1) &&
388 "PGO name is invalid (contains separator token)");
390 unsigned EncLen
= encodeULEB128(UncompressedNameStrings
.length(), P
);
393 auto WriteStringToResult
= [&](size_t CompressedLen
, StringRef InputStr
) {
394 EncLen
= encodeULEB128(CompressedLen
, P
);
396 char *HeaderStr
= reinterpret_cast<char *>(&Header
[0]);
397 unsigned HeaderLen
= P
- &Header
[0];
398 Result
.append(HeaderStr
, HeaderLen
);
400 return Error::success();
403 if (!doCompression
) {
404 return WriteStringToResult(0, UncompressedNameStrings
);
407 SmallString
<128> CompressedNameStrings
;
408 Error E
= zlib::compress(StringRef(UncompressedNameStrings
),
409 CompressedNameStrings
, zlib::BestSizeCompression
);
411 consumeError(std::move(E
));
412 return make_error
<InstrProfError
>(instrprof_error::compress_failed
);
415 return WriteStringToResult(CompressedNameStrings
.size(),
416 CompressedNameStrings
);
419 StringRef
getPGOFuncNameVarInitializer(GlobalVariable
*NameVar
) {
420 auto *Arr
= cast
<ConstantDataArray
>(NameVar
->getInitializer());
422 Arr
->isCString() ? Arr
->getAsCString() : Arr
->getAsString();
426 Error
collectPGOFuncNameStrings(ArrayRef
<GlobalVariable
*> NameVars
,
427 std::string
&Result
, bool doCompression
) {
428 std::vector
<std::string
> NameStrs
;
429 for (auto *NameVar
: NameVars
) {
430 NameStrs
.push_back(getPGOFuncNameVarInitializer(NameVar
));
432 return collectPGOFuncNameStrings(
433 NameStrs
, zlib::isAvailable() && doCompression
, Result
);
436 Error
readPGOFuncNameStrings(StringRef NameStrings
, InstrProfSymtab
&Symtab
) {
437 const uint8_t *P
= NameStrings
.bytes_begin();
438 const uint8_t *EndP
= NameStrings
.bytes_end();
441 uint64_t UncompressedSize
= decodeULEB128(P
, &N
);
443 uint64_t CompressedSize
= decodeULEB128(P
, &N
);
445 bool isCompressed
= (CompressedSize
!= 0);
446 SmallString
<128> UncompressedNameStrings
;
447 StringRef NameStrings
;
449 if (!llvm::zlib::isAvailable())
450 return make_error
<InstrProfError
>(instrprof_error::zlib_unavailable
);
452 StringRef
CompressedNameStrings(reinterpret_cast<const char *>(P
),
455 zlib::uncompress(CompressedNameStrings
, UncompressedNameStrings
,
457 consumeError(std::move(E
));
458 return make_error
<InstrProfError
>(instrprof_error::uncompress_failed
);
461 NameStrings
= StringRef(UncompressedNameStrings
.data(),
462 UncompressedNameStrings
.size());
465 StringRef(reinterpret_cast<const char *>(P
), UncompressedSize
);
466 P
+= UncompressedSize
;
468 // Now parse the name strings.
469 SmallVector
<StringRef
, 0> Names
;
470 NameStrings
.split(Names
, getInstrProfNameSeparator());
471 for (StringRef
&Name
: Names
)
472 if (Error E
= Symtab
.addFuncName(Name
))
475 while (P
< EndP
&& *P
== 0)
478 return Error::success();
481 void InstrProfRecord::accumulateCounts(CountSumOrPercent
&Sum
) const {
482 uint64_t FuncSum
= 0;
483 Sum
.NumEntries
+= Counts
.size();
484 for (size_t F
= 0, E
= Counts
.size(); F
< E
; ++F
)
485 FuncSum
+= Counts
[F
];
486 Sum
.CountSum
+= FuncSum
;
488 for (uint32_t VK
= IPVK_First
; VK
<= IPVK_Last
; ++VK
) {
489 uint64_t KindSum
= 0;
490 uint32_t NumValueSites
= getNumValueSites(VK
);
491 for (size_t I
= 0; I
< NumValueSites
; ++I
) {
492 uint32_t NV
= getNumValueDataForSite(VK
, I
);
493 std::unique_ptr
<InstrProfValueData
[]> VD
= getValueForSite(VK
, I
);
494 for (uint32_t V
= 0; V
< NV
; V
++)
495 KindSum
+= VD
[V
].Count
;
497 Sum
.ValueCounts
[VK
] += KindSum
;
501 void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord
&Input
,
503 OverlapStats
&Overlap
,
504 OverlapStats
&FuncLevelOverlap
) {
505 this->sortByTargetValues();
506 Input
.sortByTargetValues();
507 double Score
= 0.0f
, FuncLevelScore
= 0.0f
;
508 auto I
= ValueData
.begin();
509 auto IE
= ValueData
.end();
510 auto J
= Input
.ValueData
.begin();
511 auto JE
= Input
.ValueData
.end();
512 while (I
!= IE
&& J
!= JE
) {
513 if (I
->Value
== J
->Value
) {
514 Score
+= OverlapStats::score(I
->Count
, J
->Count
,
515 Overlap
.Base
.ValueCounts
[ValueKind
],
516 Overlap
.Test
.ValueCounts
[ValueKind
]);
517 FuncLevelScore
+= OverlapStats::score(
518 I
->Count
, J
->Count
, FuncLevelOverlap
.Base
.ValueCounts
[ValueKind
],
519 FuncLevelOverlap
.Test
.ValueCounts
[ValueKind
]);
521 } else if (I
->Value
< J
->Value
) {
527 Overlap
.Overlap
.ValueCounts
[ValueKind
] += Score
;
528 FuncLevelOverlap
.Overlap
.ValueCounts
[ValueKind
] += FuncLevelScore
;
531 // Return false on mismatch.
532 void InstrProfRecord::overlapValueProfData(uint32_t ValueKind
,
533 InstrProfRecord
&Other
,
534 OverlapStats
&Overlap
,
535 OverlapStats
&FuncLevelOverlap
) {
536 uint32_t ThisNumValueSites
= getNumValueSites(ValueKind
);
537 assert(ThisNumValueSites
== Other
.getNumValueSites(ValueKind
));
538 if (!ThisNumValueSites
)
541 std::vector
<InstrProfValueSiteRecord
> &ThisSiteRecords
=
542 getOrCreateValueSitesForKind(ValueKind
);
543 MutableArrayRef
<InstrProfValueSiteRecord
> OtherSiteRecords
=
544 Other
.getValueSitesForKind(ValueKind
);
545 for (uint32_t I
= 0; I
< ThisNumValueSites
; I
++)
546 ThisSiteRecords
[I
].overlap(OtherSiteRecords
[I
], ValueKind
, Overlap
,
550 void InstrProfRecord::overlap(InstrProfRecord
&Other
, OverlapStats
&Overlap
,
551 OverlapStats
&FuncLevelOverlap
,
552 uint64_t ValueCutoff
) {
553 // FuncLevel CountSum for other should already computed and nonzero.
554 assert(FuncLevelOverlap
.Test
.CountSum
>= 1.0f
);
555 accumulateCounts(FuncLevelOverlap
.Base
);
556 bool Mismatch
= (Counts
.size() != Other
.Counts
.size());
558 // Check if the value profiles mismatch.
560 for (uint32_t Kind
= IPVK_First
; Kind
<= IPVK_Last
; ++Kind
) {
561 uint32_t ThisNumValueSites
= getNumValueSites(Kind
);
562 uint32_t OtherNumValueSites
= Other
.getNumValueSites(Kind
);
563 if (ThisNumValueSites
!= OtherNumValueSites
) {
570 Overlap
.addOneMismatch(FuncLevelOverlap
.Test
);
574 // Compute overlap for value counts.
575 for (uint32_t Kind
= IPVK_First
; Kind
<= IPVK_Last
; ++Kind
)
576 overlapValueProfData(Kind
, Other
, Overlap
, FuncLevelOverlap
);
579 uint64_t MaxCount
= 0;
580 // Compute overlap for edge counts.
581 for (size_t I
= 0, E
= Other
.Counts
.size(); I
< E
; ++I
) {
582 Score
+= OverlapStats::score(Counts
[I
], Other
.Counts
[I
],
583 Overlap
.Base
.CountSum
, Overlap
.Test
.CountSum
);
584 MaxCount
= std::max(Other
.Counts
[I
], MaxCount
);
586 Overlap
.Overlap
.CountSum
+= Score
;
587 Overlap
.Overlap
.NumEntries
+= 1;
589 if (MaxCount
>= ValueCutoff
) {
590 double FuncScore
= 0.0;
591 for (size_t I
= 0, E
= Other
.Counts
.size(); I
< E
; ++I
)
592 FuncScore
+= OverlapStats::score(Counts
[I
], Other
.Counts
[I
],
593 FuncLevelOverlap
.Base
.CountSum
,
594 FuncLevelOverlap
.Test
.CountSum
);
595 FuncLevelOverlap
.Overlap
.CountSum
= FuncScore
;
596 FuncLevelOverlap
.Overlap
.NumEntries
= Other
.Counts
.size();
597 FuncLevelOverlap
.Valid
= true;
601 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord
&Input
,
603 function_ref
<void(instrprof_error
)> Warn
) {
604 this->sortByTargetValues();
605 Input
.sortByTargetValues();
606 auto I
= ValueData
.begin();
607 auto IE
= ValueData
.end();
608 for (auto J
= Input
.ValueData
.begin(), JE
= Input
.ValueData
.end(); J
!= JE
;
610 while (I
!= IE
&& I
->Value
< J
->Value
)
612 if (I
!= IE
&& I
->Value
== J
->Value
) {
614 I
->Count
= SaturatingMultiplyAdd(J
->Count
, Weight
, I
->Count
, &Overflowed
);
616 Warn(instrprof_error::counter_overflow
);
620 ValueData
.insert(I
, *J
);
624 void InstrProfValueSiteRecord::scale(uint64_t Weight
,
625 function_ref
<void(instrprof_error
)> Warn
) {
626 for (auto I
= ValueData
.begin(), IE
= ValueData
.end(); I
!= IE
; ++I
) {
628 I
->Count
= SaturatingMultiply(I
->Count
, Weight
, &Overflowed
);
630 Warn(instrprof_error::counter_overflow
);
634 // Merge Value Profile data from Src record to this record for ValueKind.
635 // Scale merged value counts by \p Weight.
636 void InstrProfRecord::mergeValueProfData(
637 uint32_t ValueKind
, InstrProfRecord
&Src
, uint64_t Weight
,
638 function_ref
<void(instrprof_error
)> Warn
) {
639 uint32_t ThisNumValueSites
= getNumValueSites(ValueKind
);
640 uint32_t OtherNumValueSites
= Src
.getNumValueSites(ValueKind
);
641 if (ThisNumValueSites
!= OtherNumValueSites
) {
642 Warn(instrprof_error::value_site_count_mismatch
);
645 if (!ThisNumValueSites
)
647 std::vector
<InstrProfValueSiteRecord
> &ThisSiteRecords
=
648 getOrCreateValueSitesForKind(ValueKind
);
649 MutableArrayRef
<InstrProfValueSiteRecord
> OtherSiteRecords
=
650 Src
.getValueSitesForKind(ValueKind
);
651 for (uint32_t I
= 0; I
< ThisNumValueSites
; I
++)
652 ThisSiteRecords
[I
].merge(OtherSiteRecords
[I
], Weight
, Warn
);
655 void InstrProfRecord::merge(InstrProfRecord
&Other
, uint64_t Weight
,
656 function_ref
<void(instrprof_error
)> Warn
) {
657 // If the number of counters doesn't match we either have bad data
658 // or a hash collision.
659 if (Counts
.size() != Other
.Counts
.size()) {
660 Warn(instrprof_error::count_mismatch
);
664 for (size_t I
= 0, E
= Other
.Counts
.size(); I
< E
; ++I
) {
667 SaturatingMultiplyAdd(Other
.Counts
[I
], Weight
, Counts
[I
], &Overflowed
);
669 Warn(instrprof_error::counter_overflow
);
672 for (uint32_t Kind
= IPVK_First
; Kind
<= IPVK_Last
; ++Kind
)
673 mergeValueProfData(Kind
, Other
, Weight
, Warn
);
676 void InstrProfRecord::scaleValueProfData(
677 uint32_t ValueKind
, uint64_t Weight
,
678 function_ref
<void(instrprof_error
)> Warn
) {
679 for (auto &R
: getValueSitesForKind(ValueKind
))
680 R
.scale(Weight
, Warn
);
683 void InstrProfRecord::scale(uint64_t Weight
,
684 function_ref
<void(instrprof_error
)> Warn
) {
685 for (auto &Count
: this->Counts
) {
687 Count
= SaturatingMultiply(Count
, Weight
, &Overflowed
);
689 Warn(instrprof_error::counter_overflow
);
691 for (uint32_t Kind
= IPVK_First
; Kind
<= IPVK_Last
; ++Kind
)
692 scaleValueProfData(Kind
, Weight
, Warn
);
695 // Map indirect call target name hash to name string.
696 uint64_t InstrProfRecord::remapValue(uint64_t Value
, uint32_t ValueKind
,
697 InstrProfSymtab
*SymTab
) {
701 if (ValueKind
== IPVK_IndirectCallTarget
)
702 return SymTab
->getFunctionHashFromAddress(Value
);
707 void InstrProfRecord::addValueData(uint32_t ValueKind
, uint32_t Site
,
708 InstrProfValueData
*VData
, uint32_t N
,
709 InstrProfSymtab
*ValueMap
) {
710 for (uint32_t I
= 0; I
< N
; I
++) {
711 VData
[I
].Value
= remapValue(VData
[I
].Value
, ValueKind
, ValueMap
);
713 std::vector
<InstrProfValueSiteRecord
> &ValueSites
=
714 getOrCreateValueSitesForKind(ValueKind
);
716 ValueSites
.emplace_back();
718 ValueSites
.emplace_back(VData
, VData
+ N
);
721 #define INSTR_PROF_COMMON_API_IMPL
722 #include "llvm/ProfileData/InstrProfData.inc"
725 * ValueProfRecordClosure Interface implementation for InstrProfRecord
726 * class. These C wrappers are used as adaptors so that C++ code can be
727 * invoked as callbacks.
729 uint32_t getNumValueKindsInstrProf(const void *Record
) {
730 return reinterpret_cast<const InstrProfRecord
*>(Record
)->getNumValueKinds();
733 uint32_t getNumValueSitesInstrProf(const void *Record
, uint32_t VKind
) {
734 return reinterpret_cast<const InstrProfRecord
*>(Record
)
735 ->getNumValueSites(VKind
);
738 uint32_t getNumValueDataInstrProf(const void *Record
, uint32_t VKind
) {
739 return reinterpret_cast<const InstrProfRecord
*>(Record
)
740 ->getNumValueData(VKind
);
743 uint32_t getNumValueDataForSiteInstrProf(const void *R
, uint32_t VK
,
745 return reinterpret_cast<const InstrProfRecord
*>(R
)
746 ->getNumValueDataForSite(VK
, S
);
749 void getValueForSiteInstrProf(const void *R
, InstrProfValueData
*Dst
,
750 uint32_t K
, uint32_t S
) {
751 reinterpret_cast<const InstrProfRecord
*>(R
)->getValueForSite(Dst
, K
, S
);
754 ValueProfData
*allocValueProfDataInstrProf(size_t TotalSizeInBytes
) {
756 (ValueProfData
*)(new (::operator new(TotalSizeInBytes
)) ValueProfData());
757 memset(VD
, 0, TotalSizeInBytes
);
761 static ValueProfRecordClosure InstrProfRecordClosure
= {
763 getNumValueKindsInstrProf
,
764 getNumValueSitesInstrProf
,
765 getNumValueDataInstrProf
,
766 getNumValueDataForSiteInstrProf
,
768 getValueForSiteInstrProf
,
769 allocValueProfDataInstrProf
};
771 // Wrapper implementation using the closure mechanism.
772 uint32_t ValueProfData::getSize(const InstrProfRecord
&Record
) {
773 auto Closure
= InstrProfRecordClosure
;
774 Closure
.Record
= &Record
;
775 return getValueProfDataSize(&Closure
);
778 // Wrapper implementation using the closure mechanism.
779 std::unique_ptr
<ValueProfData
>
780 ValueProfData::serializeFrom(const InstrProfRecord
&Record
) {
781 InstrProfRecordClosure
.Record
= &Record
;
783 std::unique_ptr
<ValueProfData
> VPD(
784 serializeValueProfDataFrom(&InstrProfRecordClosure
, nullptr));
788 void ValueProfRecord::deserializeTo(InstrProfRecord
&Record
,
789 InstrProfSymtab
*SymTab
) {
790 Record
.reserveSites(Kind
, NumValueSites
);
792 InstrProfValueData
*ValueData
= getValueProfRecordValueData(this);
793 for (uint64_t VSite
= 0; VSite
< NumValueSites
; ++VSite
) {
794 uint8_t ValueDataCount
= this->SiteCountArray
[VSite
];
795 Record
.addValueData(Kind
, VSite
, ValueData
, ValueDataCount
, SymTab
);
796 ValueData
+= ValueDataCount
;
800 // For writing/serializing, Old is the host endianness, and New is
801 // byte order intended on disk. For Reading/deserialization, Old
802 // is the on-disk source endianness, and New is the host endianness.
803 void ValueProfRecord::swapBytes(support::endianness Old
,
804 support::endianness New
) {
805 using namespace support
;
810 if (getHostEndianness() != Old
) {
811 sys::swapByteOrder
<uint32_t>(NumValueSites
);
812 sys::swapByteOrder
<uint32_t>(Kind
);
814 uint32_t ND
= getValueProfRecordNumValueData(this);
815 InstrProfValueData
*VD
= getValueProfRecordValueData(this);
817 // No need to swap byte array: SiteCountArrray.
818 for (uint32_t I
= 0; I
< ND
; I
++) {
819 sys::swapByteOrder
<uint64_t>(VD
[I
].Value
);
820 sys::swapByteOrder
<uint64_t>(VD
[I
].Count
);
822 if (getHostEndianness() == Old
) {
823 sys::swapByteOrder
<uint32_t>(NumValueSites
);
824 sys::swapByteOrder
<uint32_t>(Kind
);
828 void ValueProfData::deserializeTo(InstrProfRecord
&Record
,
829 InstrProfSymtab
*SymTab
) {
830 if (NumValueKinds
== 0)
833 ValueProfRecord
*VR
= getFirstValueProfRecord(this);
834 for (uint32_t K
= 0; K
< NumValueKinds
; K
++) {
835 VR
->deserializeTo(Record
, SymTab
);
836 VR
= getValueProfRecordNext(VR
);
841 static T
swapToHostOrder(const unsigned char *&D
, support::endianness Orig
) {
842 using namespace support
;
845 return endian::readNext
<T
, little
, unaligned
>(D
);
847 return endian::readNext
<T
, big
, unaligned
>(D
);
850 static std::unique_ptr
<ValueProfData
> allocValueProfData(uint32_t TotalSize
) {
851 return std::unique_ptr
<ValueProfData
>(new (::operator new(TotalSize
))
855 Error
ValueProfData::checkIntegrity() {
856 if (NumValueKinds
> IPVK_Last
+ 1)
857 return make_error
<InstrProfError
>(instrprof_error::malformed
);
858 // Total size needs to be mulltiple of quadword size.
859 if (TotalSize
% sizeof(uint64_t))
860 return make_error
<InstrProfError
>(instrprof_error::malformed
);
862 ValueProfRecord
*VR
= getFirstValueProfRecord(this);
863 for (uint32_t K
= 0; K
< this->NumValueKinds
; K
++) {
864 if (VR
->Kind
> IPVK_Last
)
865 return make_error
<InstrProfError
>(instrprof_error::malformed
);
866 VR
= getValueProfRecordNext(VR
);
867 if ((char *)VR
- (char *)this > (ptrdiff_t)TotalSize
)
868 return make_error
<InstrProfError
>(instrprof_error::malformed
);
870 return Error::success();
873 Expected
<std::unique_ptr
<ValueProfData
>>
874 ValueProfData::getValueProfData(const unsigned char *D
,
875 const unsigned char *const BufferEnd
,
876 support::endianness Endianness
) {
877 using namespace support
;
879 if (D
+ sizeof(ValueProfData
) > BufferEnd
)
880 return make_error
<InstrProfError
>(instrprof_error::truncated
);
882 const unsigned char *Header
= D
;
883 uint32_t TotalSize
= swapToHostOrder
<uint32_t>(Header
, Endianness
);
884 if (D
+ TotalSize
> BufferEnd
)
885 return make_error
<InstrProfError
>(instrprof_error::too_large
);
887 std::unique_ptr
<ValueProfData
> VPD
= allocValueProfData(TotalSize
);
888 memcpy(VPD
.get(), D
, TotalSize
);
890 VPD
->swapBytesToHost(Endianness
);
892 Error E
= VPD
->checkIntegrity();
896 return std::move(VPD
);
899 void ValueProfData::swapBytesToHost(support::endianness Endianness
) {
900 using namespace support
;
902 if (Endianness
== getHostEndianness())
905 sys::swapByteOrder
<uint32_t>(TotalSize
);
906 sys::swapByteOrder
<uint32_t>(NumValueKinds
);
908 ValueProfRecord
*VR
= getFirstValueProfRecord(this);
909 for (uint32_t K
= 0; K
< NumValueKinds
; K
++) {
910 VR
->swapBytes(Endianness
, getHostEndianness());
911 VR
= getValueProfRecordNext(VR
);
915 void ValueProfData::swapBytesFromHost(support::endianness Endianness
) {
916 using namespace support
;
918 if (Endianness
== getHostEndianness())
921 ValueProfRecord
*VR
= getFirstValueProfRecord(this);
922 for (uint32_t K
= 0; K
< NumValueKinds
; K
++) {
923 ValueProfRecord
*NVR
= getValueProfRecordNext(VR
);
924 VR
->swapBytes(getHostEndianness(), Endianness
);
927 sys::swapByteOrder
<uint32_t>(TotalSize
);
928 sys::swapByteOrder
<uint32_t>(NumValueKinds
);
931 void annotateValueSite(Module
&M
, Instruction
&Inst
,
932 const InstrProfRecord
&InstrProfR
,
933 InstrProfValueKind ValueKind
, uint32_t SiteIdx
,
934 uint32_t MaxMDCount
) {
935 uint32_t NV
= InstrProfR
.getNumValueDataForSite(ValueKind
, SiteIdx
);
940 std::unique_ptr
<InstrProfValueData
[]> VD
=
941 InstrProfR
.getValueForSite(ValueKind
, SiteIdx
, &Sum
);
943 ArrayRef
<InstrProfValueData
> VDs(VD
.get(), NV
);
944 annotateValueSite(M
, Inst
, VDs
, Sum
, ValueKind
, MaxMDCount
);
947 void annotateValueSite(Module
&M
, Instruction
&Inst
,
948 ArrayRef
<InstrProfValueData
> VDs
,
949 uint64_t Sum
, InstrProfValueKind ValueKind
,
950 uint32_t MaxMDCount
) {
951 LLVMContext
&Ctx
= M
.getContext();
952 MDBuilder
MDHelper(Ctx
);
953 SmallVector
<Metadata
*, 3> Vals
;
955 Vals
.push_back(MDHelper
.createString("VP"));
957 Vals
.push_back(MDHelper
.createConstant(
958 ConstantInt::get(Type::getInt32Ty(Ctx
), ValueKind
)));
961 MDHelper
.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx
), Sum
)));
963 // Value Profile Data
964 uint32_t MDCount
= MaxMDCount
;
965 for (auto &VD
: VDs
) {
966 Vals
.push_back(MDHelper
.createConstant(
967 ConstantInt::get(Type::getInt64Ty(Ctx
), VD
.Value
)));
968 Vals
.push_back(MDHelper
.createConstant(
969 ConstantInt::get(Type::getInt64Ty(Ctx
), VD
.Count
)));
973 Inst
.setMetadata(LLVMContext::MD_prof
, MDNode::get(Ctx
, Vals
));
976 bool getValueProfDataFromInst(const Instruction
&Inst
,
977 InstrProfValueKind ValueKind
,
978 uint32_t MaxNumValueData
,
979 InstrProfValueData ValueData
[],
980 uint32_t &ActualNumValueData
, uint64_t &TotalC
) {
981 MDNode
*MD
= Inst
.getMetadata(LLVMContext::MD_prof
);
985 unsigned NOps
= MD
->getNumOperands();
990 // Operand 0 is a string tag "VP":
991 MDString
*Tag
= cast
<MDString
>(MD
->getOperand(0));
995 if (!Tag
->getString().equals("VP"))
999 ConstantInt
*KindInt
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(1));
1002 if (KindInt
->getZExtValue() != ValueKind
)
1006 ConstantInt
*TotalCInt
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(2));
1009 TotalC
= TotalCInt
->getZExtValue();
1011 ActualNumValueData
= 0;
1013 for (unsigned I
= 3; I
< NOps
; I
+= 2) {
1014 if (ActualNumValueData
>= MaxNumValueData
)
1016 ConstantInt
*Value
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(I
));
1017 ConstantInt
*Count
=
1018 mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(I
+ 1));
1019 if (!Value
|| !Count
)
1021 ValueData
[ActualNumValueData
].Value
= Value
->getZExtValue();
1022 ValueData
[ActualNumValueData
].Count
= Count
->getZExtValue();
1023 ActualNumValueData
++;
1028 MDNode
*getPGOFuncNameMetadata(const Function
&F
) {
1029 return F
.getMetadata(getPGOFuncNameMetadataName());
1032 void createPGOFuncNameMetadata(Function
&F
, StringRef PGOFuncName
) {
1033 // Only for internal linkage functions.
1034 if (PGOFuncName
== F
.getName())
1036 // Don't create duplicated meta-data.
1037 if (getPGOFuncNameMetadata(F
))
1039 LLVMContext
&C
= F
.getContext();
1040 MDNode
*N
= MDNode::get(C
, MDString::get(C
, PGOFuncName
));
1041 F
.setMetadata(getPGOFuncNameMetadataName(), N
);
1044 bool needsComdatForCounter(const Function
&F
, const Module
&M
) {
1048 if (!Triple(M
.getTargetTriple()).supportsCOMDAT())
1051 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1052 // counters for function with available_externally linkage needs to be changed
1053 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1054 // created. Without using comdat, duplicate entries won't be removed by the
1055 // linker leading to increased data segement size and raw profile size. Even
1056 // worse, since the referenced counter from profile per-function data object
1057 // will be resolved to the common strong definition, the profile counts for
1058 // available_externally functions will end up being duplicated in raw profile
1059 // data. This can result in distorted profile as the counts of those dups
1060 // will be accumulated by the profile merger.
1061 GlobalValue::LinkageTypes Linkage
= F
.getLinkage();
1062 if (Linkage
!= GlobalValue::ExternalWeakLinkage
&&
1063 Linkage
!= GlobalValue::AvailableExternallyLinkage
)
1069 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1070 bool isIRPGOFlagSet(const Module
*M
) {
1072 M
->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR
));
1073 if (!IRInstrVar
|| IRInstrVar
->isDeclaration() ||
1074 IRInstrVar
->hasLocalLinkage())
1077 // Check if the flag is set.
1078 if (!IRInstrVar
->hasInitializer())
1081 auto *InitVal
= dyn_cast_or_null
<ConstantInt
>(IRInstrVar
->getInitializer());
1084 return (InitVal
->getZExtValue() & VARIANT_MASK_IR_PROF
) != 0;
1087 // Check if we can safely rename this Comdat function.
1088 bool canRenameComdatFunc(const Function
&F
, bool CheckAddressTaken
) {
1089 if (F
.getName().empty())
1091 if (!needsComdatForCounter(F
, *(F
.getParent())))
1093 // Unsafe to rename the address-taken function (which can be used in
1094 // function comparison).
1095 if (CheckAddressTaken
&& F
.hasAddressTaken())
1097 // Only safe to do if this function may be discarded if it is not used
1098 // in the compilation unit.
1099 if (!GlobalValue::isDiscardableIfUnused(F
.getLinkage()))
1102 // For AvailableExternallyLinkage functions.
1103 if (!F
.hasComdat()) {
1104 assert(F
.getLinkage() == GlobalValue::AvailableExternallyLinkage
);
1110 // Parse the value profile options.
1111 void getMemOPSizeRangeFromOption(StringRef MemOPSizeRange
, int64_t &RangeStart
,
1112 int64_t &RangeLast
) {
1113 static const int64_t DefaultMemOPSizeRangeStart
= 0;
1114 static const int64_t DefaultMemOPSizeRangeLast
= 8;
1115 RangeStart
= DefaultMemOPSizeRangeStart
;
1116 RangeLast
= DefaultMemOPSizeRangeLast
;
1118 if (!MemOPSizeRange
.empty()) {
1119 auto Pos
= MemOPSizeRange
.find(':');
1120 if (Pos
!= std::string::npos
) {
1122 MemOPSizeRange
.substr(0, Pos
).getAsInteger(10, RangeStart
);
1123 if (Pos
< MemOPSizeRange
.size() - 1)
1124 MemOPSizeRange
.substr(Pos
+ 1).getAsInteger(10, RangeLast
);
1126 MemOPSizeRange
.getAsInteger(10, RangeLast
);
1128 assert(RangeLast
>= RangeStart
);
1131 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1132 // aware this is an ir_level profile so it can set the version flag.
1133 void createIRLevelProfileFlagVar(Module
&M
, bool IsCS
) {
1134 const StringRef
VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR
));
1135 Type
*IntTy64
= Type::getInt64Ty(M
.getContext());
1136 uint64_t ProfileVersion
= (INSTR_PROF_RAW_VERSION
| VARIANT_MASK_IR_PROF
);
1138 ProfileVersion
|= VARIANT_MASK_CSIR_PROF
;
1139 auto IRLevelVersionVariable
= new GlobalVariable(
1140 M
, IntTy64
, true, GlobalValue::WeakAnyLinkage
,
1141 Constant::getIntegerValue(IntTy64
, APInt(64, ProfileVersion
)), VarName
);
1142 IRLevelVersionVariable
->setVisibility(GlobalValue::DefaultVisibility
);
1143 Triple
TT(M
.getTargetTriple());
1144 if (TT
.supportsCOMDAT()) {
1145 IRLevelVersionVariable
->setLinkage(GlobalValue::ExternalLinkage
);
1146 IRLevelVersionVariable
->setComdat(M
.getOrInsertComdat(VarName
));
1150 // Create the variable for the profile file name.
1151 void createProfileFileNameVar(Module
&M
, StringRef InstrProfileOutput
) {
1152 if (InstrProfileOutput
.empty())
1154 Constant
*ProfileNameConst
=
1155 ConstantDataArray::getString(M
.getContext(), InstrProfileOutput
, true);
1156 GlobalVariable
*ProfileNameVar
= new GlobalVariable(
1157 M
, ProfileNameConst
->getType(), true, GlobalValue::WeakAnyLinkage
,
1158 ProfileNameConst
, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR
));
1159 Triple
TT(M
.getTargetTriple());
1160 if (TT
.supportsCOMDAT()) {
1161 ProfileNameVar
->setLinkage(GlobalValue::ExternalLinkage
);
1162 ProfileNameVar
->setComdat(M
.getOrInsertComdat(
1163 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR
))));
1167 Error
OverlapStats::accumulateCounts(const std::string
&BaseFilename
,
1168 const std::string
&TestFilename
,
1170 auto getProfileSum
= [IsCS
](const std::string
&Filename
,
1171 CountSumOrPercent
&Sum
) -> Error
{
1172 auto ReaderOrErr
= InstrProfReader::create(Filename
);
1173 if (Error E
= ReaderOrErr
.takeError()) {
1176 auto Reader
= std::move(ReaderOrErr
.get());
1177 Reader
->accumulateCounts(Sum
, IsCS
);
1178 return Error::success();
1180 auto Ret
= getProfileSum(BaseFilename
, Base
);
1183 Ret
= getProfileSum(TestFilename
, Test
);
1186 this->BaseFilename
= &BaseFilename
;
1187 this->TestFilename
= &TestFilename
;
1189 return Error::success();
1192 void OverlapStats::addOneMismatch(const CountSumOrPercent
&MismatchFunc
) {
1193 Mismatch
.NumEntries
+= 1;
1194 Mismatch
.CountSum
+= MismatchFunc
.CountSum
/ Test
.CountSum
;
1195 for (unsigned I
= 0; I
< IPVK_Last
- IPVK_First
+ 1; I
++) {
1196 if (Test
.ValueCounts
[I
] >= 1.0f
)
1197 Mismatch
.ValueCounts
[I
] +=
1198 MismatchFunc
.ValueCounts
[I
] / Test
.ValueCounts
[I
];
1202 void OverlapStats::addOneUnique(const CountSumOrPercent
&UniqueFunc
) {
1203 Unique
.NumEntries
+= 1;
1204 Unique
.CountSum
+= UniqueFunc
.CountSum
/ Test
.CountSum
;
1205 for (unsigned I
= 0; I
< IPVK_Last
- IPVK_First
+ 1; I
++) {
1206 if (Test
.ValueCounts
[I
] >= 1.0f
)
1207 Unique
.ValueCounts
[I
] += UniqueFunc
.ValueCounts
[I
] / Test
.ValueCounts
[I
];
1211 void OverlapStats::dump(raw_fd_ostream
&OS
) const {
1215 const char *EntryName
=
1216 (Level
== ProgramLevel
? "functions" : "edge counters");
1217 if (Level
== ProgramLevel
) {
1218 OS
<< "Profile overlap infomation for base_profile: " << *BaseFilename
1219 << " and test_profile: " << *TestFilename
<< "\nProgram level:\n";
1221 OS
<< "Function level:\n"
1222 << " Function: " << FuncName
<< " (Hash=" << FuncHash
<< ")\n";
1225 OS
<< " # of " << EntryName
<< " overlap: " << Overlap
.NumEntries
<< "\n";
1226 if (Mismatch
.NumEntries
)
1227 OS
<< " # of " << EntryName
<< " mismatch: " << Mismatch
.NumEntries
1229 if (Unique
.NumEntries
)
1230 OS
<< " # of " << EntryName
1231 << " only in test_profile: " << Unique
.NumEntries
<< "\n";
1233 OS
<< " Edge profile overlap: " << format("%.3f%%", Overlap
.CountSum
* 100)
1235 if (Mismatch
.NumEntries
)
1236 OS
<< " Mismatched count percentage (Edge): "
1237 << format("%.3f%%", Mismatch
.CountSum
* 100) << "\n";
1238 if (Unique
.NumEntries
)
1239 OS
<< " Percentage of Edge profile only in test_profile: "
1240 << format("%.3f%%", Unique
.CountSum
* 100) << "\n";
1241 OS
<< " Edge profile base count sum: " << format("%.0f", Base
.CountSum
)
1243 << " Edge profile test count sum: " << format("%.0f", Test
.CountSum
)
1246 for (unsigned I
= 0; I
< IPVK_Last
- IPVK_First
+ 1; I
++) {
1247 if (Base
.ValueCounts
[I
] < 1.0f
&& Test
.ValueCounts
[I
] < 1.0f
)
1249 char ProfileKindName
[20];
1251 case IPVK_IndirectCallTarget
:
1252 strncpy(ProfileKindName
, "IndirectCall", 19);
1254 case IPVK_MemOPSize
:
1255 strncpy(ProfileKindName
, "MemOP", 19);
1258 snprintf(ProfileKindName
, 19, "VP[%d]", I
);
1261 OS
<< " " << ProfileKindName
1262 << " profile overlap: " << format("%.3f%%", Overlap
.ValueCounts
[I
] * 100)
1264 if (Mismatch
.NumEntries
)
1265 OS
<< " Mismatched count percentage (" << ProfileKindName
1266 << "): " << format("%.3f%%", Mismatch
.ValueCounts
[I
] * 100) << "\n";
1267 if (Unique
.NumEntries
)
1268 OS
<< " Percentage of " << ProfileKindName
1269 << " profile only in test_profile: "
1270 << format("%.3f%%", Unique
.ValueCounts
[I
] * 100) << "\n";
1271 OS
<< " " << ProfileKindName
1272 << " profile base count sum: " << format("%.0f", Base
.ValueCounts
[I
])
1274 << " " << ProfileKindName
1275 << " profile test count sum: " << format("%.0f", Test
.ValueCounts
[I
])
1280 } // end namespace llvm