1 //=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for clang's instrumentation based PGO and
11 // coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ProfileData/InstrProf.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/MDBuilder.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/Compression.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/Path.h"
28 
29 using namespace llvm;
30 
31 static cl::opt<bool> StaticFuncFullModulePrefix(
32     "static-func-full-module-prefix", cl::init(true),
33     cl::desc("Use full module build paths in the profile counter names for "
34              "static functions."));
35 
36 // This option is tailored to users that have different top-level directory in
37 // profile-gen and profile-use compilation. Users need to specific the number
38 // of levels to strip. A value larger than the number of directories in the
39 // source file will strip all the directory names and only leave the basename.
40 //
41 // Note current ThinLTO module importing for the indirect-calls assumes
42 // the source directory name not being stripped. A non-zero option value here
43 // can potentially prevent some inter-module indirect-call-promotions.
44 static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
45     "static-func-strip-dirname-prefix", cl::init(0),
46     cl::desc("Strip specified level of directory name from source path in "
47              "the profile counter name for static functions."));
48 
49 namespace {
50 std::string getInstrProfErrString(instrprof_error Err) {
51   switch (Err) {
52   case instrprof_error::success:
53     return "Success";
54   case instrprof_error::eof:
55     return "End of File";
56   case instrprof_error::unrecognized_format:
57     return "Unrecognized instrumentation profile encoding format";
58   case instrprof_error::bad_magic:
59     return "Invalid instrumentation profile data (bad magic)";
60   case instrprof_error::bad_header:
61     return "Invalid instrumentation profile data (file header is corrupt)";
62   case instrprof_error::unsupported_version:
63     return "Unsupported instrumentation profile format version";
64   case instrprof_error::unsupported_hash_type:
65     return "Unsupported instrumentation profile hash type";
66   case instrprof_error::too_large:
67     return "Too much profile data";
68   case instrprof_error::truncated:
69     return "Truncated profile data";
70   case instrprof_error::malformed:
71     return "Malformed instrumentation profile data";
72   case instrprof_error::unknown_function:
73     return "No profile data available for function";
74   case instrprof_error::hash_mismatch:
75     return "Function control flow change detected (hash mismatch)";
76   case instrprof_error::count_mismatch:
77     return "Function basic block count change detected (counter mismatch)";
78   case instrprof_error::counter_overflow:
79     return "Counter overflow";
80   case instrprof_error::value_site_count_mismatch:
81     return "Function value site count change detected (counter mismatch)";
82   case instrprof_error::compress_failed:
83     return "Failed to compress data (zlib)";
84   case instrprof_error::uncompress_failed:
85     return "Failed to uncompress data (zlib)";
86   case instrprof_error::empty_raw_profile:
87     return "Empty raw profile file";
88   }
89   llvm_unreachable("A value of instrprof_error has no message.");
90 }
91 
92 // FIXME: This class is only here to support the transition to llvm::Error. It
93 // will be removed once this transition is complete. Clients should prefer to
94 // deal with the Error value directly, rather than converting to error_code.
95 class InstrProfErrorCategoryType : public std::error_category {
96   const char *name() const noexcept override { return "llvm.instrprof"; }
97   std::string message(int IE) const override {
98     return getInstrProfErrString(static_cast<instrprof_error>(IE));
99   }
100 };
101 } // end anonymous namespace
102 
103 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
104 
105 const std::error_category &llvm::instrprof_category() {
106   return *ErrorCategory;
107 }
108 
109 namespace llvm {
110 
111 void SoftInstrProfErrors::addError(instrprof_error IE) {
112   if (IE == instrprof_error::success)
113     return;
114 
115   if (FirstError == instrprof_error::success)
116     FirstError = IE;
117 
118   switch (IE) {
119   case instrprof_error::hash_mismatch:
120     ++NumHashMismatches;
121     break;
122   case instrprof_error::count_mismatch:
123     ++NumCountMismatches;
124     break;
125   case instrprof_error::counter_overflow:
126     ++NumCounterOverflows;
127     break;
128   case instrprof_error::value_site_count_mismatch:
129     ++NumValueSiteCountMismatches;
130     break;
131   default:
132     llvm_unreachable("Not a soft error");
133   }
134 }
135 
136 std::string InstrProfError::message() const {
137   return getInstrProfErrString(Err);
138 }
139 
140 char InstrProfError::ID = 0;
141 
142 std::string getPGOFuncName(StringRef RawFuncName,
143                            GlobalValue::LinkageTypes Linkage,
144                            StringRef FileName,
145                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
146   return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
147 }
148 
149 // Strip NumPrefix level of directory name from PathNameStr. If the number of
150 // directory separators is less than NumPrefix, strip all the directories and
151 // leave base file name only.
152 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
153   uint32_t Count = NumPrefix;
154   uint32_t Pos = 0, LastPos = 0;
155   for (auto & CI : PathNameStr) {
156     ++Pos;
157     if (llvm::sys::path::is_separator(CI)) {
158       LastPos = Pos;
159       --Count;
160     }
161     if (Count == 0)
162       break;
163   }
164   return PathNameStr.substr(LastPos);
165 }
166 
167 // Return the PGOFuncName. This function has some special handling when called
168 // in LTO optimization. The following only applies when calling in LTO passes
169 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
170 // symbols. This happens after value profile annotation, but those internal
171 // linkage functions should not have a source prefix.
172 // Additionally, for ThinLTO mode, exported internal functions are promoted
173 // and renamed. We need to ensure that the original internal PGO name is
174 // used when computing the GUID that is compared against the profiled GUIDs.
175 // To differentiate compiler generated internal symbols from original ones,
176 // PGOFuncName meta data are created and attached to the original internal
177 // symbols in the value profile annotation step
178 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
179 // data, its original linkage must be non-internal.
180 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
181   if (!InLTO) {
182     StringRef FileName = (StaticFuncFullModulePrefix
183                               ? F.getParent()->getName()
184                               : sys::path::filename(F.getParent()->getName()));
185     if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
186       FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
187     return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
188   }
189 
190   // In LTO mode (when InLTO is true), first check if there is a meta data.
191   if (MDNode *MD = getPGOFuncNameMetadata(F)) {
192     StringRef S = cast<MDString>(MD->getOperand(0))->getString();
193     return S.str();
194   }
195 
196   // If there is no meta data, the function must be a global before the value
197   // profile annotation pass. Its current linkage may be internal if it is
198   // internalized in LTO mode.
199   return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
200 }
201 
202 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
203   if (FileName.empty())
204     return PGOFuncName;
205   // Drop the file name including ':'. See also getPGOFuncName.
206   if (PGOFuncName.startswith(FileName))
207     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
208   return PGOFuncName;
209 }
210 
211 // \p FuncName is the string used as profile lookup key for the function. A
212 // symbol is created to hold the name. Return the legalized symbol name.
213 std::string getPGOFuncNameVarName(StringRef FuncName,
214                                   GlobalValue::LinkageTypes Linkage) {
215   std::string VarName = getInstrProfNameVarPrefix();
216   VarName += FuncName;
217 
218   if (!GlobalValue::isLocalLinkage(Linkage))
219     return VarName;
220 
221   // Now fix up illegal chars in local VarName that may upset the assembler.
222   const char *InvalidChars = "-:<>/\"'";
223   size_t found = VarName.find_first_of(InvalidChars);
224   while (found != std::string::npos) {
225     VarName[found] = '_';
226     found = VarName.find_first_of(InvalidChars, found + 1);
227   }
228   return VarName;
229 }
230 
231 GlobalVariable *createPGOFuncNameVar(Module &M,
232                                      GlobalValue::LinkageTypes Linkage,
233                                      StringRef PGOFuncName) {
234 
235   // We generally want to match the function's linkage, but available_externally
236   // and extern_weak both have the wrong semantics, and anything that doesn't
237   // need to link across compilation units doesn't need to be visible at all.
238   if (Linkage == GlobalValue::ExternalWeakLinkage)
239     Linkage = GlobalValue::LinkOnceAnyLinkage;
240   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
241     Linkage = GlobalValue::LinkOnceODRLinkage;
242   else if (Linkage == GlobalValue::InternalLinkage ||
243            Linkage == GlobalValue::ExternalLinkage)
244     Linkage = GlobalValue::PrivateLinkage;
245 
246   auto *Value =
247       ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
248   auto FuncNameVar =
249       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
250                          getPGOFuncNameVarName(PGOFuncName, Linkage));
251 
252   // Hide the symbol so that we correctly get a copy for each executable.
253   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
254     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
255 
256   return FuncNameVar;
257 }
258 
259 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
260   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
261 }
262 
263 void InstrProfSymtab::create(Module &M, bool InLTO) {
264   for (Function &F : M) {
265     // Function may not have a name: like using asm("") to overwrite the name.
266     // Ignore in this case.
267     if (!F.hasName())
268       continue;
269     const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
270     addFuncName(PGOFuncName);
271     MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
272   }
273 
274   finalizeSymtab();
275 }
276 
277 Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
278                                 bool doCompression, std::string &Result) {
279   assert(NameStrs.size() && "No name data to emit");
280 
281   uint8_t Header[16], *P = Header;
282   std::string UncompressedNameStrings =
283       join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
284 
285   assert(StringRef(UncompressedNameStrings)
286                  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
287          "PGO name is invalid (contains separator token)");
288 
289   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
290   P += EncLen;
291 
292   auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
293     EncLen = encodeULEB128(CompressedLen, P);
294     P += EncLen;
295     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
296     unsigned HeaderLen = P - &Header[0];
297     Result.append(HeaderStr, HeaderLen);
298     Result += InputStr;
299     return Error::success();
300   };
301 
302   if (!doCompression) {
303     return WriteStringToResult(0, UncompressedNameStrings);
304   }
305 
306   SmallString<128> CompressedNameStrings;
307   Error E = zlib::compress(StringRef(UncompressedNameStrings),
308                            CompressedNameStrings, zlib::BestSizeCompression);
309   if (E) {
310     consumeError(std::move(E));
311     return make_error<InstrProfError>(instrprof_error::compress_failed);
312   }
313 
314   return WriteStringToResult(CompressedNameStrings.size(),
315                              CompressedNameStrings);
316 }
317 
318 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
319   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
320   StringRef NameStr =
321       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
322   return NameStr;
323 }
324 
325 Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
326                                 std::string &Result, bool doCompression) {
327   std::vector<std::string> NameStrs;
328   for (auto *NameVar : NameVars) {
329     NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
330   }
331   return collectPGOFuncNameStrings(
332       NameStrs, zlib::isAvailable() && doCompression, Result);
333 }
334 
335 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
336   const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
337   const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
338                                                           NameStrings.size());
339   while (P < EndP) {
340     uint32_t N;
341     uint64_t UncompressedSize = decodeULEB128(P, &N);
342     P += N;
343     uint64_t CompressedSize = decodeULEB128(P, &N);
344     P += N;
345     bool isCompressed = (CompressedSize != 0);
346     SmallString<128> UncompressedNameStrings;
347     StringRef NameStrings;
348     if (isCompressed) {
349       StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
350                                       CompressedSize);
351       if (Error E =
352               zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
353                                UncompressedSize)) {
354         consumeError(std::move(E));
355         return make_error<InstrProfError>(instrprof_error::uncompress_failed);
356       }
357       P += CompressedSize;
358       NameStrings = StringRef(UncompressedNameStrings.data(),
359                               UncompressedNameStrings.size());
360     } else {
361       NameStrings =
362           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
363       P += UncompressedSize;
364     }
365     // Now parse the name strings.
366     SmallVector<StringRef, 0> Names;
367     NameStrings.split(Names, getInstrProfNameSeparator());
368     for (StringRef &Name : Names)
369       Symtab.addFuncName(Name);
370 
371     while (P < EndP && *P == 0)
372       P++;
373   }
374   Symtab.finalizeSymtab();
375   return Error::success();
376 }
377 
378 void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
379                                      InstrProfValueSiteRecord &Input,
380                                      uint64_t Weight) {
381   this->sortByTargetValues();
382   Input.sortByTargetValues();
383   auto I = ValueData.begin();
384   auto IE = ValueData.end();
385   for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
386        ++J) {
387     while (I != IE && I->Value < J->Value)
388       ++I;
389     if (I != IE && I->Value == J->Value) {
390       bool Overflowed;
391       I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
392       if (Overflowed)
393         SIPE.addError(instrprof_error::counter_overflow);
394       ++I;
395       continue;
396     }
397     ValueData.insert(I, *J);
398   }
399 }
400 
401 void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
402                                      uint64_t Weight) {
403   for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
404     bool Overflowed;
405     I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
406     if (Overflowed)
407       SIPE.addError(instrprof_error::counter_overflow);
408   }
409 }
410 
411 // Merge Value Profile data from Src record to this record for ValueKind.
412 // Scale merged value counts by \p Weight.
413 void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
414                                          InstrProfRecord &Src,
415                                          uint64_t Weight) {
416   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
417   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
418   if (ThisNumValueSites != OtherNumValueSites) {
419     SIPE.addError(instrprof_error::value_site_count_mismatch);
420     return;
421   }
422   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
423       getValueSitesForKind(ValueKind);
424   std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
425       Src.getValueSitesForKind(ValueKind);
426   for (uint32_t I = 0; I < ThisNumValueSites; I++)
427     ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
428 }
429 
430 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
431   // If the number of counters doesn't match we either have bad data
432   // or a hash collision.
433   if (Counts.size() != Other.Counts.size()) {
434     SIPE.addError(instrprof_error::count_mismatch);
435     return;
436   }
437 
438   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
439     bool Overflowed;
440     Counts[I] =
441         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
442     if (Overflowed)
443       SIPE.addError(instrprof_error::counter_overflow);
444   }
445 
446   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
447     mergeValueProfData(Kind, Other, Weight);
448 }
449 
450 void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
451   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
452   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
453       getValueSitesForKind(ValueKind);
454   for (uint32_t I = 0; I < ThisNumValueSites; I++)
455     ThisSiteRecords[I].scale(SIPE, Weight);
456 }
457 
458 void InstrProfRecord::scale(uint64_t Weight) {
459   for (auto &Count : this->Counts) {
460     bool Overflowed;
461     Count = SaturatingMultiply(Count, Weight, &Overflowed);
462     if (Overflowed)
463       SIPE.addError(instrprof_error::counter_overflow);
464   }
465   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
466     scaleValueProfData(Kind, Weight);
467 }
468 
469 // Map indirect call target name hash to name string.
470 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
471                                      ValueMapType *ValueMap) {
472   if (!ValueMap)
473     return Value;
474   switch (ValueKind) {
475   case IPVK_IndirectCallTarget: {
476     auto Result =
477         std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
478                          [](const std::pair<uint64_t, uint64_t> &LHS,
479                             uint64_t RHS) { return LHS.first < RHS; });
480    // Raw function pointer collected by value profiler may be from
481    // external functions that are not instrumented. They won't have
482    // mapping data to be used by the deserializer. Force the value to
483    // be 0 in this case.
484     if (Result != ValueMap->end() && Result->first == Value)
485       Value = (uint64_t)Result->second;
486     else
487       Value = 0;
488     break;
489   }
490   }
491   return Value;
492 }
493 
494 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
495                                    InstrProfValueData *VData, uint32_t N,
496                                    ValueMapType *ValueMap) {
497   for (uint32_t I = 0; I < N; I++) {
498     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
499   }
500   std::vector<InstrProfValueSiteRecord> &ValueSites =
501       getValueSitesForKind(ValueKind);
502   if (N == 0)
503     ValueSites.emplace_back();
504   else
505     ValueSites.emplace_back(VData, VData + N);
506 }
507 
508 #define INSTR_PROF_COMMON_API_IMPL
509 #include "llvm/ProfileData/InstrProfData.inc"
510 
511 /*!
512  * \brief ValueProfRecordClosure Interface implementation for  InstrProfRecord
513  *  class. These C wrappers are used as adaptors so that C++ code can be
514  *  invoked as callbacks.
515  */
516 uint32_t getNumValueKindsInstrProf(const void *Record) {
517   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
518 }
519 
520 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
521   return reinterpret_cast<const InstrProfRecord *>(Record)
522       ->getNumValueSites(VKind);
523 }
524 
525 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
526   return reinterpret_cast<const InstrProfRecord *>(Record)
527       ->getNumValueData(VKind);
528 }
529 
530 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
531                                          uint32_t S) {
532   return reinterpret_cast<const InstrProfRecord *>(R)
533       ->getNumValueDataForSite(VK, S);
534 }
535 
536 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
537                               uint32_t K, uint32_t S) {
538   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
539 }
540 
541 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
542   ValueProfData *VD =
543       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
544   memset(VD, 0, TotalSizeInBytes);
545   return VD;
546 }
547 
548 static ValueProfRecordClosure InstrProfRecordClosure = {
549     nullptr,
550     getNumValueKindsInstrProf,
551     getNumValueSitesInstrProf,
552     getNumValueDataInstrProf,
553     getNumValueDataForSiteInstrProf,
554     nullptr,
555     getValueForSiteInstrProf,
556     allocValueProfDataInstrProf};
557 
558 // Wrapper implementation using the closure mechanism.
559 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
560   InstrProfRecordClosure.Record = &Record;
561   return getValueProfDataSize(&InstrProfRecordClosure);
562 }
563 
564 // Wrapper implementation using the closure mechanism.
565 std::unique_ptr<ValueProfData>
566 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
567   InstrProfRecordClosure.Record = &Record;
568 
569   std::unique_ptr<ValueProfData> VPD(
570       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
571   return VPD;
572 }
573 
574 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
575                                     InstrProfRecord::ValueMapType *VMap) {
576   Record.reserveSites(Kind, NumValueSites);
577 
578   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
579   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
580     uint8_t ValueDataCount = this->SiteCountArray[VSite];
581     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
582     ValueData += ValueDataCount;
583   }
584 }
585 
586 // For writing/serializing,  Old is the host endianness, and  New is
587 // byte order intended on disk. For Reading/deserialization, Old
588 // is the on-disk source endianness, and New is the host endianness.
589 void ValueProfRecord::swapBytes(support::endianness Old,
590                                 support::endianness New) {
591   using namespace support;
592   if (Old == New)
593     return;
594 
595   if (getHostEndianness() != Old) {
596     sys::swapByteOrder<uint32_t>(NumValueSites);
597     sys::swapByteOrder<uint32_t>(Kind);
598   }
599   uint32_t ND = getValueProfRecordNumValueData(this);
600   InstrProfValueData *VD = getValueProfRecordValueData(this);
601 
602   // No need to swap byte array: SiteCountArrray.
603   for (uint32_t I = 0; I < ND; I++) {
604     sys::swapByteOrder<uint64_t>(VD[I].Value);
605     sys::swapByteOrder<uint64_t>(VD[I].Count);
606   }
607   if (getHostEndianness() == Old) {
608     sys::swapByteOrder<uint32_t>(NumValueSites);
609     sys::swapByteOrder<uint32_t>(Kind);
610   }
611 }
612 
613 void ValueProfData::deserializeTo(InstrProfRecord &Record,
614                                   InstrProfRecord::ValueMapType *VMap) {
615   if (NumValueKinds == 0)
616     return;
617 
618   ValueProfRecord *VR = getFirstValueProfRecord(this);
619   for (uint32_t K = 0; K < NumValueKinds; K++) {
620     VR->deserializeTo(Record, VMap);
621     VR = getValueProfRecordNext(VR);
622   }
623 }
624 
625 template <class T>
626 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
627   using namespace support;
628   if (Orig == little)
629     return endian::readNext<T, little, unaligned>(D);
630   else
631     return endian::readNext<T, big, unaligned>(D);
632 }
633 
634 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
635   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
636                                             ValueProfData());
637 }
638 
639 Error ValueProfData::checkIntegrity() {
640   if (NumValueKinds > IPVK_Last + 1)
641     return make_error<InstrProfError>(instrprof_error::malformed);
642   // Total size needs to be mulltiple of quadword size.
643   if (TotalSize % sizeof(uint64_t))
644     return make_error<InstrProfError>(instrprof_error::malformed);
645 
646   ValueProfRecord *VR = getFirstValueProfRecord(this);
647   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
648     if (VR->Kind > IPVK_Last)
649       return make_error<InstrProfError>(instrprof_error::malformed);
650     VR = getValueProfRecordNext(VR);
651     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
652       return make_error<InstrProfError>(instrprof_error::malformed);
653   }
654   return Error::success();
655 }
656 
657 Expected<std::unique_ptr<ValueProfData>>
658 ValueProfData::getValueProfData(const unsigned char *D,
659                                 const unsigned char *const BufferEnd,
660                                 support::endianness Endianness) {
661   using namespace support;
662   if (D + sizeof(ValueProfData) > BufferEnd)
663     return make_error<InstrProfError>(instrprof_error::truncated);
664 
665   const unsigned char *Header = D;
666   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
667   if (D + TotalSize > BufferEnd)
668     return make_error<InstrProfError>(instrprof_error::too_large);
669 
670   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
671   memcpy(VPD.get(), D, TotalSize);
672   // Byte swap.
673   VPD->swapBytesToHost(Endianness);
674 
675   Error E = VPD->checkIntegrity();
676   if (E)
677     return std::move(E);
678 
679   return std::move(VPD);
680 }
681 
682 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
683   using namespace support;
684   if (Endianness == getHostEndianness())
685     return;
686 
687   sys::swapByteOrder<uint32_t>(TotalSize);
688   sys::swapByteOrder<uint32_t>(NumValueKinds);
689 
690   ValueProfRecord *VR = getFirstValueProfRecord(this);
691   for (uint32_t K = 0; K < NumValueKinds; K++) {
692     VR->swapBytes(Endianness, getHostEndianness());
693     VR = getValueProfRecordNext(VR);
694   }
695 }
696 
697 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
698   using namespace support;
699   if (Endianness == getHostEndianness())
700     return;
701 
702   ValueProfRecord *VR = getFirstValueProfRecord(this);
703   for (uint32_t K = 0; K < NumValueKinds; K++) {
704     ValueProfRecord *NVR = getValueProfRecordNext(VR);
705     VR->swapBytes(getHostEndianness(), Endianness);
706     VR = NVR;
707   }
708   sys::swapByteOrder<uint32_t>(TotalSize);
709   sys::swapByteOrder<uint32_t>(NumValueKinds);
710 }
711 
712 void annotateValueSite(Module &M, Instruction &Inst,
713                        const InstrProfRecord &InstrProfR,
714                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
715                        uint32_t MaxMDCount) {
716   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
717   if (!NV)
718     return;
719 
720   uint64_t Sum = 0;
721   std::unique_ptr<InstrProfValueData[]> VD =
722       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
723 
724   ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
725   annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
726 }
727 
728 void annotateValueSite(Module &M, Instruction &Inst,
729                        ArrayRef<InstrProfValueData> VDs,
730                        uint64_t Sum, InstrProfValueKind ValueKind,
731                        uint32_t MaxMDCount) {
732   LLVMContext &Ctx = M.getContext();
733   MDBuilder MDHelper(Ctx);
734   SmallVector<Metadata *, 3> Vals;
735   // Tag
736   Vals.push_back(MDHelper.createString("VP"));
737   // Value Kind
738   Vals.push_back(MDHelper.createConstant(
739       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
740   // Total Count
741   Vals.push_back(
742       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
743 
744   // Value Profile Data
745   uint32_t MDCount = MaxMDCount;
746   for (auto &VD : VDs) {
747     Vals.push_back(MDHelper.createConstant(
748         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
749     Vals.push_back(MDHelper.createConstant(
750         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
751     if (--MDCount == 0)
752       break;
753   }
754   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
755 }
756 
757 bool getValueProfDataFromInst(const Instruction &Inst,
758                               InstrProfValueKind ValueKind,
759                               uint32_t MaxNumValueData,
760                               InstrProfValueData ValueData[],
761                               uint32_t &ActualNumValueData, uint64_t &TotalC) {
762   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
763   if (!MD)
764     return false;
765 
766   unsigned NOps = MD->getNumOperands();
767 
768   if (NOps < 5)
769     return false;
770 
771   // Operand 0 is a string tag "VP":
772   MDString *Tag = cast<MDString>(MD->getOperand(0));
773   if (!Tag)
774     return false;
775 
776   if (!Tag->getString().equals("VP"))
777     return false;
778 
779   // Now check kind:
780   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
781   if (!KindInt)
782     return false;
783   if (KindInt->getZExtValue() != ValueKind)
784     return false;
785 
786   // Get total count
787   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
788   if (!TotalCInt)
789     return false;
790   TotalC = TotalCInt->getZExtValue();
791 
792   ActualNumValueData = 0;
793 
794   for (unsigned I = 3; I < NOps; I += 2) {
795     if (ActualNumValueData >= MaxNumValueData)
796       break;
797     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
798     ConstantInt *Count =
799         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
800     if (!Value || !Count)
801       return false;
802     ValueData[ActualNumValueData].Value = Value->getZExtValue();
803     ValueData[ActualNumValueData].Count = Count->getZExtValue();
804     ActualNumValueData++;
805   }
806   return true;
807 }
808 
809 MDNode *getPGOFuncNameMetadata(const Function &F) {
810   return F.getMetadata(getPGOFuncNameMetadataName());
811 }
812 
813 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
814   // Only for internal linkage functions.
815   if (PGOFuncName == F.getName())
816       return;
817   // Don't create duplicated meta-data.
818   if (getPGOFuncNameMetadata(F))
819     return;
820   LLVMContext &C = F.getContext();
821   MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
822   F.setMetadata(getPGOFuncNameMetadataName(), N);
823 }
824 
825 bool needsComdatForCounter(const Function &F, const Module &M) {
826   if (F.hasComdat())
827     return true;
828 
829   Triple TT(M.getTargetTriple());
830   if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
831     return false;
832 
833   // See createPGOFuncNameVar for more details. To avoid link errors, profile
834   // counters for function with available_externally linkage needs to be changed
835   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
836   // created. Without using comdat, duplicate entries won't be removed by the
837   // linker leading to increased data segement size and raw profile size. Even
838   // worse, since the referenced counter from profile per-function data object
839   // will be resolved to the common strong definition, the profile counts for
840   // available_externally functions will end up being duplicated in raw profile
841   // data. This can result in distorted profile as the counts of those dups
842   // will be accumulated by the profile merger.
843   GlobalValue::LinkageTypes Linkage = F.getLinkage();
844   if (Linkage != GlobalValue::ExternalWeakLinkage &&
845       Linkage != GlobalValue::AvailableExternallyLinkage)
846     return false;
847 
848   return true;
849 }
850 
851 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
852 bool isIRPGOFlagSet(const Module *M) {
853   auto IRInstrVar =
854       M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
855   if (!IRInstrVar || IRInstrVar->isDeclaration() ||
856       IRInstrVar->hasLocalLinkage())
857     return false;
858 
859   // Check if the flag is set.
860   if (!IRInstrVar->hasInitializer())
861     return false;
862 
863   const Constant *InitVal = IRInstrVar->getInitializer();
864   if (!InitVal)
865     return false;
866 
867   return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
868           VARIANT_MASK_IR_PROF) != 0;
869 }
870 
871 // Check if we can safely rename this Comdat function.
872 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
873   if (F.getName().empty())
874     return false;
875   if (!needsComdatForCounter(F, *(F.getParent())))
876     return false;
877   // Unsafe to rename the address-taken function (which can be used in
878   // function comparison).
879   if (CheckAddressTaken && F.hasAddressTaken())
880     return false;
881   // Only safe to do if this function may be discarded if it is not used
882   // in the compilation unit.
883   if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
884     return false;
885 
886   // For AvailableExternallyLinkage functions.
887   if (!F.hasComdat()) {
888     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
889     return true;
890   }
891   return true;
892 }
893 } // end namespace llvm
894