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/ArrayRef.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.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 = (StaticFuncFullModulePrefix
256                               ? F.getParent()->getName()
257                               : sys::path::filename(F.getParent()->getName()));
258     if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
259       FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
260     return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
261   }
262 
263   // In LTO mode (when InLTO is true), first check if there is a meta data.
264   if (MDNode *MD = getPGOFuncNameMetadata(F)) {
265     StringRef S = cast<MDString>(MD->getOperand(0))->getString();
266     return S.str();
267   }
268 
269   // If there is no meta data, the function must be a global before the value
270   // profile annotation pass. Its current linkage may be internal if it is
271   // internalized in LTO mode.
272   return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
273 }
274 
275 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
276   if (FileName.empty())
277     return PGOFuncName;
278   // Drop the file name including ':'. See also getPGOFuncName.
279   if (PGOFuncName.startswith(FileName))
280     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
281   return PGOFuncName;
282 }
283 
284 // \p FuncName is the string used as profile lookup key for the function. A
285 // symbol is created to hold the name. Return the legalized symbol name.
286 std::string getPGOFuncNameVarName(StringRef FuncName,
287                                   GlobalValue::LinkageTypes Linkage) {
288   std::string VarName = getInstrProfNameVarPrefix();
289   VarName += FuncName;
290 
291   if (!GlobalValue::isLocalLinkage(Linkage))
292     return VarName;
293 
294   // Now fix up illegal chars in local VarName that may upset the assembler.
295   const char *InvalidChars = "-:<>/\"'";
296   size_t found = VarName.find_first_of(InvalidChars);
297   while (found != std::string::npos) {
298     VarName[found] = '_';
299     found = VarName.find_first_of(InvalidChars, found + 1);
300   }
301   return VarName;
302 }
303 
304 GlobalVariable *createPGOFuncNameVar(Module &M,
305                                      GlobalValue::LinkageTypes Linkage,
306                                      StringRef PGOFuncName) {
307   // We generally want to match the function's linkage, but available_externally
308   // and extern_weak both have the wrong semantics, and anything that doesn't
309   // need to link across compilation units doesn't need to be visible at all.
310   if (Linkage == GlobalValue::ExternalWeakLinkage)
311     Linkage = GlobalValue::LinkOnceAnyLinkage;
312   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
313     Linkage = GlobalValue::LinkOnceODRLinkage;
314   else if (Linkage == GlobalValue::InternalLinkage ||
315            Linkage == GlobalValue::ExternalLinkage)
316     Linkage = GlobalValue::PrivateLinkage;
317 
318   auto *Value =
319       ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
320   auto FuncNameVar =
321       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
322                          getPGOFuncNameVarName(PGOFuncName, Linkage));
323 
324   // Hide the symbol so that we correctly get a copy for each executable.
325   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
326     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
327 
328   return FuncNameVar;
329 }
330 
331 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
332   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
333 }
334 
335 Error InstrProfSymtab::create(Module &M, bool InLTO) {
336   for (Function &F : M) {
337     // Function may not have a name: like using asm("") to overwrite the name.
338     // Ignore in this case.
339     if (!F.hasName())
340       continue;
341     const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
342     if (Error E = addFuncName(PGOFuncName))
343       return E;
344     MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
345     // In ThinLTO, local function may have been promoted to global and have
346     // suffix added to the function name. We need to add the stripped function
347     // name to the symbol table so that we can find a match from profile.
348     if (InLTO) {
349       auto pos = PGOFuncName.find('.');
350       if (pos != std::string::npos) {
351         const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
352         if (Error E = addFuncName(OtherFuncName))
353           return E;
354         MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
355       }
356     }
357   }
358   Sorted = false;
359   finalizeSymtab();
360   return Error::success();
361 }
362 
363 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
364                                 bool doCompression, std::string &Result) {
365   assert(!NameStrs.empty() && "No name data to emit");
366 
367   uint8_t Header[16], *P = Header;
368   std::string UncompressedNameStrings =
369       join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
370 
371   assert(StringRef(UncompressedNameStrings)
372                  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
373          "PGO name is invalid (contains separator token)");
374 
375   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
376   P += EncLen;
377 
378   auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
379     EncLen = encodeULEB128(CompressedLen, P);
380     P += EncLen;
381     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
382     unsigned HeaderLen = P - &Header[0];
383     Result.append(HeaderStr, HeaderLen);
384     Result += InputStr;
385     return Error::success();
386   };
387 
388   if (!doCompression) {
389     return WriteStringToResult(0, UncompressedNameStrings);
390   }
391 
392   SmallString<128> CompressedNameStrings;
393   Error E = zlib::compress(StringRef(UncompressedNameStrings),
394                            CompressedNameStrings, zlib::BestSizeCompression);
395   if (E) {
396     consumeError(std::move(E));
397     return make_error<InstrProfError>(instrprof_error::compress_failed);
398   }
399 
400   return WriteStringToResult(CompressedNameStrings.size(),
401                              CompressedNameStrings);
402 }
403 
404 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
405   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
406   StringRef NameStr =
407       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
408   return NameStr;
409 }
410 
411 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
412                                 std::string &Result, bool doCompression) {
413   std::vector<std::string> NameStrs;
414   for (auto *NameVar : NameVars) {
415     NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
416   }
417   return collectPGOFuncNameStrings(
418       NameStrs, zlib::isAvailable() && doCompression, Result);
419 }
420 
421 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
422   const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
423   const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
424                                                           NameStrings.size());
425   while (P < EndP) {
426     uint32_t N;
427     uint64_t UncompressedSize = decodeULEB128(P, &N);
428     P += N;
429     uint64_t CompressedSize = decodeULEB128(P, &N);
430     P += N;
431     bool isCompressed = (CompressedSize != 0);
432     SmallString<128> UncompressedNameStrings;
433     StringRef NameStrings;
434     if (isCompressed) {
435       if (!llvm::zlib::isAvailable())
436         return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
437 
438       StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
439                                       CompressedSize);
440       if (Error E =
441               zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
442                                UncompressedSize)) {
443         consumeError(std::move(E));
444         return make_error<InstrProfError>(instrprof_error::uncompress_failed);
445       }
446       P += CompressedSize;
447       NameStrings = StringRef(UncompressedNameStrings.data(),
448                               UncompressedNameStrings.size());
449     } else {
450       NameStrings =
451           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
452       P += UncompressedSize;
453     }
454     // Now parse the name strings.
455     SmallVector<StringRef, 0> Names;
456     NameStrings.split(Names, getInstrProfNameSeparator());
457     for (StringRef &Name : Names)
458       if (Error E = Symtab.addFuncName(Name))
459         return E;
460 
461     while (P < EndP && *P == 0)
462       P++;
463   }
464   return Error::success();
465 }
466 
467 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
468                                      uint64_t Weight,
469                                      function_ref<void(instrprof_error)> Warn) {
470   this->sortByTargetValues();
471   Input.sortByTargetValues();
472   auto I = ValueData.begin();
473   auto IE = ValueData.end();
474   for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
475        ++J) {
476     while (I != IE && I->Value < J->Value)
477       ++I;
478     if (I != IE && I->Value == J->Value) {
479       bool Overflowed;
480       I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
481       if (Overflowed)
482         Warn(instrprof_error::counter_overflow);
483       ++I;
484       continue;
485     }
486     ValueData.insert(I, *J);
487   }
488 }
489 
490 void InstrProfValueSiteRecord::scale(uint64_t Weight,
491                                      function_ref<void(instrprof_error)> Warn) {
492   for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
493     bool Overflowed;
494     I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
495     if (Overflowed)
496       Warn(instrprof_error::counter_overflow);
497   }
498 }
499 
500 // Merge Value Profile data from Src record to this record for ValueKind.
501 // Scale merged value counts by \p Weight.
502 void InstrProfRecord::mergeValueProfData(
503     uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
504     function_ref<void(instrprof_error)> Warn) {
505   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
506   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
507   if (ThisNumValueSites != OtherNumValueSites) {
508     Warn(instrprof_error::value_site_count_mismatch);
509     return;
510   }
511   if (!ThisNumValueSites)
512     return;
513   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
514       getOrCreateValueSitesForKind(ValueKind);
515   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
516       Src.getValueSitesForKind(ValueKind);
517   for (uint32_t I = 0; I < ThisNumValueSites; I++)
518     ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
519 }
520 
521 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
522                             function_ref<void(instrprof_error)> Warn) {
523   // If the number of counters doesn't match we either have bad data
524   // or a hash collision.
525   if (Counts.size() != Other.Counts.size()) {
526     Warn(instrprof_error::count_mismatch);
527     return;
528   }
529 
530   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
531     bool Overflowed;
532     Counts[I] =
533         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
534     if (Overflowed)
535       Warn(instrprof_error::counter_overflow);
536   }
537 
538   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
539     mergeValueProfData(Kind, Other, Weight, Warn);
540 }
541 
542 void InstrProfRecord::scaleValueProfData(
543     uint32_t ValueKind, uint64_t Weight,
544     function_ref<void(instrprof_error)> Warn) {
545   for (auto &R : getValueSitesForKind(ValueKind))
546     R.scale(Weight, Warn);
547 }
548 
549 void InstrProfRecord::scale(uint64_t Weight,
550                             function_ref<void(instrprof_error)> Warn) {
551   for (auto &Count : this->Counts) {
552     bool Overflowed;
553     Count = SaturatingMultiply(Count, Weight, &Overflowed);
554     if (Overflowed)
555       Warn(instrprof_error::counter_overflow);
556   }
557   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
558     scaleValueProfData(Kind, Weight, Warn);
559 }
560 
561 // Map indirect call target name hash to name string.
562 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
563                                      ValueMapType *ValueMap) {
564   if (!ValueMap)
565     return Value;
566   switch (ValueKind) {
567   case IPVK_IndirectCallTarget: {
568     auto Result =
569         std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
570                          [](const std::pair<uint64_t, uint64_t> &LHS,
571                             uint64_t RHS) { return LHS.first < RHS; });
572    // Raw function pointer collected by value profiler may be from
573    // external functions that are not instrumented. They won't have
574    // mapping data to be used by the deserializer. Force the value to
575    // be 0 in this case.
576     if (Result != ValueMap->end() && Result->first == Value)
577       Value = (uint64_t)Result->second;
578     else
579       Value = 0;
580     break;
581   }
582   }
583   return Value;
584 }
585 
586 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
587                                    InstrProfValueData *VData, uint32_t N,
588                                    ValueMapType *ValueMap) {
589   for (uint32_t I = 0; I < N; I++) {
590     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
591   }
592   std::vector<InstrProfValueSiteRecord> &ValueSites =
593       getOrCreateValueSitesForKind(ValueKind);
594   if (N == 0)
595     ValueSites.emplace_back();
596   else
597     ValueSites.emplace_back(VData, VData + N);
598 }
599 
600 #define INSTR_PROF_COMMON_API_IMPL
601 #include "llvm/ProfileData/InstrProfData.inc"
602 
603 /*!
604  * \brief ValueProfRecordClosure Interface implementation for  InstrProfRecord
605  *  class. These C wrappers are used as adaptors so that C++ code can be
606  *  invoked as callbacks.
607  */
608 uint32_t getNumValueKindsInstrProf(const void *Record) {
609   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
610 }
611 
612 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
613   return reinterpret_cast<const InstrProfRecord *>(Record)
614       ->getNumValueSites(VKind);
615 }
616 
617 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
618   return reinterpret_cast<const InstrProfRecord *>(Record)
619       ->getNumValueData(VKind);
620 }
621 
622 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
623                                          uint32_t S) {
624   return reinterpret_cast<const InstrProfRecord *>(R)
625       ->getNumValueDataForSite(VK, S);
626 }
627 
628 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
629                               uint32_t K, uint32_t S) {
630   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
631 }
632 
633 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
634   ValueProfData *VD =
635       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
636   memset(VD, 0, TotalSizeInBytes);
637   return VD;
638 }
639 
640 static ValueProfRecordClosure InstrProfRecordClosure = {
641     nullptr,
642     getNumValueKindsInstrProf,
643     getNumValueSitesInstrProf,
644     getNumValueDataInstrProf,
645     getNumValueDataForSiteInstrProf,
646     nullptr,
647     getValueForSiteInstrProf,
648     allocValueProfDataInstrProf};
649 
650 // Wrapper implementation using the closure mechanism.
651 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
652   auto Closure = InstrProfRecordClosure;
653   Closure.Record = &Record;
654   return getValueProfDataSize(&Closure);
655 }
656 
657 // Wrapper implementation using the closure mechanism.
658 std::unique_ptr<ValueProfData>
659 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
660   InstrProfRecordClosure.Record = &Record;
661 
662   std::unique_ptr<ValueProfData> VPD(
663       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
664   return VPD;
665 }
666 
667 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
668                                     InstrProfRecord::ValueMapType *VMap) {
669   Record.reserveSites(Kind, NumValueSites);
670 
671   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
672   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
673     uint8_t ValueDataCount = this->SiteCountArray[VSite];
674     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
675     ValueData += ValueDataCount;
676   }
677 }
678 
679 // For writing/serializing,  Old is the host endianness, and  New is
680 // byte order intended on disk. For Reading/deserialization, Old
681 // is the on-disk source endianness, and New is the host endianness.
682 void ValueProfRecord::swapBytes(support::endianness Old,
683                                 support::endianness New) {
684   using namespace support;
685 
686   if (Old == New)
687     return;
688 
689   if (getHostEndianness() != Old) {
690     sys::swapByteOrder<uint32_t>(NumValueSites);
691     sys::swapByteOrder<uint32_t>(Kind);
692   }
693   uint32_t ND = getValueProfRecordNumValueData(this);
694   InstrProfValueData *VD = getValueProfRecordValueData(this);
695 
696   // No need to swap byte array: SiteCountArrray.
697   for (uint32_t I = 0; I < ND; I++) {
698     sys::swapByteOrder<uint64_t>(VD[I].Value);
699     sys::swapByteOrder<uint64_t>(VD[I].Count);
700   }
701   if (getHostEndianness() == Old) {
702     sys::swapByteOrder<uint32_t>(NumValueSites);
703     sys::swapByteOrder<uint32_t>(Kind);
704   }
705 }
706 
707 void ValueProfData::deserializeTo(InstrProfRecord &Record,
708                                   InstrProfRecord::ValueMapType *VMap) {
709   if (NumValueKinds == 0)
710     return;
711 
712   ValueProfRecord *VR = getFirstValueProfRecord(this);
713   for (uint32_t K = 0; K < NumValueKinds; K++) {
714     VR->deserializeTo(Record, VMap);
715     VR = getValueProfRecordNext(VR);
716   }
717 }
718 
719 template <class T>
720 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
721   using namespace support;
722 
723   if (Orig == little)
724     return endian::readNext<T, little, unaligned>(D);
725   else
726     return endian::readNext<T, big, unaligned>(D);
727 }
728 
729 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
730   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
731                                             ValueProfData());
732 }
733 
734 Error ValueProfData::checkIntegrity() {
735   if (NumValueKinds > IPVK_Last + 1)
736     return make_error<InstrProfError>(instrprof_error::malformed);
737   // Total size needs to be mulltiple of quadword size.
738   if (TotalSize % sizeof(uint64_t))
739     return make_error<InstrProfError>(instrprof_error::malformed);
740 
741   ValueProfRecord *VR = getFirstValueProfRecord(this);
742   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
743     if (VR->Kind > IPVK_Last)
744       return make_error<InstrProfError>(instrprof_error::malformed);
745     VR = getValueProfRecordNext(VR);
746     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
747       return make_error<InstrProfError>(instrprof_error::malformed);
748   }
749   return Error::success();
750 }
751 
752 Expected<std::unique_ptr<ValueProfData>>
753 ValueProfData::getValueProfData(const unsigned char *D,
754                                 const unsigned char *const BufferEnd,
755                                 support::endianness Endianness) {
756   using namespace support;
757 
758   if (D + sizeof(ValueProfData) > BufferEnd)
759     return make_error<InstrProfError>(instrprof_error::truncated);
760 
761   const unsigned char *Header = D;
762   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
763   if (D + TotalSize > BufferEnd)
764     return make_error<InstrProfError>(instrprof_error::too_large);
765 
766   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
767   memcpy(VPD.get(), D, TotalSize);
768   // Byte swap.
769   VPD->swapBytesToHost(Endianness);
770 
771   Error E = VPD->checkIntegrity();
772   if (E)
773     return std::move(E);
774 
775   return std::move(VPD);
776 }
777 
778 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
779   using namespace support;
780 
781   if (Endianness == getHostEndianness())
782     return;
783 
784   sys::swapByteOrder<uint32_t>(TotalSize);
785   sys::swapByteOrder<uint32_t>(NumValueKinds);
786 
787   ValueProfRecord *VR = getFirstValueProfRecord(this);
788   for (uint32_t K = 0; K < NumValueKinds; K++) {
789     VR->swapBytes(Endianness, getHostEndianness());
790     VR = getValueProfRecordNext(VR);
791   }
792 }
793 
794 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
795   using namespace support;
796 
797   if (Endianness == getHostEndianness())
798     return;
799 
800   ValueProfRecord *VR = getFirstValueProfRecord(this);
801   for (uint32_t K = 0; K < NumValueKinds; K++) {
802     ValueProfRecord *NVR = getValueProfRecordNext(VR);
803     VR->swapBytes(getHostEndianness(), Endianness);
804     VR = NVR;
805   }
806   sys::swapByteOrder<uint32_t>(TotalSize);
807   sys::swapByteOrder<uint32_t>(NumValueKinds);
808 }
809 
810 void annotateValueSite(Module &M, Instruction &Inst,
811                        const InstrProfRecord &InstrProfR,
812                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
813                        uint32_t MaxMDCount) {
814   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
815   if (!NV)
816     return;
817 
818   uint64_t Sum = 0;
819   std::unique_ptr<InstrProfValueData[]> VD =
820       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
821 
822   ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
823   annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
824 }
825 
826 void annotateValueSite(Module &M, Instruction &Inst,
827                        ArrayRef<InstrProfValueData> VDs,
828                        uint64_t Sum, InstrProfValueKind ValueKind,
829                        uint32_t MaxMDCount) {
830   LLVMContext &Ctx = M.getContext();
831   MDBuilder MDHelper(Ctx);
832   SmallVector<Metadata *, 3> Vals;
833   // Tag
834   Vals.push_back(MDHelper.createString("VP"));
835   // Value Kind
836   Vals.push_back(MDHelper.createConstant(
837       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
838   // Total Count
839   Vals.push_back(
840       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
841 
842   // Value Profile Data
843   uint32_t MDCount = MaxMDCount;
844   for (auto &VD : VDs) {
845     Vals.push_back(MDHelper.createConstant(
846         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
847     Vals.push_back(MDHelper.createConstant(
848         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
849     if (--MDCount == 0)
850       break;
851   }
852   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
853 }
854 
855 bool getValueProfDataFromInst(const Instruction &Inst,
856                               InstrProfValueKind ValueKind,
857                               uint32_t MaxNumValueData,
858                               InstrProfValueData ValueData[],
859                               uint32_t &ActualNumValueData, uint64_t &TotalC) {
860   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
861   if (!MD)
862     return false;
863 
864   unsigned NOps = MD->getNumOperands();
865 
866   if (NOps < 5)
867     return false;
868 
869   // Operand 0 is a string tag "VP":
870   MDString *Tag = cast<MDString>(MD->getOperand(0));
871   if (!Tag)
872     return false;
873 
874   if (!Tag->getString().equals("VP"))
875     return false;
876 
877   // Now check kind:
878   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
879   if (!KindInt)
880     return false;
881   if (KindInt->getZExtValue() != ValueKind)
882     return false;
883 
884   // Get total count
885   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
886   if (!TotalCInt)
887     return false;
888   TotalC = TotalCInt->getZExtValue();
889 
890   ActualNumValueData = 0;
891 
892   for (unsigned I = 3; I < NOps; I += 2) {
893     if (ActualNumValueData >= MaxNumValueData)
894       break;
895     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
896     ConstantInt *Count =
897         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
898     if (!Value || !Count)
899       return false;
900     ValueData[ActualNumValueData].Value = Value->getZExtValue();
901     ValueData[ActualNumValueData].Count = Count->getZExtValue();
902     ActualNumValueData++;
903   }
904   return true;
905 }
906 
907 MDNode *getPGOFuncNameMetadata(const Function &F) {
908   return F.getMetadata(getPGOFuncNameMetadataName());
909 }
910 
911 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
912   // Only for internal linkage functions.
913   if (PGOFuncName == F.getName())
914       return;
915   // Don't create duplicated meta-data.
916   if (getPGOFuncNameMetadata(F))
917     return;
918   LLVMContext &C = F.getContext();
919   MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
920   F.setMetadata(getPGOFuncNameMetadataName(), N);
921 }
922 
923 bool needsComdatForCounter(const Function &F, const Module &M) {
924   if (F.hasComdat())
925     return true;
926 
927   Triple TT(M.getTargetTriple());
928   if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
929     return false;
930 
931   // See createPGOFuncNameVar for more details. To avoid link errors, profile
932   // counters for function with available_externally linkage needs to be changed
933   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
934   // created. Without using comdat, duplicate entries won't be removed by the
935   // linker leading to increased data segement size and raw profile size. Even
936   // worse, since the referenced counter from profile per-function data object
937   // will be resolved to the common strong definition, the profile counts for
938   // available_externally functions will end up being duplicated in raw profile
939   // data. This can result in distorted profile as the counts of those dups
940   // will be accumulated by the profile merger.
941   GlobalValue::LinkageTypes Linkage = F.getLinkage();
942   if (Linkage != GlobalValue::ExternalWeakLinkage &&
943       Linkage != GlobalValue::AvailableExternallyLinkage)
944     return false;
945 
946   return true;
947 }
948 
949 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
950 bool isIRPGOFlagSet(const Module *M) {
951   auto IRInstrVar =
952       M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
953   if (!IRInstrVar || IRInstrVar->isDeclaration() ||
954       IRInstrVar->hasLocalLinkage())
955     return false;
956 
957   // Check if the flag is set.
958   if (!IRInstrVar->hasInitializer())
959     return false;
960 
961   const Constant *InitVal = IRInstrVar->getInitializer();
962   if (!InitVal)
963     return false;
964 
965   return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
966           VARIANT_MASK_IR_PROF) != 0;
967 }
968 
969 // Check if we can safely rename this Comdat function.
970 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
971   if (F.getName().empty())
972     return false;
973   if (!needsComdatForCounter(F, *(F.getParent())))
974     return false;
975   // Unsafe to rename the address-taken function (which can be used in
976   // function comparison).
977   if (CheckAddressTaken && F.hasAddressTaken())
978     return false;
979   // Only safe to do if this function may be discarded if it is not used
980   // in the compilation unit.
981   if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
982     return false;
983 
984   // For AvailableExternallyLinkage functions.
985   if (!F.hasComdat()) {
986     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
987     return true;
988   }
989   return true;
990 }
991 
992 // Parse the value profile options.
993 void getMemOPSizeRangeFromOption(StringRef MemOPSizeRange, int64_t &RangeStart,
994                                  int64_t &RangeLast) {
995   static const int64_t DefaultMemOPSizeRangeStart = 0;
996   static const int64_t DefaultMemOPSizeRangeLast = 8;
997   RangeStart = DefaultMemOPSizeRangeStart;
998   RangeLast = DefaultMemOPSizeRangeLast;
999 
1000   if (!MemOPSizeRange.empty()) {
1001     auto Pos = MemOPSizeRange.find(':');
1002     if (Pos != std::string::npos) {
1003       if (Pos > 0)
1004         MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
1005       if (Pos < MemOPSizeRange.size() - 1)
1006         MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
1007     } else
1008       MemOPSizeRange.getAsInteger(10, RangeLast);
1009   }
1010   assert(RangeLast >= RangeStart);
1011 }
1012 
1013 } // end namespace llvm
1014