1 //===- bolt/Passes/IndirectCallPromotion.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the IndirectCallPromotion class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/IndirectCallPromotion.h"
14 #include "bolt/Passes/BinaryFunctionCallGraph.h"
15 #include "bolt/Passes/DataflowInfoManager.h"
16 #include "bolt/Utils/CommandLineOpts.h"
17 #include "llvm/Support/CommandLine.h"
18 
19 #define DEBUG_TYPE "ICP"
20 #define DEBUG_VERBOSE(Level, X)                                                \
21   if (opts::Verbosity >= (Level)) {                                            \
22     X;                                                                         \
23   }
24 
25 using namespace llvm;
26 using namespace bolt;
27 
28 namespace opts {
29 
30 extern cl::OptionCategory BoltOptCategory;
31 
32 extern cl::opt<IndirectCallPromotionType> IndirectCallPromotion;
33 extern cl::opt<unsigned> Verbosity;
34 extern cl::opt<unsigned> ExecutionCountThreshold;
35 
36 static cl::opt<unsigned> ICPJTRemainingPercentThreshold(
37     "icp-jt-remaining-percent-threshold",
38     cl::desc("The percentage threshold against remaining unpromoted indirect "
39              "call count for the promotion for jump tables"),
40     cl::init(30), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
41 
42 static cl::opt<unsigned> ICPJTTotalPercentThreshold(
43     "icp-jt-total-percent-threshold",
44     cl::desc(
45         "The percentage threshold against total count for the promotion for "
46         "jump tables"),
47     cl::init(5), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
48 
49 static cl::opt<unsigned> ICPCallsRemainingPercentThreshold(
50     "icp-calls-remaining-percent-threshold",
51     cl::desc("The percentage threshold against remaining unpromoted indirect "
52              "call count for the promotion for calls"),
53     cl::init(50), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
54 
55 static cl::opt<unsigned> ICPCallsTotalPercentThreshold(
56     "icp-calls-total-percent-threshold",
57     cl::desc(
58         "The percentage threshold against total count for the promotion for "
59         "calls"),
60     cl::init(30), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
61 
62 static cl::opt<unsigned> IndirectCallPromotionMispredictThreshold(
63     "indirect-call-promotion-mispredict-threshold",
64     cl::desc("misprediction threshold for skipping ICP on an "
65              "indirect call"),
66     cl::init(0), cl::ZeroOrMore, cl::cat(BoltOptCategory));
67 
68 static cl::opt<bool> IndirectCallPromotionUseMispredicts(
69     "indirect-call-promotion-use-mispredicts",
70     cl::desc("use misprediction frequency for determining whether or not ICP "
71              "should be applied at a callsite.  The "
72              "-indirect-call-promotion-mispredict-threshold value will be used "
73              "by this heuristic"),
74     cl::ZeroOrMore, cl::cat(BoltOptCategory));
75 
76 static cl::opt<unsigned> IndirectCallPromotionTopN(
77     "indirect-call-promotion-topn",
78     cl::desc("limit number of targets to consider when doing indirect "
79              "call promotion. 0 = no limit"),
80     cl::init(3), cl::ZeroOrMore, cl::cat(BoltOptCategory));
81 
82 static cl::opt<unsigned> IndirectCallPromotionCallsTopN(
83     "indirect-call-promotion-calls-topn",
84     cl::desc("limit number of targets to consider when doing indirect "
85              "call promotion on calls. 0 = no limit"),
86     cl::init(0), cl::ZeroOrMore, cl::cat(BoltOptCategory));
87 
88 static cl::opt<unsigned> IndirectCallPromotionJumpTablesTopN(
89     "indirect-call-promotion-jump-tables-topn",
90     cl::desc("limit number of targets to consider when doing indirect "
91              "call promotion on jump tables. 0 = no limit"),
92     cl::init(0), cl::ZeroOrMore, cl::cat(BoltOptCategory));
93 
94 static cl::opt<bool> EliminateLoads(
95     "icp-eliminate-loads",
96     cl::desc("enable load elimination using memory profiling data when "
97              "performing ICP"),
98     cl::init(true), cl::ZeroOrMore, cl::cat(BoltOptCategory));
99 
100 static cl::opt<unsigned> ICPTopCallsites(
101     "icp-top-callsites",
102     cl::desc("optimize hottest calls until at least this percentage of all "
103              "indirect calls frequency is covered. 0 = all callsites"),
104     cl::init(99), cl::Hidden, cl::ZeroOrMore, cl::cat(BoltOptCategory));
105 
106 static cl::list<std::string>
107     ICPFuncsList("icp-funcs", cl::CommaSeparated,
108                  cl::desc("list of functions to enable ICP for"),
109                  cl::value_desc("func1,func2,func3,..."), cl::Hidden,
110                  cl::cat(BoltOptCategory));
111 
112 static cl::opt<bool>
113     ICPOldCodeSequence("icp-old-code-sequence",
114                        cl::desc("use old code sequence for promoted calls"),
115                        cl::init(false), cl::ZeroOrMore, cl::Hidden,
116                        cl::cat(BoltOptCategory));
117 
118 static cl::opt<bool> ICPJumpTablesByTarget(
119     "icp-jump-tables-targets",
120     cl::desc(
121         "for jump tables, optimize indirect jmp targets instead of indices"),
122     cl::init(false), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
123 
124 } // namespace opts
125 
126 namespace llvm {
127 namespace bolt {
128 
129 namespace {
130 
131 bool verifyProfile(std::map<uint64_t, BinaryFunction> &BFs) {
132   bool IsValid = true;
133   for (auto &BFI : BFs) {
134     BinaryFunction &BF = BFI.second;
135     if (!BF.isSimple())
136       continue;
137     for (BinaryBasicBlock *BB : BF.layout()) {
138       auto BI = BB->branch_info_begin();
139       for (BinaryBasicBlock *SuccBB : BB->successors()) {
140         if (BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE && BI->Count > 0) {
141           if (BB->getKnownExecutionCount() == 0 ||
142               SuccBB->getKnownExecutionCount() == 0) {
143             errs() << "BOLT-WARNING: profile verification failed after ICP for "
144                       "function "
145                    << BF << '\n';
146             IsValid = false;
147           }
148         }
149         ++BI;
150       }
151     }
152   }
153   return IsValid;
154 }
155 
156 } // namespace
157 
158 IndirectCallPromotion::Callsite::Callsite(BinaryFunction &BF,
159                                           const IndirectCallProfile &ICP)
160     : From(BF.getSymbol()), To(ICP.Offset), Mispreds(ICP.Mispreds),
161       Branches(ICP.Count) {
162   if (ICP.Symbol) {
163     To.Sym = ICP.Symbol;
164     To.Addr = 0;
165   }
166 }
167 
168 void IndirectCallPromotion::printDecision(
169     llvm::raw_ostream &OS,
170     std::vector<IndirectCallPromotion::Callsite> &Targets, unsigned N) const {
171   uint64_t TotalCount = 0;
172   uint64_t TotalMispreds = 0;
173   for (const Callsite &S : Targets) {
174     TotalCount += S.Branches;
175     TotalMispreds += S.Mispreds;
176   }
177   if (!TotalCount)
178     TotalCount = 1;
179   if (!TotalMispreds)
180     TotalMispreds = 1;
181 
182   OS << "BOLT-INFO: ICP decision for call site with " << Targets.size()
183      << " targets, Count = " << TotalCount << ", Mispreds = " << TotalMispreds
184      << "\n";
185 
186   size_t I = 0;
187   for (const Callsite &S : Targets) {
188     OS << "Count = " << S.Branches << ", "
189        << format("%.1f", (100.0 * S.Branches) / TotalCount) << ", "
190        << "Mispreds = " << S.Mispreds << ", "
191        << format("%.1f", (100.0 * S.Mispreds) / TotalMispreds);
192     if (I < N)
193       OS << " * to be optimized *";
194     if (!S.JTIndices.empty()) {
195       OS << " Indices:";
196       for (const uint64_t Idx : S.JTIndices)
197         OS << " " << Idx;
198     }
199     OS << "\n";
200     I += S.JTIndices.empty() ? 1 : S.JTIndices.size();
201   }
202 }
203 
204 // Get list of targets for a given call sorted by most frequently
205 // called first.
206 std::vector<IndirectCallPromotion::Callsite>
207 IndirectCallPromotion::getCallTargets(BinaryBasicBlock &BB,
208                                       const MCInst &Inst) const {
209   BinaryFunction &BF = *BB.getFunction();
210   BinaryContext &BC = BF.getBinaryContext();
211   std::vector<Callsite> Targets;
212 
213   if (const JumpTable *JT = BF.getJumpTable(Inst)) {
214     // Don't support PIC jump tables for now
215     if (!opts::ICPJumpTablesByTarget && JT->Type == JumpTable::JTT_PIC)
216       return Targets;
217     const Location From(BF.getSymbol());
218     const std::pair<size_t, size_t> Range =
219         JT->getEntriesForAddress(BC.MIB->getJumpTable(Inst));
220     assert(JT->Counts.empty() || JT->Counts.size() >= Range.second);
221     JumpTable::JumpInfo DefaultJI;
222     const JumpTable::JumpInfo *JI =
223         JT->Counts.empty() ? &DefaultJI : &JT->Counts[Range.first];
224     const size_t JIAdj = JT->Counts.empty() ? 0 : 1;
225     assert(JT->Type == JumpTable::JTT_PIC ||
226            JT->EntrySize == BC.AsmInfo->getCodePointerSize());
227     for (size_t I = Range.first; I < Range.second; ++I, JI += JIAdj) {
228       MCSymbol *Entry = JT->Entries[I];
229       assert(BF.getBasicBlockForLabel(Entry) ||
230              Entry == BF.getFunctionEndLabel() ||
231              Entry == BF.getFunctionColdEndLabel());
232       if (Entry == BF.getFunctionEndLabel() ||
233           Entry == BF.getFunctionColdEndLabel())
234         continue;
235       const Location To(Entry);
236       const BinaryBasicBlock::BinaryBranchInfo &BI = BB.getBranchInfo(Entry);
237       Targets.emplace_back(From, To, BI.MispredictedCount, BI.Count,
238                            I - Range.first);
239     }
240 
241     // Sort by symbol then addr.
242     std::sort(Targets.begin(), Targets.end(),
243               [](const Callsite &A, const Callsite &B) {
244                 if (A.To.Sym && B.To.Sym)
245                   return A.To.Sym < B.To.Sym;
246                 else if (A.To.Sym && !B.To.Sym)
247                   return true;
248                 else if (!A.To.Sym && B.To.Sym)
249                   return false;
250                 else
251                   return A.To.Addr < B.To.Addr;
252               });
253 
254     // Targets may contain multiple entries to the same target, but using
255     // different indices. Their profile will report the same number of branches
256     // for different indices if the target is the same. That's because we don't
257     // profile the index value, but only the target via LBR.
258     auto First = Targets.begin();
259     auto Last = Targets.end();
260     auto Result = First;
261     while (++First != Last) {
262       Callsite &A = *Result;
263       const Callsite &B = *First;
264       if (A.To.Sym && B.To.Sym && A.To.Sym == B.To.Sym)
265         A.JTIndices.insert(A.JTIndices.end(), B.JTIndices.begin(),
266                            B.JTIndices.end());
267       else
268         *(++Result) = *First;
269     }
270     ++Result;
271 
272     LLVM_DEBUG(if (Targets.end() - Result > 0) {
273       dbgs() << "BOLT-INFO: ICP: " << (Targets.end() - Result)
274              << " duplicate targets removed\n";
275     });
276 
277     Targets.erase(Result, Targets.end());
278   } else {
279     // Don't try to optimize PC relative indirect calls.
280     if (Inst.getOperand(0).isReg() &&
281         Inst.getOperand(0).getReg() == BC.MRI->getProgramCounter())
282       return Targets;
283 
284     auto ICSP = BC.MIB->tryGetAnnotationAs<IndirectCallSiteProfile>(
285         Inst, "CallProfile");
286     if (ICSP) {
287       for (const IndirectCallProfile &CSP : ICSP.get()) {
288         Callsite Site(BF, CSP);
289         if (Site.isValid())
290           Targets.emplace_back(std::move(Site));
291       }
292     }
293   }
294 
295   // Sort by target count, number of indices in case of jump table,  and
296   // mispredicts. We prioritize targets with high count, small number of
297   // indices and high mispredicts
298   std::stable_sort(Targets.begin(), Targets.end(),
299                    [](const Callsite &A, const Callsite &B) {
300                      if (A.Branches != B.Branches)
301                        return A.Branches > B.Branches;
302                      else if (A.JTIndices.size() != B.JTIndices.size())
303                        return A.JTIndices.size() < B.JTIndices.size();
304                      else
305                        return A.Mispreds > B.Mispreds;
306                    });
307 
308   // Remove non-symbol targets
309   auto Last = std::remove_if(Targets.begin(), Targets.end(),
310                              [](const Callsite &CS) { return !CS.To.Sym; });
311   Targets.erase(Last, Targets.end());
312 
313   LLVM_DEBUG(if (BF.getJumpTable(Inst)) {
314     uint64_t TotalCount = 0;
315     uint64_t TotalMispreds = 0;
316     for (const Callsite &S : Targets) {
317       TotalCount += S.Branches;
318       TotalMispreds += S.Mispreds;
319     }
320     if (!TotalCount)
321       TotalCount = 1;
322     if (!TotalMispreds)
323       TotalMispreds = 1;
324 
325     dbgs() << "BOLT-INFO: ICP: jump table size = " << Targets.size()
326            << ", Count = " << TotalCount << ", Mispreds = " << TotalMispreds
327            << "\n";
328 
329     size_t I = 0;
330     for (const Callsite &S : Targets) {
331       dbgs() << "Count[" << I << "] = " << S.Branches << ", "
332              << format("%.1f", (100.0 * S.Branches) / TotalCount) << ", "
333              << "Mispreds[" << I << "] = " << S.Mispreds << ", "
334              << format("%.1f", (100.0 * S.Mispreds) / TotalMispreds) << "\n";
335       ++I;
336     }
337   });
338 
339   return Targets;
340 }
341 
342 IndirectCallPromotion::JumpTableInfoType
343 IndirectCallPromotion::maybeGetHotJumpTableTargets(BinaryBasicBlock &BB,
344                                                    MCInst &CallInst,
345                                                    MCInst *&TargetFetchInst,
346                                                    const JumpTable *JT) const {
347   assert(JT && "Can't get jump table addrs for non-jump tables.");
348 
349   BinaryFunction &Function = *BB.getFunction();
350   BinaryContext &BC = Function.getBinaryContext();
351 
352   if (!Function.hasMemoryProfile() || !opts::EliminateLoads)
353     return JumpTableInfoType();
354 
355   JumpTableInfoType HotTargets;
356   MCInst *MemLocInstr;
357   MCInst *PCRelBaseOut;
358   unsigned BaseReg, IndexReg;
359   int64_t DispValue;
360   const MCExpr *DispExpr;
361   MutableArrayRef<MCInst> Insts(&BB.front(), &CallInst);
362   const IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
363       CallInst, Insts.begin(), Insts.end(), BC.AsmInfo->getCodePointerSize(),
364       MemLocInstr, BaseReg, IndexReg, DispValue, DispExpr, PCRelBaseOut);
365 
366   assert(MemLocInstr && "There should always be a load for jump tables");
367   if (!MemLocInstr)
368     return JumpTableInfoType();
369 
370   LLVM_DEBUG({
371     dbgs() << "BOLT-INFO: ICP attempting to find memory profiling data for "
372            << "jump table in " << Function << " at @ "
373            << (&CallInst - &BB.front()) << "\n"
374            << "BOLT-INFO: ICP target fetch instructions:\n";
375     BC.printInstruction(dbgs(), *MemLocInstr, 0, &Function);
376     if (MemLocInstr != &CallInst)
377       BC.printInstruction(dbgs(), CallInst, 0, &Function);
378   });
379 
380   DEBUG_VERBOSE(1, {
381     dbgs() << "Jmp info: Type = " << (unsigned)Type << ", "
382            << "BaseReg = " << BC.MRI->getName(BaseReg) << ", "
383            << "IndexReg = " << BC.MRI->getName(IndexReg) << ", "
384            << "DispValue = " << Twine::utohexstr(DispValue) << ", "
385            << "DispExpr = " << DispExpr << ", "
386            << "MemLocInstr = ";
387     BC.printInstruction(dbgs(), *MemLocInstr, 0, &Function);
388     dbgs() << "\n";
389   });
390 
391   ++TotalIndexBasedCandidates;
392 
393   auto ErrorOrMemAccesssProfile =
394       BC.MIB->tryGetAnnotationAs<MemoryAccessProfile>(*MemLocInstr,
395                                                       "MemoryAccessProfile");
396   if (!ErrorOrMemAccesssProfile) {
397     DEBUG_VERBOSE(1, dbgs()
398                          << "BOLT-INFO: ICP no memory profiling data found\n");
399     return JumpTableInfoType();
400   }
401   MemoryAccessProfile &MemAccessProfile = ErrorOrMemAccesssProfile.get();
402 
403   uint64_t ArrayStart;
404   if (DispExpr) {
405     ErrorOr<uint64_t> DispValueOrError =
406         BC.getSymbolValue(*BC.MIB->getTargetSymbol(DispExpr));
407     assert(DispValueOrError && "global symbol needs a value");
408     ArrayStart = *DispValueOrError;
409   } else {
410     ArrayStart = static_cast<uint64_t>(DispValue);
411   }
412 
413   if (BaseReg == BC.MRI->getProgramCounter())
414     ArrayStart += Function.getAddress() + MemAccessProfile.NextInstrOffset;
415 
416   // This is a map of [symbol] -> [count, index] and is used to combine indices
417   // into the jump table since there may be multiple addresses that all have the
418   // same entry.
419   std::map<MCSymbol *, std::pair<uint64_t, uint64_t>> HotTargetMap;
420   const std::pair<size_t, size_t> Range = JT->getEntriesForAddress(ArrayStart);
421 
422   for (const AddressAccess &AccessInfo : MemAccessProfile.AddressAccessInfo) {
423     size_t Index;
424     // Mem data occasionally includes nullprs, ignore them.
425     if (!AccessInfo.MemoryObject && !AccessInfo.Offset)
426       continue;
427 
428     if (AccessInfo.Offset % JT->EntrySize != 0) // ignore bogus data
429       return JumpTableInfoType();
430 
431     if (AccessInfo.MemoryObject) {
432       // Deal with bad/stale data
433       if (!AccessInfo.MemoryObject->getName().startswith(
434               "JUMP_TABLE/" + Function.getOneName().str()))
435         return JumpTableInfoType();
436       Index =
437           (AccessInfo.Offset - (ArrayStart - JT->getAddress())) / JT->EntrySize;
438     } else {
439       Index = (AccessInfo.Offset - ArrayStart) / JT->EntrySize;
440     }
441 
442     // If Index is out of range it probably means the memory profiling data is
443     // wrong for this instruction, bail out.
444     if (Index >= Range.second) {
445       LLVM_DEBUG(dbgs() << "BOLT-INFO: Index out of range of " << Range.first
446                         << ", " << Range.second << "\n");
447       return JumpTableInfoType();
448     }
449 
450     // Make sure the hot index points at a legal label corresponding to a BB,
451     // e.g. not the end of function (unreachable) label.
452     if (!Function.getBasicBlockForLabel(JT->Entries[Index + Range.first])) {
453       LLVM_DEBUG({
454         dbgs() << "BOLT-INFO: hot index " << Index << " pointing at bogus "
455                << "label " << JT->Entries[Index + Range.first]->getName()
456                << " in jump table:\n";
457         JT->print(dbgs());
458         dbgs() << "HotTargetMap:\n";
459         for (std::pair<MCSymbol *const, std::pair<uint64_t, uint64_t>> &HT :
460              HotTargetMap)
461           dbgs() << "BOLT-INFO: " << HT.first->getName()
462                  << " = (count=" << HT.second.first
463                  << ", index=" << HT.second.second << ")\n";
464       });
465       return JumpTableInfoType();
466     }
467 
468     std::pair<uint64_t, uint64_t> &HotTarget =
469         HotTargetMap[JT->Entries[Index + Range.first]];
470     HotTarget.first += AccessInfo.Count;
471     HotTarget.second = Index;
472   }
473 
474   std::transform(
475       HotTargetMap.begin(), HotTargetMap.end(), std::back_inserter(HotTargets),
476       [](const std::pair<MCSymbol *, std::pair<uint64_t, uint64_t>> &A) {
477         return A.second;
478       });
479 
480   // Sort with highest counts first.
481   std::sort(HotTargets.rbegin(), HotTargets.rend());
482 
483   LLVM_DEBUG({
484     dbgs() << "BOLT-INFO: ICP jump table hot targets:\n";
485     for (const std::pair<uint64_t, uint64_t> &Target : HotTargets)
486       dbgs() << "BOLT-INFO:  Idx = " << Target.second << ", "
487              << "Count = " << Target.first << "\n";
488   });
489 
490   BC.MIB->getOrCreateAnnotationAs<uint16_t>(CallInst, "JTIndexReg") = IndexReg;
491 
492   TargetFetchInst = MemLocInstr;
493 
494   return HotTargets;
495 }
496 
497 IndirectCallPromotion::SymTargetsType
498 IndirectCallPromotion::findCallTargetSymbols(std::vector<Callsite> &Targets,
499                                              size_t &N, BinaryBasicBlock &BB,
500                                              MCInst &CallInst,
501                                              MCInst *&TargetFetchInst) const {
502   const JumpTable *JT = BB.getFunction()->getJumpTable(CallInst);
503   SymTargetsType SymTargets;
504 
505   if (JT) {
506     JumpTableInfoType HotTargets =
507         maybeGetHotJumpTableTargets(BB, CallInst, TargetFetchInst, JT);
508 
509     if (!HotTargets.empty()) {
510       auto findTargetsIndex = [&](uint64_t JTIndex) {
511         for (size_t I = 0; I < Targets.size(); ++I) {
512           std::vector<uint64_t> &JTIs = Targets[I].JTIndices;
513           if (std::find(JTIs.begin(), JTIs.end(), JTIndex) != JTIs.end())
514             return I;
515         }
516         LLVM_DEBUG(
517             dbgs() << "BOLT-ERROR: Unable to find target index for hot jump "
518                    << " table entry in " << *BB.getFunction() << "\n");
519         llvm_unreachable("Hot indices must be referred to by at least one "
520                          "callsite");
521       };
522 
523       if (opts::Verbosity >= 1)
524         for (size_t I = 0; I < HotTargets.size(); ++I)
525           outs() << "BOLT-INFO: HotTarget[" << I << "] = ("
526                  << HotTargets[I].first << ", " << HotTargets[I].second
527                  << ")\n";
528 
529       // Recompute hottest targets, now discriminating which index is hot
530       // NOTE: This is a tradeoff. On one hand, we get index information. On the
531       // other hand, info coming from the memory profile is much less accurate
532       // than LBRs. So we may actually end up working with more coarse
533       // profile granularity in exchange for information about indices.
534       std::vector<Callsite> NewTargets;
535       std::map<const MCSymbol *, uint32_t> IndicesPerTarget;
536       uint64_t TotalMemAccesses = 0;
537       for (size_t I = 0; I < HotTargets.size(); ++I) {
538         const uint64_t TargetIndex = findTargetsIndex(HotTargets[I].second);
539         ++IndicesPerTarget[Targets[TargetIndex].To.Sym];
540         TotalMemAccesses += HotTargets[I].first;
541       }
542       uint64_t RemainingMemAccesses = TotalMemAccesses;
543       const size_t TopN = opts::IndirectCallPromotionJumpTablesTopN != 0
544                               ? opts::IndirectCallPromotionTopN
545                               : opts::IndirectCallPromotionTopN;
546       size_t I = 0;
547       for (; I < HotTargets.size(); ++I) {
548         const uint64_t MemAccesses = HotTargets[I].first;
549         if (100 * MemAccesses <
550             TotalMemAccesses * opts::ICPJTTotalPercentThreshold)
551           break;
552         if (100 * MemAccesses <
553             RemainingMemAccesses * opts::ICPJTRemainingPercentThreshold)
554           break;
555         if (TopN && I >= TopN)
556           break;
557         RemainingMemAccesses -= MemAccesses;
558 
559         const uint64_t JTIndex = HotTargets[I].second;
560         Callsite &Target = Targets[findTargetsIndex(JTIndex)];
561 
562         NewTargets.push_back(Target);
563         std::vector<uint64_t>({JTIndex}).swap(NewTargets.back().JTIndices);
564         Target.JTIndices.erase(std::remove(Target.JTIndices.begin(),
565                                            Target.JTIndices.end(), JTIndex),
566                                Target.JTIndices.end());
567 
568         // Keep fixCFG counts sane if more indices use this same target later
569         assert(IndicesPerTarget[Target.To.Sym] > 0 && "wrong map");
570         NewTargets.back().Branches =
571             Target.Branches / IndicesPerTarget[Target.To.Sym];
572         NewTargets.back().Mispreds =
573             Target.Mispreds / IndicesPerTarget[Target.To.Sym];
574         assert(Target.Branches >= NewTargets.back().Branches);
575         assert(Target.Mispreds >= NewTargets.back().Mispreds);
576         Target.Branches -= NewTargets.back().Branches;
577         Target.Mispreds -= NewTargets.back().Mispreds;
578       }
579       std::copy(Targets.begin(), Targets.end(), std::back_inserter(NewTargets));
580       std::swap(NewTargets, Targets);
581       N = I;
582 
583       if (N == 0 && opts::Verbosity >= 1) {
584         outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " in "
585                << BB.getName()
586                << ": failed to meet thresholds after memory profile data was "
587                   "loaded.\n";
588         return SymTargets;
589       }
590     }
591 
592     for (size_t I = 0, TgtIdx = 0; I < N; ++TgtIdx) {
593       Callsite &Target = Targets[TgtIdx];
594       assert(Target.To.Sym && "All ICP targets must be to known symbols");
595       assert(!Target.JTIndices.empty() && "Jump tables must have indices");
596       for (uint64_t Idx : Target.JTIndices) {
597         SymTargets.emplace_back(Target.To.Sym, Idx);
598         ++I;
599       }
600     }
601   } else {
602     for (size_t I = 0; I < N; ++I) {
603       assert(Targets[I].To.Sym && "All ICP targets must be to known symbols");
604       assert(Targets[I].JTIndices.empty() &&
605              "Can't have jump table indices for non-jump tables");
606       SymTargets.emplace_back(Targets[I].To.Sym, 0);
607     }
608   }
609 
610   return SymTargets;
611 }
612 
613 IndirectCallPromotion::MethodInfoType IndirectCallPromotion::maybeGetVtableSyms(
614     BinaryBasicBlock &BB, MCInst &Inst,
615     const SymTargetsType &SymTargets) const {
616   BinaryFunction &Function = *BB.getFunction();
617   BinaryContext &BC = Function.getBinaryContext();
618   std::vector<std::pair<MCSymbol *, uint64_t>> VtableSyms;
619   std::vector<MCInst *> MethodFetchInsns;
620   unsigned VtableReg, MethodReg;
621   uint64_t MethodOffset;
622 
623   assert(!Function.getJumpTable(Inst) &&
624          "Can't get vtable addrs for jump tables.");
625 
626   if (!Function.hasMemoryProfile() || !opts::EliminateLoads)
627     return MethodInfoType();
628 
629   MutableArrayRef<MCInst> Insts(&BB.front(), &Inst + 1);
630   if (!BC.MIB->analyzeVirtualMethodCall(Insts.begin(), Insts.end(),
631                                         MethodFetchInsns, VtableReg, MethodReg,
632                                         MethodOffset)) {
633     DEBUG_VERBOSE(
634         1, dbgs() << "BOLT-INFO: ICP unable to analyze method call in "
635                   << Function << " at @ " << (&Inst - &BB.front()) << "\n");
636     return MethodInfoType();
637   }
638 
639   ++TotalMethodLoadEliminationCandidates;
640 
641   DEBUG_VERBOSE(1, {
642     dbgs() << "BOLT-INFO: ICP found virtual method call in " << Function
643            << " at @ " << (&Inst - &BB.front()) << "\n";
644     dbgs() << "BOLT-INFO: ICP method fetch instructions:\n";
645     for (MCInst *Inst : MethodFetchInsns)
646       BC.printInstruction(dbgs(), *Inst, 0, &Function);
647 
648     if (MethodFetchInsns.back() != &Inst)
649       BC.printInstruction(dbgs(), Inst, 0, &Function);
650   });
651 
652   // Try to get value profiling data for the method load instruction.
653   auto ErrorOrMemAccesssProfile =
654       BC.MIB->tryGetAnnotationAs<MemoryAccessProfile>(*MethodFetchInsns.back(),
655                                                       "MemoryAccessProfile");
656   if (!ErrorOrMemAccesssProfile) {
657     DEBUG_VERBOSE(1, dbgs()
658                          << "BOLT-INFO: ICP no memory profiling data found\n");
659     return MethodInfoType();
660   }
661   MemoryAccessProfile &MemAccessProfile = ErrorOrMemAccesssProfile.get();
662 
663   // Find the vtable that each method belongs to.
664   std::map<const MCSymbol *, uint64_t> MethodToVtable;
665 
666   for (const AddressAccess &AccessInfo : MemAccessProfile.AddressAccessInfo) {
667     uint64_t Address = AccessInfo.Offset;
668     if (AccessInfo.MemoryObject)
669       Address += AccessInfo.MemoryObject->getAddress();
670 
671     // Ignore bogus data.
672     if (!Address)
673       continue;
674 
675     const uint64_t VtableBase = Address - MethodOffset;
676 
677     DEBUG_VERBOSE(1, dbgs() << "BOLT-INFO: ICP vtable = "
678                             << Twine::utohexstr(VtableBase) << "+"
679                             << MethodOffset << "/" << AccessInfo.Count << "\n");
680 
681     if (ErrorOr<uint64_t> MethodAddr = BC.getPointerAtAddress(Address)) {
682       BinaryData *MethodBD = BC.getBinaryDataAtAddress(MethodAddr.get());
683       if (!MethodBD) // skip unknown methods
684         continue;
685       MCSymbol *MethodSym = MethodBD->getSymbol();
686       MethodToVtable[MethodSym] = VtableBase;
687       DEBUG_VERBOSE(1, {
688         const BinaryFunction *Method = BC.getFunctionForSymbol(MethodSym);
689         dbgs() << "BOLT-INFO: ICP found method = "
690                << Twine::utohexstr(MethodAddr.get()) << "/"
691                << (Method ? Method->getPrintName() : "") << "\n";
692       });
693     }
694   }
695 
696   // Find the vtable for each target symbol.
697   for (size_t I = 0; I < SymTargets.size(); ++I) {
698     auto Itr = MethodToVtable.find(SymTargets[I].first);
699     if (Itr != MethodToVtable.end()) {
700       if (BinaryData *BD = BC.getBinaryDataContainingAddress(Itr->second)) {
701         const uint64_t Addend = Itr->second - BD->getAddress();
702         VtableSyms.emplace_back(BD->getSymbol(), Addend);
703         continue;
704       }
705     }
706     // Give up if we can't find the vtable for a method.
707     DEBUG_VERBOSE(1, dbgs() << "BOLT-INFO: ICP can't find vtable for "
708                             << SymTargets[I].first->getName() << "\n");
709     return MethodInfoType();
710   }
711 
712   // Make sure the vtable reg is not clobbered by the argument passing code
713   if (VtableReg != MethodReg) {
714     for (MCInst *CurInst = MethodFetchInsns.front(); CurInst < &Inst;
715          ++CurInst) {
716       const MCInstrDesc &InstrInfo = BC.MII->get(CurInst->getOpcode());
717       if (InstrInfo.hasDefOfPhysReg(*CurInst, VtableReg, *BC.MRI))
718         return MethodInfoType();
719     }
720   }
721 
722   return MethodInfoType(VtableSyms, MethodFetchInsns);
723 }
724 
725 std::vector<std::unique_ptr<BinaryBasicBlock>>
726 IndirectCallPromotion::rewriteCall(
727     BinaryBasicBlock &IndCallBlock, const MCInst &CallInst,
728     MCPlusBuilder::BlocksVectorTy &&ICPcode,
729     const std::vector<MCInst *> &MethodFetchInsns) const {
730   BinaryFunction &Function = *IndCallBlock.getFunction();
731   MCPlusBuilder *MIB = Function.getBinaryContext().MIB.get();
732 
733   // Create new basic blocks with correct code in each one first.
734   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
735   const bool IsTailCallOrJT =
736       (MIB->isTailCall(CallInst) || Function.getJumpTable(CallInst));
737 
738   // Move instructions from the tail of the original call block
739   // to the merge block.
740 
741   // Remember any pseudo instructions following a tail call.  These
742   // must be preserved and moved to the original block.
743   InstructionListType TailInsts;
744   const MCInst *TailInst = &CallInst;
745   if (IsTailCallOrJT)
746     while (TailInst + 1 < &(*IndCallBlock.end()) &&
747            MIB->isPseudo(*(TailInst + 1)))
748       TailInsts.push_back(*++TailInst);
749 
750   InstructionListType MovedInst = IndCallBlock.splitInstructions(&CallInst);
751   // Link new BBs to the original input offset of the BB where the indirect
752   // call site is, so we can map samples recorded in new BBs back to the
753   // original BB seen in the input binary (if using BAT)
754   const uint32_t OrigOffset = IndCallBlock.getInputOffset();
755 
756   IndCallBlock.eraseInstructions(MethodFetchInsns.begin(),
757                                  MethodFetchInsns.end());
758   if (IndCallBlock.empty() ||
759       (!MethodFetchInsns.empty() && MethodFetchInsns.back() == &CallInst))
760     IndCallBlock.addInstructions(ICPcode.front().second.begin(),
761                                  ICPcode.front().second.end());
762   else
763     IndCallBlock.replaceInstruction(std::prev(IndCallBlock.end()),
764                                     ICPcode.front().second);
765   IndCallBlock.addInstructions(TailInsts.begin(), TailInsts.end());
766 
767   for (auto Itr = ICPcode.begin() + 1; Itr != ICPcode.end(); ++Itr) {
768     MCSymbol *&Sym = Itr->first;
769     InstructionListType &Insts = Itr->second;
770     assert(Sym);
771     std::unique_ptr<BinaryBasicBlock> TBB =
772         Function.createBasicBlock(OrigOffset, Sym);
773     for (MCInst &Inst : Insts) // sanitize new instructions.
774       if (MIB->isCall(Inst))
775         MIB->removeAnnotation(Inst, "CallProfile");
776     TBB->addInstructions(Insts.begin(), Insts.end());
777     NewBBs.emplace_back(std::move(TBB));
778   }
779 
780   // Move tail of instructions from after the original call to
781   // the merge block.
782   if (!IsTailCallOrJT)
783     NewBBs.back()->addInstructions(MovedInst.begin(), MovedInst.end());
784 
785   return NewBBs;
786 }
787 
788 BinaryBasicBlock *
789 IndirectCallPromotion::fixCFG(BinaryBasicBlock &IndCallBlock,
790                               const bool IsTailCall, const bool IsJumpTable,
791                               IndirectCallPromotion::BasicBlocksVector &&NewBBs,
792                               const std::vector<Callsite> &Targets) const {
793   BinaryFunction &Function = *IndCallBlock.getFunction();
794   using BinaryBranchInfo = BinaryBasicBlock::BinaryBranchInfo;
795   BinaryBasicBlock *MergeBlock = nullptr;
796 
797   // Scale indirect call counts to the execution count of the original
798   // basic block containing the indirect call.
799   uint64_t TotalCount = IndCallBlock.getKnownExecutionCount();
800   uint64_t TotalIndirectBranches = 0;
801   for (const Callsite &Target : Targets)
802     TotalIndirectBranches += Target.Branches;
803   if (TotalIndirectBranches == 0)
804     TotalIndirectBranches = 1;
805   BinaryBasicBlock::BranchInfoType BBI;
806   BinaryBasicBlock::BranchInfoType ScaledBBI;
807   for (const Callsite &Target : Targets) {
808     const size_t NumEntries =
809         std::max(static_cast<std::size_t>(1UL), Target.JTIndices.size());
810     for (size_t I = 0; I < NumEntries; ++I) {
811       BBI.push_back(
812           BinaryBranchInfo{(Target.Branches + NumEntries - 1) / NumEntries,
813                            (Target.Mispreds + NumEntries - 1) / NumEntries});
814       ScaledBBI.push_back(
815           BinaryBranchInfo{uint64_t(TotalCount * Target.Branches /
816                                     (NumEntries * TotalIndirectBranches)),
817                            uint64_t(TotalCount * Target.Mispreds /
818                                     (NumEntries * TotalIndirectBranches))});
819     }
820   }
821 
822   if (IsJumpTable) {
823     BinaryBasicBlock *NewIndCallBlock = NewBBs.back().get();
824     IndCallBlock.moveAllSuccessorsTo(NewIndCallBlock);
825 
826     std::vector<MCSymbol *> SymTargets;
827     for (const Callsite &Target : Targets) {
828       const size_t NumEntries =
829           std::max(static_cast<std::size_t>(1UL), Target.JTIndices.size());
830       for (size_t I = 0; I < NumEntries; ++I)
831         SymTargets.push_back(Target.To.Sym);
832     }
833     assert(SymTargets.size() > NewBBs.size() - 1 &&
834            "There must be a target symbol associated with each new BB.");
835 
836     for (uint64_t I = 0; I < NewBBs.size(); ++I) {
837       BinaryBasicBlock *SourceBB = I ? NewBBs[I - 1].get() : &IndCallBlock;
838       SourceBB->setExecutionCount(TotalCount);
839 
840       BinaryBasicBlock *TargetBB =
841           Function.getBasicBlockForLabel(SymTargets[I]);
842       SourceBB->addSuccessor(TargetBB, ScaledBBI[I]); // taken
843 
844       TotalCount -= ScaledBBI[I].Count;
845       SourceBB->addSuccessor(NewBBs[I].get(), TotalCount); // fall-through
846 
847       // Update branch info for the indirect jump.
848       BinaryBasicBlock::BinaryBranchInfo &BranchInfo =
849           NewIndCallBlock->getBranchInfo(*TargetBB);
850       if (BranchInfo.Count > BBI[I].Count)
851         BranchInfo.Count -= BBI[I].Count;
852       else
853         BranchInfo.Count = 0;
854 
855       if (BranchInfo.MispredictedCount > BBI[I].MispredictedCount)
856         BranchInfo.MispredictedCount -= BBI[I].MispredictedCount;
857       else
858         BranchInfo.MispredictedCount = 0;
859     }
860   } else {
861     assert(NewBBs.size() >= 2);
862     assert(NewBBs.size() % 2 == 1 || IndCallBlock.succ_empty());
863     assert(NewBBs.size() % 2 == 1 || IsTailCall);
864 
865     auto ScaledBI = ScaledBBI.begin();
866     auto updateCurrentBranchInfo = [&] {
867       assert(ScaledBI != ScaledBBI.end());
868       TotalCount -= ScaledBI->Count;
869       ++ScaledBI;
870     };
871 
872     if (!IsTailCall) {
873       MergeBlock = NewBBs.back().get();
874       IndCallBlock.moveAllSuccessorsTo(MergeBlock);
875     }
876 
877     // Fix up successors and execution counts.
878     updateCurrentBranchInfo();
879     IndCallBlock.addSuccessor(NewBBs[1].get(), TotalCount);
880     IndCallBlock.addSuccessor(NewBBs[0].get(), ScaledBBI[0]);
881 
882     const size_t Adj = IsTailCall ? 1 : 2;
883     for (size_t I = 0; I < NewBBs.size() - Adj; ++I) {
884       assert(TotalCount <= IndCallBlock.getExecutionCount() ||
885              TotalCount <= uint64_t(TotalIndirectBranches));
886       uint64_t ExecCount = ScaledBBI[(I + 1) / 2].Count;
887       if (I % 2 == 0) {
888         if (MergeBlock)
889           NewBBs[I]->addSuccessor(MergeBlock, ScaledBBI[(I + 1) / 2].Count);
890       } else {
891         assert(I + 2 < NewBBs.size());
892         updateCurrentBranchInfo();
893         NewBBs[I]->addSuccessor(NewBBs[I + 2].get(), TotalCount);
894         NewBBs[I]->addSuccessor(NewBBs[I + 1].get(), ScaledBBI[(I + 1) / 2]);
895         ExecCount += TotalCount;
896       }
897       NewBBs[I]->setExecutionCount(ExecCount);
898     }
899 
900     if (MergeBlock) {
901       // Arrange for the MergeBlock to be the fallthrough for the first
902       // promoted call block.
903       std::unique_ptr<BinaryBasicBlock> MBPtr;
904       std::swap(MBPtr, NewBBs.back());
905       NewBBs.pop_back();
906       NewBBs.emplace(NewBBs.begin() + 1, std::move(MBPtr));
907       // TODO: is COUNT_FALLTHROUGH_EDGE the right thing here?
908       NewBBs.back()->addSuccessor(MergeBlock, TotalCount); // uncond branch
909     }
910   }
911 
912   // Update the execution count.
913   NewBBs.back()->setExecutionCount(TotalCount);
914 
915   // Update BB and BB layout.
916   Function.insertBasicBlocks(&IndCallBlock, std::move(NewBBs));
917   assert(Function.validateCFG());
918 
919   return MergeBlock;
920 }
921 
922 size_t IndirectCallPromotion::canPromoteCallsite(
923     const BinaryBasicBlock &BB, const MCInst &Inst,
924     const std::vector<Callsite> &Targets, uint64_t NumCalls) {
925   if (BB.getKnownExecutionCount() < opts::ExecutionCountThreshold)
926     return 0;
927 
928   const bool IsJumpTable = BB.getFunction()->getJumpTable(Inst);
929 
930   auto computeStats = [&](size_t N) {
931     for (size_t I = 0; I < N; ++I)
932       if (!IsJumpTable)
933         TotalNumFrequentCalls += Targets[I].Branches;
934       else
935         TotalNumFrequentJmps += Targets[I].Branches;
936   };
937 
938   // If we have no targets (or no calls), skip this callsite.
939   if (Targets.empty() || !NumCalls) {
940     if (opts::Verbosity >= 1) {
941       const auto InstIdx = &Inst - &(*BB.begin());
942       outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " @ "
943              << InstIdx << " in " << BB.getName() << ", calls = " << NumCalls
944              << ", targets empty or NumCalls == 0.\n";
945     }
946     return 0;
947   }
948 
949   size_t TopN = opts::IndirectCallPromotionTopN;
950   if (IsJumpTable) {
951     if (opts::IndirectCallPromotionJumpTablesTopN != 0)
952       TopN = opts::IndirectCallPromotionJumpTablesTopN;
953   } else if (opts::IndirectCallPromotionCallsTopN != 0) {
954     TopN = opts::IndirectCallPromotionCallsTopN;
955   }
956   const size_t TrialN = TopN ? std::min(TopN, Targets.size()) : Targets.size();
957 
958   if (opts::ICPTopCallsites > 0) {
959     BinaryContext &BC = BB.getFunction()->getBinaryContext();
960     if (!BC.MIB->hasAnnotation(Inst, "DoICP"))
961       return 0;
962   }
963 
964   // Pick the top N targets.
965   uint64_t TotalCallsTopN = 0;
966   uint64_t TotalMispredictsTopN = 0;
967   size_t N = 0;
968 
969   if (opts::IndirectCallPromotionUseMispredicts &&
970       (!IsJumpTable || opts::ICPJumpTablesByTarget)) {
971     // Count total number of mispredictions for (at most) the top N targets.
972     // We may choose a smaller N (TrialN vs. N) if the frequency threshold
973     // is exceeded by fewer targets.
974     double Threshold = double(opts::IndirectCallPromotionMispredictThreshold);
975     for (size_t I = 0; I < TrialN && Threshold > 0; ++I, ++N) {
976       Threshold -= (100.0 * Targets[I].Mispreds) / NumCalls;
977       TotalMispredictsTopN += Targets[I].Mispreds;
978     }
979     computeStats(N);
980 
981     // Compute the misprediction frequency of the top N call targets.  If this
982     // frequency is greater than the threshold, we should try ICP on this
983     // callsite.
984     const double TopNFrequency = (100.0 * TotalMispredictsTopN) / NumCalls;
985     if (TopNFrequency == 0 ||
986         TopNFrequency < opts::IndirectCallPromotionMispredictThreshold) {
987       if (opts::Verbosity >= 1) {
988         const auto InstIdx = &Inst - &(*BB.begin());
989         outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " @ "
990                << InstIdx << " in " << BB.getName() << ", calls = " << NumCalls
991                << ", top N mis. frequency " << format("%.1f", TopNFrequency)
992                << "% < " << opts::IndirectCallPromotionMispredictThreshold
993                << "%\n";
994       }
995       return 0;
996     }
997   } else {
998     size_t MaxTargets = 0;
999 
1000     // Count total number of calls for (at most) the top N targets.
1001     // We may choose a smaller N (TrialN vs. N) if the frequency threshold
1002     // is exceeded by fewer targets.
1003     const unsigned TotalThreshold = IsJumpTable
1004                                         ? opts::ICPJTTotalPercentThreshold
1005                                         : opts::ICPCallsTotalPercentThreshold;
1006     const unsigned RemainingThreshold =
1007         IsJumpTable ? opts::ICPJTRemainingPercentThreshold
1008                     : opts::ICPCallsRemainingPercentThreshold;
1009     uint64_t NumRemainingCalls = NumCalls;
1010     for (size_t I = 0; I < TrialN; ++I, ++MaxTargets) {
1011       if (100 * Targets[I].Branches < NumCalls * TotalThreshold)
1012         break;
1013       if (100 * Targets[I].Branches < NumRemainingCalls * RemainingThreshold)
1014         break;
1015       if (N + (Targets[I].JTIndices.empty() ? 1 : Targets[I].JTIndices.size()) >
1016           TrialN)
1017         break;
1018       TotalCallsTopN += Targets[I].Branches;
1019       TotalMispredictsTopN += Targets[I].Mispreds;
1020       NumRemainingCalls -= Targets[I].Branches;
1021       N += Targets[I].JTIndices.empty() ? 1 : Targets[I].JTIndices.size();
1022     }
1023     computeStats(MaxTargets);
1024 
1025     // Don't check misprediction frequency for jump tables -- we don't really
1026     // care as long as we are saving loads from the jump table.
1027     if (!IsJumpTable || opts::ICPJumpTablesByTarget) {
1028       // Compute the misprediction frequency of the top N call targets.  If
1029       // this frequency is less than the threshold, we should skip ICP at
1030       // this callsite.
1031       const double TopNMispredictFrequency =
1032           (100.0 * TotalMispredictsTopN) / NumCalls;
1033 
1034       if (TopNMispredictFrequency <
1035           opts::IndirectCallPromotionMispredictThreshold) {
1036         if (opts::Verbosity >= 1) {
1037           const auto InstIdx = &Inst - &(*BB.begin());
1038           outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " @ "
1039                  << InstIdx << " in " << BB.getName()
1040                  << ", calls = " << NumCalls << ", top N mispredict frequency "
1041                  << format("%.1f", TopNMispredictFrequency) << "% < "
1042                  << opts::IndirectCallPromotionMispredictThreshold << "%\n";
1043         }
1044         return 0;
1045       }
1046     }
1047   }
1048 
1049   // Filter functions that can have ICP applied (for debugging)
1050   if (!opts::ICPFuncsList.empty()) {
1051     for (std::string &Name : opts::ICPFuncsList)
1052       if (BB.getFunction()->hasName(Name))
1053         return N;
1054     return 0;
1055   }
1056 
1057   return N;
1058 }
1059 
1060 void IndirectCallPromotion::printCallsiteInfo(
1061     const BinaryBasicBlock &BB, const MCInst &Inst,
1062     const std::vector<Callsite> &Targets, const size_t N,
1063     uint64_t NumCalls) const {
1064   BinaryContext &BC = BB.getFunction()->getBinaryContext();
1065   const bool IsTailCall = BC.MIB->isTailCall(Inst);
1066   const bool IsJumpTable = BB.getFunction()->getJumpTable(Inst);
1067   const auto InstIdx = &Inst - &(*BB.begin());
1068 
1069   outs() << "BOLT-INFO: ICP candidate branch info: " << *BB.getFunction()
1070          << " @ " << InstIdx << " in " << BB.getName()
1071          << " -> calls = " << NumCalls
1072          << (IsTailCall ? " (tail)" : (IsJumpTable ? " (jump table)" : ""))
1073          << "\n";
1074   for (size_t I = 0; I < N; I++) {
1075     const double Frequency = 100.0 * Targets[I].Branches / NumCalls;
1076     const double MisFrequency = 100.0 * Targets[I].Mispreds / NumCalls;
1077     outs() << "BOLT-INFO:   ";
1078     if (Targets[I].To.Sym)
1079       outs() << Targets[I].To.Sym->getName();
1080     else
1081       outs() << Targets[I].To.Addr;
1082     outs() << ", calls = " << Targets[I].Branches
1083            << ", mispreds = " << Targets[I].Mispreds
1084            << ", taken freq = " << format("%.1f", Frequency) << "%"
1085            << ", mis. freq = " << format("%.1f", MisFrequency) << "%";
1086     bool First = true;
1087     for (uint64_t JTIndex : Targets[I].JTIndices) {
1088       outs() << (First ? ", indices = " : ", ") << JTIndex;
1089       First = false;
1090     }
1091     outs() << "\n";
1092   }
1093 
1094   LLVM_DEBUG({
1095     dbgs() << "BOLT-INFO: ICP original call instruction:";
1096     BC.printInstruction(dbgs(), Inst, Targets[0].From.Addr, nullptr, true);
1097   });
1098 }
1099 
1100 void IndirectCallPromotion::runOnFunctions(BinaryContext &BC) {
1101   if (opts::IndirectCallPromotion == ICP_NONE)
1102     return;
1103 
1104   auto &BFs = BC.getBinaryFunctions();
1105 
1106   const bool OptimizeCalls = (opts::IndirectCallPromotion == ICP_CALLS ||
1107                               opts::IndirectCallPromotion == ICP_ALL);
1108   const bool OptimizeJumpTables =
1109       (opts::IndirectCallPromotion == ICP_JUMP_TABLES ||
1110        opts::IndirectCallPromotion == ICP_ALL);
1111 
1112   std::unique_ptr<RegAnalysis> RA;
1113   std::unique_ptr<BinaryFunctionCallGraph> CG;
1114   if (OptimizeJumpTables) {
1115     CG.reset(new BinaryFunctionCallGraph(buildCallGraph(BC)));
1116     RA.reset(new RegAnalysis(BC, &BFs, &*CG));
1117   }
1118 
1119   // If icp-top-callsites is enabled, compute the total number of indirect
1120   // calls and then optimize the hottest callsites that contribute to that
1121   // total.
1122   SetVector<BinaryFunction *> Functions;
1123   if (opts::ICPTopCallsites == 0) {
1124     for (auto &KV : BFs)
1125       Functions.insert(&KV.second);
1126   } else {
1127     using IndirectCallsite = std::tuple<uint64_t, MCInst *, BinaryFunction *>;
1128     std::vector<IndirectCallsite> IndirectCalls;
1129     size_t TotalIndirectCalls = 0;
1130 
1131     // Find all the indirect callsites.
1132     for (auto &BFIt : BFs) {
1133       BinaryFunction &Function = BFIt.second;
1134 
1135       if (!Function.isSimple() || Function.isIgnored() ||
1136           !Function.hasProfile())
1137         continue;
1138 
1139       const bool HasLayout = !Function.layout_empty();
1140 
1141       for (BinaryBasicBlock &BB : Function) {
1142         if (HasLayout && Function.isSplit() && BB.isCold())
1143           continue;
1144 
1145         for (MCInst &Inst : BB) {
1146           const bool IsJumpTable = Function.getJumpTable(Inst);
1147           const bool HasIndirectCallProfile =
1148               BC.MIB->hasAnnotation(Inst, "CallProfile");
1149           const bool IsDirectCall =
1150               (BC.MIB->isCall(Inst) && BC.MIB->getTargetSymbol(Inst, 0));
1151 
1152           if (!IsDirectCall &&
1153               ((HasIndirectCallProfile && !IsJumpTable && OptimizeCalls) ||
1154                (IsJumpTable && OptimizeJumpTables))) {
1155             uint64_t NumCalls = 0;
1156             for (const Callsite &BInfo : getCallTargets(BB, Inst))
1157               NumCalls += BInfo.Branches;
1158             IndirectCalls.push_back(
1159                 std::make_tuple(NumCalls, &Inst, &Function));
1160             TotalIndirectCalls += NumCalls;
1161           }
1162         }
1163       }
1164     }
1165 
1166     // Sort callsites by execution count.
1167     std::sort(IndirectCalls.rbegin(), IndirectCalls.rend());
1168 
1169     // Find callsites that contribute to the top "opts::ICPTopCallsites"%
1170     // number of calls.
1171     const float TopPerc = opts::ICPTopCallsites / 100.0f;
1172     int64_t MaxCalls = TotalIndirectCalls * TopPerc;
1173     uint64_t LastFreq = std::numeric_limits<uint64_t>::max();
1174     size_t Num = 0;
1175     for (const IndirectCallsite &IC : IndirectCalls) {
1176       const uint64_t CurFreq = std::get<0>(IC);
1177       // Once we decide to stop, include at least all branches that share the
1178       // same frequency of the last one to avoid non-deterministic behavior
1179       // (e.g. turning on/off ICP depending on the order of functions)
1180       if (MaxCalls <= 0 && CurFreq != LastFreq)
1181         break;
1182       MaxCalls -= CurFreq;
1183       LastFreq = CurFreq;
1184       BC.MIB->addAnnotation(*std::get<1>(IC), "DoICP", true);
1185       Functions.insert(std::get<2>(IC));
1186       ++Num;
1187     }
1188     outs() << "BOLT-INFO: ICP Total indirect calls = " << TotalIndirectCalls
1189            << ", " << Num << " callsites cover " << opts::ICPTopCallsites
1190            << "% of all indirect calls\n";
1191   }
1192 
1193   for (BinaryFunction *FuncPtr : Functions) {
1194     BinaryFunction &Function = *FuncPtr;
1195 
1196     if (!Function.isSimple() || Function.isIgnored() || !Function.hasProfile())
1197       continue;
1198 
1199     const bool HasLayout = !Function.layout_empty();
1200 
1201     // Total number of indirect calls issued from the current Function.
1202     // (a fraction of TotalIndirectCalls)
1203     uint64_t FuncTotalIndirectCalls = 0;
1204     uint64_t FuncTotalIndirectJmps = 0;
1205 
1206     std::vector<BinaryBasicBlock *> BBs;
1207     for (BinaryBasicBlock &BB : Function) {
1208       // Skip indirect calls in cold blocks.
1209       if (!HasLayout || !Function.isSplit() || !BB.isCold())
1210         BBs.push_back(&BB);
1211     }
1212     if (BBs.empty())
1213       continue;
1214 
1215     DataflowInfoManager Info(Function, RA.get(), nullptr);
1216     while (!BBs.empty()) {
1217       BinaryBasicBlock *BB = BBs.back();
1218       BBs.pop_back();
1219 
1220       for (unsigned Idx = 0; Idx < BB->size(); ++Idx) {
1221         MCInst &Inst = BB->getInstructionAtIndex(Idx);
1222         const auto InstIdx = &Inst - &(*BB->begin());
1223         const bool IsTailCall = BC.MIB->isTailCall(Inst);
1224         const bool HasIndirectCallProfile =
1225             BC.MIB->hasAnnotation(Inst, "CallProfile");
1226         const bool IsJumpTable = Function.getJumpTable(Inst);
1227 
1228         if (BC.MIB->isCall(Inst))
1229           TotalCalls += BB->getKnownExecutionCount();
1230 
1231         if (IsJumpTable && !OptimizeJumpTables)
1232           continue;
1233 
1234         if (!IsJumpTable && (!HasIndirectCallProfile || !OptimizeCalls))
1235           continue;
1236 
1237         // Ignore direct calls.
1238         if (BC.MIB->isCall(Inst) && BC.MIB->getTargetSymbol(Inst, 0))
1239           continue;
1240 
1241         assert((BC.MIB->isCall(Inst) || BC.MIB->isIndirectBranch(Inst)) &&
1242                "expected a call or an indirect jump instruction");
1243 
1244         if (IsJumpTable)
1245           ++TotalJumpTableCallsites;
1246         else
1247           ++TotalIndirectCallsites;
1248 
1249         std::vector<Callsite> Targets = getCallTargets(*BB, Inst);
1250 
1251         // Compute the total number of calls from this particular callsite.
1252         uint64_t NumCalls = 0;
1253         for (const Callsite &BInfo : Targets)
1254           NumCalls += BInfo.Branches;
1255         if (!IsJumpTable)
1256           FuncTotalIndirectCalls += NumCalls;
1257         else
1258           FuncTotalIndirectJmps += NumCalls;
1259 
1260         // If FLAGS regs is alive after this jmp site, do not try
1261         // promoting because we will clobber FLAGS.
1262         if (IsJumpTable) {
1263           ErrorOr<const BitVector &> State =
1264               Info.getLivenessAnalysis().getStateBefore(Inst);
1265           if (!State || (State && (*State)[BC.MIB->getFlagsReg()])) {
1266             if (opts::Verbosity >= 1)
1267               outs() << "BOLT-INFO: ICP failed in " << Function << " @ "
1268                      << InstIdx << " in " << BB->getName()
1269                      << ", calls = " << NumCalls
1270                      << (State ? ", cannot clobber flags reg.\n"
1271                                : ", no liveness data available.\n");
1272             continue;
1273           }
1274         }
1275 
1276         // Should this callsite be optimized?  Return the number of targets
1277         // to use when promoting this call.  A value of zero means to skip
1278         // this callsite.
1279         size_t N = canPromoteCallsite(*BB, Inst, Targets, NumCalls);
1280 
1281         // If it is a jump table and it failed to meet our initial threshold,
1282         // proceed to findCallTargetSymbols -- it may reevaluate N if
1283         // memory profile is present
1284         if (!N && !IsJumpTable)
1285           continue;
1286 
1287         if (opts::Verbosity >= 1)
1288           printCallsiteInfo(*BB, Inst, Targets, N, NumCalls);
1289 
1290         // Find MCSymbols or absolute addresses for each call target.
1291         MCInst *TargetFetchInst = nullptr;
1292         const SymTargetsType SymTargets =
1293             findCallTargetSymbols(Targets, N, *BB, Inst, TargetFetchInst);
1294 
1295         // findCallTargetSymbols may have changed N if mem profile is available
1296         // for jump tables
1297         if (!N)
1298           continue;
1299 
1300         LLVM_DEBUG(printDecision(dbgs(), Targets, N));
1301 
1302         // If we can't resolve any of the target symbols, punt on this callsite.
1303         // TODO: can this ever happen?
1304         if (SymTargets.size() < N) {
1305           const size_t LastTarget = SymTargets.size();
1306           if (opts::Verbosity >= 1)
1307             outs() << "BOLT-INFO: ICP failed in " << Function << " @ "
1308                    << InstIdx << " in " << BB->getName()
1309                    << ", calls = " << NumCalls
1310                    << ", ICP failed to find target symbol for "
1311                    << Targets[LastTarget].To.Sym->getName() << "\n";
1312           continue;
1313         }
1314 
1315         MethodInfoType MethodInfo;
1316 
1317         if (!IsJumpTable) {
1318           MethodInfo = maybeGetVtableSyms(*BB, Inst, SymTargets);
1319           TotalMethodLoadsEliminated += MethodInfo.first.empty() ? 0 : 1;
1320           LLVM_DEBUG(dbgs()
1321                      << "BOLT-INFO: ICP "
1322                      << (!MethodInfo.first.empty() ? "found" : "did not find")
1323                      << " vtables for all methods.\n");
1324         } else if (TargetFetchInst) {
1325           ++TotalIndexBasedJumps;
1326           MethodInfo.second.push_back(TargetFetchInst);
1327         }
1328 
1329         // Generate new promoted call code for this callsite.
1330         MCPlusBuilder::BlocksVectorTy ICPcode =
1331             (IsJumpTable && !opts::ICPJumpTablesByTarget)
1332                 ? BC.MIB->jumpTablePromotion(Inst, SymTargets,
1333                                              MethodInfo.second, BC.Ctx.get())
1334                 : BC.MIB->indirectCallPromotion(
1335                       Inst, SymTargets, MethodInfo.first, MethodInfo.second,
1336                       opts::ICPOldCodeSequence, BC.Ctx.get());
1337 
1338         if (ICPcode.empty()) {
1339           if (opts::Verbosity >= 1)
1340             outs() << "BOLT-INFO: ICP failed in " << Function << " @ "
1341                    << InstIdx << " in " << BB->getName()
1342                    << ", calls = " << NumCalls
1343                    << ", unable to generate promoted call code.\n";
1344           continue;
1345         }
1346 
1347         LLVM_DEBUG({
1348           uint64_t Offset = Targets[0].From.Addr;
1349           dbgs() << "BOLT-INFO: ICP indirect call code:\n";
1350           for (const auto &entry : ICPcode) {
1351             const MCSymbol *const &Sym = entry.first;
1352             const InstructionListType &Insts = entry.second;
1353             if (Sym)
1354               dbgs() << Sym->getName() << ":\n";
1355             Offset = BC.printInstructions(dbgs(), Insts.begin(), Insts.end(),
1356                                           Offset);
1357           }
1358           dbgs() << "---------------------------------------------------\n";
1359         });
1360 
1361         // Rewrite the CFG with the newly generated ICP code.
1362         std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs =
1363             rewriteCall(*BB, Inst, std::move(ICPcode), MethodInfo.second);
1364 
1365         // Fix the CFG after inserting the new basic blocks.
1366         BinaryBasicBlock *MergeBlock =
1367             fixCFG(*BB, IsTailCall, IsJumpTable, std::move(NewBBs), Targets);
1368 
1369         // Since the tail of the original block was split off and it may contain
1370         // additional indirect calls, we must add the merge block to the set of
1371         // blocks to process.
1372         if (MergeBlock)
1373           BBs.push_back(MergeBlock);
1374 
1375         if (opts::Verbosity >= 1)
1376           outs() << "BOLT-INFO: ICP succeeded in " << Function << " @ "
1377                  << InstIdx << " in " << BB->getName()
1378                  << " -> calls = " << NumCalls << "\n";
1379 
1380         if (IsJumpTable)
1381           ++TotalOptimizedJumpTableCallsites;
1382         else
1383           ++TotalOptimizedIndirectCallsites;
1384 
1385         Modified.insert(&Function);
1386       }
1387     }
1388     TotalIndirectCalls += FuncTotalIndirectCalls;
1389     TotalIndirectJmps += FuncTotalIndirectJmps;
1390   }
1391 
1392   outs() << "BOLT-INFO: ICP total indirect callsites with profile = "
1393          << TotalIndirectCallsites << "\n"
1394          << "BOLT-INFO: ICP total jump table callsites = "
1395          << TotalJumpTableCallsites << "\n"
1396          << "BOLT-INFO: ICP total number of calls = " << TotalCalls << "\n"
1397          << "BOLT-INFO: ICP percentage of calls that are indirect = "
1398          << format("%.1f", (100.0 * TotalIndirectCalls) / TotalCalls) << "%\n"
1399          << "BOLT-INFO: ICP percentage of indirect calls that can be "
1400             "optimized = "
1401          << format("%.1f", (100.0 * TotalNumFrequentCalls) /
1402                                std::max<size_t>(TotalIndirectCalls, 1))
1403          << "%\n"
1404          << "BOLT-INFO: ICP percentage of indirect callsites that are "
1405             "optimized = "
1406          << format("%.1f", (100.0 * TotalOptimizedIndirectCallsites) /
1407                                std::max<uint64_t>(TotalIndirectCallsites, 1))
1408          << "%\n"
1409          << "BOLT-INFO: ICP number of method load elimination candidates = "
1410          << TotalMethodLoadEliminationCandidates << "\n"
1411          << "BOLT-INFO: ICP percentage of method calls candidates that have "
1412             "loads eliminated = "
1413          << format("%.1f", (100.0 * TotalMethodLoadsEliminated) /
1414                                std::max<uint64_t>(
1415                                    TotalMethodLoadEliminationCandidates, 1))
1416          << "%\n"
1417          << "BOLT-INFO: ICP percentage of indirect branches that are "
1418             "optimized = "
1419          << format("%.1f", (100.0 * TotalNumFrequentJmps) /
1420                                std::max<uint64_t>(TotalIndirectJmps, 1))
1421          << "%\n"
1422          << "BOLT-INFO: ICP percentage of jump table callsites that are "
1423          << "optimized = "
1424          << format("%.1f", (100.0 * TotalOptimizedJumpTableCallsites) /
1425                                std::max<uint64_t>(TotalJumpTableCallsites, 1))
1426          << "%\n"
1427          << "BOLT-INFO: ICP number of jump table callsites that can use hot "
1428          << "indices = " << TotalIndexBasedCandidates << "\n"
1429          << "BOLT-INFO: ICP percentage of jump table callsites that use hot "
1430             "indices = "
1431          << format("%.1f", (100.0 * TotalIndexBasedJumps) /
1432                                std::max<uint64_t>(TotalIndexBasedCandidates, 1))
1433          << "%\n";
1434 
1435   (void)verifyProfile;
1436 #ifndef NDEBUG
1437   verifyProfile(BFs);
1438 #endif
1439 }
1440 
1441 } // namespace bolt
1442 } // namespace llvm
1443