xref: /llvm-project/bolt/lib/Passes/BinaryPasses.cpp (revision 6b9bca8faaa759c56fdd6e8697f9be38d201bd71)
1 //===- bolt/Passes/BinaryPasses.cpp - Binary-level passes -----------------===//
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 multiple passes for binary optimization and analysis.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/BinaryPasses.h"
14 #include "bolt/Core/FunctionLayout.h"
15 #include "bolt/Core/ParallelUtilities.h"
16 #include "bolt/Passes/ReorderAlgorithm.h"
17 #include "bolt/Passes/ReorderFunctions.h"
18 #include "llvm/Support/CommandLine.h"
19 #include <atomic>
20 #include <mutex>
21 #include <numeric>
22 #include <vector>
23 
24 #define DEBUG_TYPE "bolt-opts"
25 
26 using namespace llvm;
27 using namespace bolt;
28 
29 static const char *dynoStatsOptName(const bolt::DynoStats::Category C) {
30   assert(C > bolt::DynoStats::FIRST_DYNO_STAT &&
31          C < DynoStats::LAST_DYNO_STAT && "Unexpected dyno stat category.");
32 
33   static std::string OptNames[bolt::DynoStats::LAST_DYNO_STAT + 1];
34 
35   OptNames[C] = bolt::DynoStats::Description(C);
36 
37   std::replace(OptNames[C].begin(), OptNames[C].end(), ' ', '-');
38 
39   return OptNames[C].c_str();
40 }
41 
42 namespace opts {
43 
44 extern cl::OptionCategory BoltCategory;
45 extern cl::OptionCategory BoltOptCategory;
46 
47 extern cl::opt<bolt::MacroFusionType> AlignMacroOpFusion;
48 extern cl::opt<unsigned> Verbosity;
49 extern cl::opt<bool> EnableBAT;
50 extern cl::opt<unsigned> ExecutionCountThreshold;
51 extern cl::opt<bool> UpdateDebugSections;
52 extern cl::opt<bolt::ReorderFunctions::ReorderType> ReorderFunctions;
53 
54 enum DynoStatsSortOrder : char {
55   Ascending,
56   Descending
57 };
58 
59 static cl::opt<DynoStatsSortOrder> DynoStatsSortOrderOpt(
60     "print-sorted-by-order",
61     cl::desc("use ascending or descending order when printing functions "
62              "ordered by dyno stats"),
63     cl::init(DynoStatsSortOrder::Descending), cl::cat(BoltOptCategory));
64 
65 cl::list<std::string>
66 HotTextMoveSections("hot-text-move-sections",
67   cl::desc("list of sections containing functions used for hugifying hot text. "
68            "BOLT makes sure these functions are not placed on the same page as "
69            "the hot text. (default=\'.stub,.mover\')."),
70   cl::value_desc("sec1,sec2,sec3,..."),
71   cl::CommaSeparated,
72   cl::ZeroOrMore,
73   cl::cat(BoltCategory));
74 
75 bool isHotTextMover(const BinaryFunction &Function) {
76   for (std::string &SectionName : opts::HotTextMoveSections) {
77     if (Function.getOriginSectionName() &&
78         *Function.getOriginSectionName() == SectionName)
79       return true;
80   }
81 
82   return false;
83 }
84 
85 static cl::opt<bool> MinBranchClusters(
86     "min-branch-clusters",
87     cl::desc("use a modified clustering algorithm geared towards minimizing "
88              "branches"),
89     cl::Hidden, cl::cat(BoltOptCategory));
90 
91 static cl::list<Peepholes::PeepholeOpts> Peepholes(
92     "peepholes", cl::CommaSeparated, cl::desc("enable peephole optimizations"),
93     cl::value_desc("opt1,opt2,opt3,..."),
94     cl::values(clEnumValN(Peepholes::PEEP_NONE, "none", "disable peepholes"),
95                clEnumValN(Peepholes::PEEP_DOUBLE_JUMPS, "double-jumps",
96                           "remove double jumps when able"),
97                clEnumValN(Peepholes::PEEP_TAILCALL_TRAPS, "tailcall-traps",
98                           "insert tail call traps"),
99                clEnumValN(Peepholes::PEEP_USELESS_BRANCHES, "useless-branches",
100                           "remove useless conditional branches"),
101                clEnumValN(Peepholes::PEEP_ALL, "all",
102                           "enable all peephole optimizations")),
103     cl::ZeroOrMore, cl::cat(BoltOptCategory));
104 
105 static cl::opt<unsigned>
106     PrintFuncStat("print-function-statistics",
107                   cl::desc("print statistics about basic block ordering"),
108                   cl::init(0), cl::cat(BoltOptCategory));
109 
110 static cl::opt<bool> PrintLargeFunctions(
111     "print-large-functions",
112     cl::desc("print functions that could not be overwritten due to excessive "
113              "size"),
114     cl::init(false), cl::cat(BoltOptCategory));
115 
116 static cl::list<bolt::DynoStats::Category>
117     PrintSortedBy("print-sorted-by", cl::CommaSeparated,
118                   cl::desc("print functions sorted by order of dyno stats"),
119                   cl::value_desc("key1,key2,key3,..."),
120                   cl::values(
121 #define D(name, description, ...)                                              \
122   clEnumValN(bolt::DynoStats::name, dynoStatsOptName(bolt::DynoStats::name),   \
123              description),
124                       REAL_DYNO_STATS
125 #undef D
126                           clEnumValN(bolt::DynoStats::LAST_DYNO_STAT, "all",
127                                      "sorted by all names")),
128                   cl::ZeroOrMore, cl::cat(BoltOptCategory));
129 
130 static cl::opt<bool>
131     PrintUnknown("print-unknown",
132                  cl::desc("print names of functions with unknown control flow"),
133                  cl::cat(BoltCategory), cl::Hidden);
134 
135 static cl::opt<bool>
136     PrintUnknownCFG("print-unknown-cfg",
137                     cl::desc("dump CFG of functions with unknown control flow"),
138                     cl::cat(BoltCategory), cl::ReallyHidden);
139 
140 // Please MSVC19 with a forward declaration: otherwise it reports an error about
141 // an undeclared variable inside a callback.
142 extern cl::opt<bolt::ReorderBasicBlocks::LayoutType> ReorderBlocks;
143 cl::opt<bolt::ReorderBasicBlocks::LayoutType> ReorderBlocks(
144     "reorder-blocks", cl::desc("change layout of basic blocks in a function"),
145     cl::init(bolt::ReorderBasicBlocks::LT_NONE),
146     cl::values(
147         clEnumValN(bolt::ReorderBasicBlocks::LT_NONE, "none",
148                    "do not reorder basic blocks"),
149         clEnumValN(bolt::ReorderBasicBlocks::LT_REVERSE, "reverse",
150                    "layout blocks in reverse order"),
151         clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE, "normal",
152                    "perform optimal layout based on profile"),
153         clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_BRANCH,
154                    "branch-predictor",
155                    "perform optimal layout prioritizing branch "
156                    "predictions"),
157         clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_CACHE, "cache",
158                    "perform optimal layout prioritizing I-cache "
159                    "behavior"),
160         clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_CACHE_PLUS, "cache+",
161                    "perform layout optimizing I-cache behavior"),
162         clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_EXT_TSP, "ext-tsp",
163                    "perform layout optimizing I-cache behavior"),
164         clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_SHUFFLE,
165                    "cluster-shuffle", "perform random layout of clusters")),
166     cl::ZeroOrMore, cl::cat(BoltOptCategory),
167     cl::callback([](const bolt::ReorderBasicBlocks::LayoutType &option) {
168       if (option == bolt::ReorderBasicBlocks::LT_OPTIMIZE_CACHE_PLUS) {
169         errs() << "BOLT-WARNING: '-reorder-blocks=cache+' is deprecated, please"
170                << " use '-reorder-blocks=ext-tsp' instead\n";
171         ReorderBlocks = bolt::ReorderBasicBlocks::LT_OPTIMIZE_EXT_TSP;
172       }
173     }));
174 
175 static cl::opt<unsigned> ReportBadLayout(
176     "report-bad-layout",
177     cl::desc("print top <uint> functions with suboptimal code layout on input"),
178     cl::init(0), cl::Hidden, cl::cat(BoltOptCategory));
179 
180 static cl::opt<bool>
181     ReportStaleFuncs("report-stale",
182                      cl::desc("print the list of functions with stale profile"),
183                      cl::Hidden, cl::cat(BoltOptCategory));
184 
185 enum SctcModes : char {
186   SctcAlways,
187   SctcPreserveDirection,
188   SctcHeuristic
189 };
190 
191 static cl::opt<SctcModes>
192 SctcMode("sctc-mode",
193   cl::desc("mode for simplify conditional tail calls"),
194   cl::init(SctcAlways),
195   cl::values(clEnumValN(SctcAlways, "always", "always perform sctc"),
196     clEnumValN(SctcPreserveDirection,
197       "preserve",
198       "only perform sctc when branch direction is "
199       "preserved"),
200     clEnumValN(SctcHeuristic,
201       "heuristic",
202       "use branch prediction data to control sctc")),
203   cl::ZeroOrMore,
204   cl::cat(BoltOptCategory));
205 
206 static cl::opt<unsigned>
207 StaleThreshold("stale-threshold",
208     cl::desc(
209       "maximum percentage of stale functions to tolerate (default: 100)"),
210     cl::init(100),
211     cl::Hidden,
212     cl::cat(BoltOptCategory));
213 
214 static cl::opt<unsigned> TSPThreshold(
215     "tsp-threshold",
216     cl::desc(
217         "maximum number of hot basic blocks in a function for which to use "
218         "a precise TSP solution while re-ordering basic blocks"),
219     cl::init(10), cl::Hidden, cl::cat(BoltOptCategory));
220 
221 static cl::opt<unsigned> TopCalledLimit(
222     "top-called-limit",
223     cl::desc("maximum number of functions to print in top called "
224              "functions section"),
225     cl::init(100), cl::Hidden, cl::cat(BoltCategory));
226 
227 } // namespace opts
228 
229 namespace llvm {
230 namespace bolt {
231 
232 bool BinaryFunctionPass::shouldOptimize(const BinaryFunction &BF) const {
233   return BF.isSimple() && BF.getState() == BinaryFunction::State::CFG &&
234          !BF.isIgnored();
235 }
236 
237 bool BinaryFunctionPass::shouldPrint(const BinaryFunction &BF) const {
238   return BF.isSimple() && !BF.isIgnored();
239 }
240 
241 void NormalizeCFG::runOnFunction(BinaryFunction &BF) {
242   uint64_t NumRemoved = 0;
243   uint64_t NumDuplicateEdges = 0;
244   uint64_t NeedsFixBranches = 0;
245   for (BinaryBasicBlock &BB : BF) {
246     if (!BB.empty())
247       continue;
248 
249     if (BB.isEntryPoint() || BB.isLandingPad())
250       continue;
251 
252     // Handle a dangling empty block.
253     if (BB.succ_size() == 0) {
254       // If an empty dangling basic block has a predecessor, it could be a
255       // result of codegen for __builtin_unreachable. In such case, do not
256       // remove the block.
257       if (BB.pred_size() == 0) {
258         BB.markValid(false);
259         ++NumRemoved;
260       }
261       continue;
262     }
263 
264     // The block should have just one successor.
265     BinaryBasicBlock *Successor = BB.getSuccessor();
266     assert(Successor && "invalid CFG encountered");
267 
268     // Redirect all predecessors to the successor block.
269     while (!BB.pred_empty()) {
270       BinaryBasicBlock *Predecessor = *BB.pred_begin();
271       if (Predecessor->hasJumpTable())
272         break;
273 
274       if (Predecessor == Successor)
275         break;
276 
277       BinaryBasicBlock::BinaryBranchInfo &BI = Predecessor->getBranchInfo(BB);
278       Predecessor->replaceSuccessor(&BB, Successor, BI.Count,
279                                     BI.MispredictedCount);
280       // We need to fix branches even if we failed to replace all successors
281       // and remove the block.
282       NeedsFixBranches = true;
283     }
284 
285     if (BB.pred_empty()) {
286       BB.removeAllSuccessors();
287       BB.markValid(false);
288       ++NumRemoved;
289     }
290   }
291 
292   if (NumRemoved)
293     BF.eraseInvalidBBs();
294 
295   // Check for duplicate successors. Do it after the empty block elimination as
296   // we can get more duplicate successors.
297   for (BinaryBasicBlock &BB : BF)
298     if (!BB.hasJumpTable() && BB.succ_size() == 2 &&
299         BB.getConditionalSuccessor(false) == BB.getConditionalSuccessor(true))
300       ++NumDuplicateEdges;
301 
302   // fixBranches() will get rid of duplicate edges and update jump instructions.
303   if (NumDuplicateEdges || NeedsFixBranches)
304     BF.fixBranches();
305 
306   NumDuplicateEdgesMerged += NumDuplicateEdges;
307   NumBlocksRemoved += NumRemoved;
308 }
309 
310 Error NormalizeCFG::runOnFunctions(BinaryContext &BC) {
311   ParallelUtilities::runOnEachFunction(
312       BC, ParallelUtilities::SchedulingPolicy::SP_BB_LINEAR,
313       [&](BinaryFunction &BF) { runOnFunction(BF); },
314       [&](const BinaryFunction &BF) { return !shouldOptimize(BF); },
315       "NormalizeCFG");
316   if (NumBlocksRemoved)
317     BC.outs() << "BOLT-INFO: removed " << NumBlocksRemoved << " empty block"
318               << (NumBlocksRemoved == 1 ? "" : "s") << '\n';
319   if (NumDuplicateEdgesMerged)
320     BC.outs() << "BOLT-INFO: merged " << NumDuplicateEdgesMerged
321               << " duplicate CFG edge"
322               << (NumDuplicateEdgesMerged == 1 ? "" : "s") << '\n';
323   return Error::success();
324 }
325 
326 void EliminateUnreachableBlocks::runOnFunction(BinaryFunction &Function) {
327   BinaryContext &BC = Function.getBinaryContext();
328   unsigned Count;
329   uint64_t Bytes;
330   Function.markUnreachableBlocks();
331   LLVM_DEBUG({
332     for (BinaryBasicBlock &BB : Function) {
333       if (!BB.isValid()) {
334         dbgs() << "BOLT-INFO: UCE found unreachable block " << BB.getName()
335                << " in function " << Function << "\n";
336         Function.dump();
337       }
338     }
339   });
340   BinaryContext::IndependentCodeEmitter Emitter =
341       BC.createIndependentMCCodeEmitter();
342   std::tie(Count, Bytes) = Function.eraseInvalidBBs(Emitter.MCE.get());
343   DeletedBlocks += Count;
344   DeletedBytes += Bytes;
345   if (Count) {
346     auto L = BC.scopeLock();
347     Modified.insert(&Function);
348     if (opts::Verbosity > 0)
349       BC.outs() << "BOLT-INFO: removed " << Count
350                 << " dead basic block(s) accounting for " << Bytes
351                 << " bytes in function " << Function << '\n';
352   }
353 }
354 
355 Error EliminateUnreachableBlocks::runOnFunctions(BinaryContext &BC) {
356   ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) {
357     runOnFunction(BF);
358   };
359 
360   ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
361     return !shouldOptimize(BF) || BF.getLayout().block_empty();
362   };
363 
364   ParallelUtilities::runOnEachFunction(
365       BC, ParallelUtilities::SchedulingPolicy::SP_CONSTANT, WorkFun,
366       SkipPredicate, "elimininate-unreachable");
367 
368   if (DeletedBlocks)
369     BC.outs() << "BOLT-INFO: UCE removed " << DeletedBlocks << " blocks and "
370               << DeletedBytes << " bytes of code\n";
371   return Error::success();
372 }
373 
374 bool ReorderBasicBlocks::shouldPrint(const BinaryFunction &BF) const {
375   return (BinaryFunctionPass::shouldPrint(BF) &&
376           opts::ReorderBlocks != ReorderBasicBlocks::LT_NONE);
377 }
378 
379 bool ReorderBasicBlocks::shouldOptimize(const BinaryFunction &BF) const {
380   // Apply execution count threshold
381   if (BF.getKnownExecutionCount() < opts::ExecutionCountThreshold)
382     return false;
383 
384   return BinaryFunctionPass::shouldOptimize(BF);
385 }
386 
387 Error ReorderBasicBlocks::runOnFunctions(BinaryContext &BC) {
388   if (opts::ReorderBlocks == ReorderBasicBlocks::LT_NONE)
389     return Error::success();
390 
391   std::atomic_uint64_t ModifiedFuncCount(0);
392   std::mutex FunctionEditDistanceMutex;
393   DenseMap<const BinaryFunction *, uint64_t> FunctionEditDistance;
394 
395   ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) {
396     SmallVector<const BinaryBasicBlock *, 0> OldBlockOrder;
397     if (opts::PrintFuncStat > 0)
398       llvm::copy(BF.getLayout().blocks(), std::back_inserter(OldBlockOrder));
399 
400     const bool LayoutChanged =
401         modifyFunctionLayout(BF, opts::ReorderBlocks, opts::MinBranchClusters);
402     if (LayoutChanged) {
403       ModifiedFuncCount.fetch_add(1, std::memory_order_relaxed);
404       if (opts::PrintFuncStat > 0) {
405         const uint64_t Distance = BF.getLayout().getEditDistance(OldBlockOrder);
406         std::lock_guard<std::mutex> Lock(FunctionEditDistanceMutex);
407         FunctionEditDistance[&BF] = Distance;
408       }
409     }
410   };
411 
412   ParallelUtilities::PredicateTy SkipFunc = [&](const BinaryFunction &BF) {
413     return !shouldOptimize(BF);
414   };
415 
416   ParallelUtilities::runOnEachFunction(
417       BC, ParallelUtilities::SchedulingPolicy::SP_BB_LINEAR, WorkFun, SkipFunc,
418       "ReorderBasicBlocks");
419   const size_t NumAllProfiledFunctions =
420       BC.NumProfiledFuncs + BC.NumStaleProfileFuncs;
421 
422   BC.outs() << "BOLT-INFO: basic block reordering modified layout of "
423             << format(
424                    "%zu functions (%.2lf%% of profiled, %.2lf%% of total)\n",
425                    ModifiedFuncCount.load(std::memory_order_relaxed),
426                    100.0 * ModifiedFuncCount.load(std::memory_order_relaxed) /
427                        NumAllProfiledFunctions,
428                    100.0 * ModifiedFuncCount.load(std::memory_order_relaxed) /
429                        BC.getBinaryFunctions().size());
430 
431   if (opts::PrintFuncStat > 0) {
432     raw_ostream &OS = BC.outs();
433     // Copy all the values into vector in order to sort them
434     std::map<uint64_t, BinaryFunction &> ScoreMap;
435     auto &BFs = BC.getBinaryFunctions();
436     for (auto It = BFs.begin(); It != BFs.end(); ++It)
437       ScoreMap.insert(std::pair<uint64_t, BinaryFunction &>(
438           It->second.getFunctionScore(), It->second));
439 
440     OS << "\nBOLT-INFO: Printing Function Statistics:\n\n";
441     OS << "           There are " << BFs.size() << " functions in total. \n";
442     OS << "           Number of functions being modified: "
443        << ModifiedFuncCount.load(std::memory_order_relaxed) << "\n";
444     OS << "           User asks for detailed information on top "
445        << opts::PrintFuncStat << " functions. (Ranked by function score)"
446        << "\n\n";
447     uint64_t I = 0;
448     for (std::map<uint64_t, BinaryFunction &>::reverse_iterator Rit =
449              ScoreMap.rbegin();
450          Rit != ScoreMap.rend() && I < opts::PrintFuncStat; ++Rit, ++I) {
451       BinaryFunction &Function = Rit->second;
452 
453       OS << "           Information for function of top: " << (I + 1) << ": \n";
454       OS << "             Function Score is: " << Function.getFunctionScore()
455          << "\n";
456       OS << "             There are " << Function.size()
457          << " number of blocks in this function.\n";
458       OS << "             There are " << Function.getInstructionCount()
459          << " number of instructions in this function.\n";
460       OS << "             The edit distance for this function is: "
461          << FunctionEditDistance.lookup(&Function) << "\n\n";
462     }
463   }
464   return Error::success();
465 }
466 
467 bool ReorderBasicBlocks::modifyFunctionLayout(BinaryFunction &BF,
468                                               LayoutType Type,
469                                               bool MinBranchClusters) const {
470   if (BF.size() == 0 || Type == LT_NONE)
471     return false;
472 
473   BinaryFunction::BasicBlockOrderType NewLayout;
474   std::unique_ptr<ReorderAlgorithm> Algo;
475 
476   // Cannot do optimal layout without profile.
477   if (Type != LT_REVERSE && !BF.hasValidProfile())
478     return false;
479 
480   if (Type == LT_REVERSE) {
481     Algo.reset(new ReverseReorderAlgorithm());
482   } else if (BF.size() <= opts::TSPThreshold && Type != LT_OPTIMIZE_SHUFFLE) {
483     // Work on optimal solution if problem is small enough
484     LLVM_DEBUG(dbgs() << "finding optimal block layout for " << BF << "\n");
485     Algo.reset(new TSPReorderAlgorithm());
486   } else {
487     LLVM_DEBUG(dbgs() << "running block layout heuristics on " << BF << "\n");
488 
489     std::unique_ptr<ClusterAlgorithm> CAlgo;
490     if (MinBranchClusters)
491       CAlgo.reset(new MinBranchGreedyClusterAlgorithm());
492     else
493       CAlgo.reset(new PHGreedyClusterAlgorithm());
494 
495     switch (Type) {
496     case LT_OPTIMIZE:
497       Algo.reset(new OptimizeReorderAlgorithm(std::move(CAlgo)));
498       break;
499 
500     case LT_OPTIMIZE_BRANCH:
501       Algo.reset(new OptimizeBranchReorderAlgorithm(std::move(CAlgo)));
502       break;
503 
504     case LT_OPTIMIZE_CACHE:
505       Algo.reset(new OptimizeCacheReorderAlgorithm(std::move(CAlgo)));
506       break;
507 
508     case LT_OPTIMIZE_EXT_TSP:
509       Algo.reset(new ExtTSPReorderAlgorithm());
510       break;
511 
512     case LT_OPTIMIZE_SHUFFLE:
513       Algo.reset(new RandomClusterReorderAlgorithm(std::move(CAlgo)));
514       break;
515 
516     default:
517       llvm_unreachable("unexpected layout type");
518     }
519   }
520 
521   Algo->reorderBasicBlocks(BF, NewLayout);
522 
523   return BF.getLayout().update(NewLayout);
524 }
525 
526 Error FixupBranches::runOnFunctions(BinaryContext &BC) {
527   for (auto &It : BC.getBinaryFunctions()) {
528     BinaryFunction &Function = It.second;
529     if (!BC.shouldEmit(Function) || !Function.isSimple())
530       continue;
531 
532     Function.fixBranches();
533   }
534   return Error::success();
535 }
536 
537 Error FinalizeFunctions::runOnFunctions(BinaryContext &BC) {
538   std::atomic<bool> HasFatal{false};
539   ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) {
540     if (!BF.finalizeCFIState()) {
541       if (BC.HasRelocations) {
542         BC.errs() << "BOLT-ERROR: unable to fix CFI state for function " << BF
543                   << ". Exiting.\n";
544         HasFatal = true;
545         return;
546       }
547       BF.setSimple(false);
548       return;
549     }
550 
551     BF.setFinalized();
552 
553     // Update exception handling information.
554     BF.updateEHRanges();
555   };
556 
557   ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
558     return !BC.shouldEmit(BF);
559   };
560 
561   ParallelUtilities::runOnEachFunction(
562       BC, ParallelUtilities::SchedulingPolicy::SP_CONSTANT, WorkFun,
563       SkipPredicate, "FinalizeFunctions");
564   if (HasFatal)
565     return createFatalBOLTError("finalize CFI state failure");
566   return Error::success();
567 }
568 
569 Error CheckLargeFunctions::runOnFunctions(BinaryContext &BC) {
570   if (BC.HasRelocations)
571     return Error::success();
572 
573   // If the function wouldn't fit, mark it as non-simple. Otherwise, we may emit
574   // incorrect meta data.
575   ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) {
576     uint64_t HotSize, ColdSize;
577     std::tie(HotSize, ColdSize) =
578         BC.calculateEmittedSize(BF, /*FixBranches=*/false);
579     if (HotSize > BF.getMaxSize()) {
580       if (opts::PrintLargeFunctions)
581         BC.outs() << "BOLT-INFO: " << BF << " size exceeds allocated space by "
582                   << (HotSize - BF.getMaxSize()) << " bytes\n";
583       BF.setSimple(false);
584     }
585   };
586 
587   ParallelUtilities::PredicateTy SkipFunc = [&](const BinaryFunction &BF) {
588     return !shouldOptimize(BF);
589   };
590 
591   ParallelUtilities::runOnEachFunction(
592       BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun,
593       SkipFunc, "CheckLargeFunctions");
594 
595   return Error::success();
596 }
597 
598 bool CheckLargeFunctions::shouldOptimize(const BinaryFunction &BF) const {
599   // Unlike other passes, allow functions in non-CFG state.
600   return BF.isSimple() && !BF.isIgnored();
601 }
602 
603 Error LowerAnnotations::runOnFunctions(BinaryContext &BC) {
604   // Convert GnuArgsSize annotations into CFIs.
605   for (BinaryFunction *BF : BC.getAllBinaryFunctions()) {
606     for (FunctionFragment &FF : BF->getLayout().fragments()) {
607       // Reset at the start of the new fragment.
608       int64_t CurrentGnuArgsSize = 0;
609 
610       for (BinaryBasicBlock *const BB : FF) {
611         for (auto II = BB->begin(); II != BB->end(); ++II) {
612           if (!BF->usesGnuArgsSize() || !BC.MIB->isInvoke(*II))
613             continue;
614 
615           const int64_t NewGnuArgsSize = BC.MIB->getGnuArgsSize(*II);
616           assert(NewGnuArgsSize >= 0 && "Expected non-negative GNU_args_size.");
617           if (NewGnuArgsSize == CurrentGnuArgsSize)
618             continue;
619 
620           auto InsertII = BF->addCFIInstruction(
621               BB, II,
622               MCCFIInstruction::createGnuArgsSize(nullptr, NewGnuArgsSize));
623           CurrentGnuArgsSize = NewGnuArgsSize;
624           II = std::next(InsertII);
625         }
626       }
627     }
628   }
629   return Error::success();
630 }
631 
632 // Check for dirty state in MCSymbol objects that might be a consequence
633 // of running calculateEmittedSize() in parallel, during split functions
634 // pass. If an inconsistent state is found (symbol already registered or
635 // already defined), clean it.
636 Error CleanMCState::runOnFunctions(BinaryContext &BC) {
637   MCContext &Ctx = *BC.Ctx;
638   for (const auto &SymMapEntry : Ctx.getSymbols()) {
639     const MCSymbol *S = SymMapEntry.second;
640     if (S->isDefined()) {
641       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Symbol \"" << S->getName()
642                         << "\" is already defined\n");
643       const_cast<MCSymbol *>(S)->setUndefined();
644     }
645     if (S->isRegistered()) {
646       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Symbol \"" << S->getName()
647                         << "\" is already registered\n");
648       const_cast<MCSymbol *>(S)->setIsRegistered(false);
649     }
650     LLVM_DEBUG(if (S->isVariable()) {
651       dbgs() << "BOLT-DEBUG: Symbol \"" << S->getName() << "\" is variable\n";
652     });
653   }
654   return Error::success();
655 }
656 
657 // This peephole fixes jump instructions that jump to another basic
658 // block with a single jump instruction, e.g.
659 //
660 // B0: ...
661 //     jmp  B1   (or jcc B1)
662 //
663 // B1: jmp  B2
664 //
665 // ->
666 //
667 // B0: ...
668 //     jmp  B2   (or jcc B2)
669 //
670 static uint64_t fixDoubleJumps(BinaryFunction &Function, bool MarkInvalid) {
671   uint64_t NumDoubleJumps = 0;
672 
673   MCContext *Ctx = Function.getBinaryContext().Ctx.get();
674   MCPlusBuilder *MIB = Function.getBinaryContext().MIB.get();
675   for (BinaryBasicBlock &BB : Function) {
676     auto checkAndPatch = [&](BinaryBasicBlock *Pred, BinaryBasicBlock *Succ,
677                              const MCSymbol *SuccSym) {
678       // Ignore infinite loop jumps or fallthrough tail jumps.
679       if (Pred == Succ || Succ == &BB)
680         return false;
681 
682       if (Succ) {
683         const MCSymbol *TBB = nullptr;
684         const MCSymbol *FBB = nullptr;
685         MCInst *CondBranch = nullptr;
686         MCInst *UncondBranch = nullptr;
687         bool Res = Pred->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
688         if (!Res) {
689           LLVM_DEBUG(dbgs() << "analyzeBranch failed in peepholes in block:\n";
690                      Pred->dump());
691           return false;
692         }
693         Pred->replaceSuccessor(&BB, Succ);
694 
695         // We must patch up any existing branch instructions to match up
696         // with the new successor.
697         assert((CondBranch || (!CondBranch && Pred->succ_size() == 1)) &&
698                "Predecessor block has inconsistent number of successors");
699         if (CondBranch && MIB->getTargetSymbol(*CondBranch) == BB.getLabel()) {
700           MIB->replaceBranchTarget(*CondBranch, Succ->getLabel(), Ctx);
701         } else if (UncondBranch &&
702                    MIB->getTargetSymbol(*UncondBranch) == BB.getLabel()) {
703           MIB->replaceBranchTarget(*UncondBranch, Succ->getLabel(), Ctx);
704         } else if (!UncondBranch) {
705           assert(Function.getLayout().getBasicBlockAfter(Pred, false) != Succ &&
706                  "Don't add an explicit jump to a fallthrough block.");
707           Pred->addBranchInstruction(Succ);
708         }
709       } else {
710         // Succ will be null in the tail call case.  In this case we
711         // need to explicitly add a tail call instruction.
712         MCInst *Branch = Pred->getLastNonPseudoInstr();
713         if (Branch && MIB->isUnconditionalBranch(*Branch)) {
714           assert(MIB->getTargetSymbol(*Branch) == BB.getLabel());
715           Pred->removeSuccessor(&BB);
716           Pred->eraseInstruction(Pred->findInstruction(Branch));
717           Pred->addTailCallInstruction(SuccSym);
718         } else {
719           return false;
720         }
721       }
722 
723       ++NumDoubleJumps;
724       LLVM_DEBUG(dbgs() << "Removed double jump in " << Function << " from "
725                         << Pred->getName() << " -> " << BB.getName() << " to "
726                         << Pred->getName() << " -> " << SuccSym->getName()
727                         << (!Succ ? " (tail)\n" : "\n"));
728 
729       return true;
730     };
731 
732     if (BB.getNumNonPseudos() != 1 || BB.isLandingPad())
733       continue;
734 
735     MCInst *Inst = BB.getFirstNonPseudoInstr();
736     const bool IsTailCall = MIB->isTailCall(*Inst);
737 
738     if (!MIB->isUnconditionalBranch(*Inst) && !IsTailCall)
739       continue;
740 
741     // If we operate after SCTC make sure it's not a conditional tail call.
742     if (IsTailCall && MIB->isConditionalBranch(*Inst))
743       continue;
744 
745     const MCSymbol *SuccSym = MIB->getTargetSymbol(*Inst);
746     BinaryBasicBlock *Succ = BB.getSuccessor();
747 
748     if (((!Succ || &BB == Succ) && !IsTailCall) || (IsTailCall && !SuccSym))
749       continue;
750 
751     std::vector<BinaryBasicBlock *> Preds = {BB.pred_begin(), BB.pred_end()};
752 
753     for (BinaryBasicBlock *Pred : Preds) {
754       if (Pred->isLandingPad())
755         continue;
756 
757       if (Pred->getSuccessor() == &BB ||
758           (Pred->getConditionalSuccessor(true) == &BB && !IsTailCall) ||
759           Pred->getConditionalSuccessor(false) == &BB)
760         if (checkAndPatch(Pred, Succ, SuccSym) && MarkInvalid)
761           BB.markValid(BB.pred_size() != 0 || BB.isLandingPad() ||
762                        BB.isEntryPoint());
763     }
764   }
765 
766   return NumDoubleJumps;
767 }
768 
769 bool SimplifyConditionalTailCalls::shouldRewriteBranch(
770     const BinaryBasicBlock *PredBB, const MCInst &CondBranch,
771     const BinaryBasicBlock *BB, const bool DirectionFlag) {
772   if (BeenOptimized.count(PredBB))
773     return false;
774 
775   const bool IsForward = BinaryFunction::isForwardBranch(PredBB, BB);
776 
777   if (IsForward)
778     ++NumOrigForwardBranches;
779   else
780     ++NumOrigBackwardBranches;
781 
782   if (opts::SctcMode == opts::SctcAlways)
783     return true;
784 
785   if (opts::SctcMode == opts::SctcPreserveDirection)
786     return IsForward == DirectionFlag;
787 
788   const ErrorOr<std::pair<double, double>> Frequency =
789       PredBB->getBranchStats(BB);
790 
791   // It's ok to rewrite the conditional branch if the new target will be
792   // a backward branch.
793 
794   // If no data available for these branches, then it should be ok to
795   // do the optimization since it will reduce code size.
796   if (Frequency.getError())
797     return true;
798 
799   // TODO: should this use misprediction frequency instead?
800   const bool Result = (IsForward && Frequency.get().first >= 0.5) ||
801                       (!IsForward && Frequency.get().first <= 0.5);
802 
803   return Result == DirectionFlag;
804 }
805 
806 uint64_t SimplifyConditionalTailCalls::fixTailCalls(BinaryFunction &BF) {
807   // Need updated indices to correctly detect branch' direction.
808   BF.getLayout().updateLayoutIndices();
809   BF.markUnreachableBlocks();
810 
811   MCPlusBuilder *MIB = BF.getBinaryContext().MIB.get();
812   MCContext *Ctx = BF.getBinaryContext().Ctx.get();
813   uint64_t NumLocalCTCCandidates = 0;
814   uint64_t NumLocalCTCs = 0;
815   uint64_t LocalCTCTakenCount = 0;
816   uint64_t LocalCTCExecCount = 0;
817   std::vector<std::pair<BinaryBasicBlock *, const BinaryBasicBlock *>>
818       NeedsUncondBranch;
819 
820   // Will block be deleted by UCE?
821   auto isValid = [](const BinaryBasicBlock *BB) {
822     return (BB->pred_size() != 0 || BB->isLandingPad() || BB->isEntryPoint());
823   };
824 
825   for (BinaryBasicBlock *BB : BF.getLayout().blocks()) {
826     // Locate BB with a single direct tail-call instruction.
827     if (BB->getNumNonPseudos() != 1)
828       continue;
829 
830     MCInst *Instr = BB->getFirstNonPseudoInstr();
831     if (!MIB->isTailCall(*Instr) || MIB->isConditionalBranch(*Instr))
832       continue;
833 
834     const MCSymbol *CalleeSymbol = MIB->getTargetSymbol(*Instr);
835     if (!CalleeSymbol)
836       continue;
837 
838     // Detect direction of the possible conditional tail call.
839     const bool IsForwardCTC = BF.isForwardCall(CalleeSymbol);
840 
841     // Iterate through all predecessors.
842     for (BinaryBasicBlock *PredBB : BB->predecessors()) {
843       BinaryBasicBlock *CondSucc = PredBB->getConditionalSuccessor(true);
844       if (!CondSucc)
845         continue;
846 
847       ++NumLocalCTCCandidates;
848 
849       const MCSymbol *TBB = nullptr;
850       const MCSymbol *FBB = nullptr;
851       MCInst *CondBranch = nullptr;
852       MCInst *UncondBranch = nullptr;
853       bool Result = PredBB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
854 
855       // analyzeBranch() can fail due to unusual branch instructions, e.g. jrcxz
856       if (!Result) {
857         LLVM_DEBUG(dbgs() << "analyzeBranch failed in SCTC in block:\n";
858                    PredBB->dump());
859         continue;
860       }
861 
862       assert(Result && "internal error analyzing conditional branch");
863       assert(CondBranch && "conditional branch expected");
864 
865       // Skip dynamic branches for now.
866       if (BF.getBinaryContext().MIB->isDynamicBranch(*CondBranch))
867         continue;
868 
869       // It's possible that PredBB is also a successor to BB that may have
870       // been processed by a previous iteration of the SCTC loop, in which
871       // case it may have been marked invalid.  We should skip rewriting in
872       // this case.
873       if (!PredBB->isValid()) {
874         assert(PredBB->isSuccessor(BB) &&
875                "PredBB should be valid if it is not a successor to BB");
876         continue;
877       }
878 
879       // We don't want to reverse direction of the branch in new order
880       // without further profile analysis.
881       const bool DirectionFlag = CondSucc == BB ? IsForwardCTC : !IsForwardCTC;
882       if (!shouldRewriteBranch(PredBB, *CondBranch, BB, DirectionFlag))
883         continue;
884 
885       // Record this block so that we don't try to optimize it twice.
886       BeenOptimized.insert(PredBB);
887 
888       uint64_t Count = 0;
889       if (CondSucc != BB) {
890         // Patch the new target address into the conditional branch.
891         MIB->reverseBranchCondition(*CondBranch, CalleeSymbol, Ctx);
892         // Since we reversed the condition on the branch we need to change
893         // the target for the unconditional branch or add a unconditional
894         // branch to the old target.  This has to be done manually since
895         // fixupBranches is not called after SCTC.
896         NeedsUncondBranch.emplace_back(PredBB, CondSucc);
897         Count = PredBB->getFallthroughBranchInfo().Count;
898       } else {
899         // Change destination of the conditional branch.
900         MIB->replaceBranchTarget(*CondBranch, CalleeSymbol, Ctx);
901         Count = PredBB->getTakenBranchInfo().Count;
902       }
903       const uint64_t CTCTakenFreq =
904           Count == BinaryBasicBlock::COUNT_NO_PROFILE ? 0 : Count;
905 
906       // Annotate it, so "isCall" returns true for this jcc
907       MIB->setConditionalTailCall(*CondBranch);
908       // Add info about the conditional tail call frequency, otherwise this
909       // info will be lost when we delete the associated BranchInfo entry
910       auto &CTCAnnotation =
911           MIB->getOrCreateAnnotationAs<uint64_t>(*CondBranch, "CTCTakenCount");
912       CTCAnnotation = CTCTakenFreq;
913       // Preserve Offset annotation, used in BAT.
914       // Instr is a direct tail call instruction that was created when CTCs are
915       // first expanded, and has the original CTC offset set.
916       if (std::optional<uint32_t> Offset = MIB->getOffset(*Instr))
917         MIB->setOffset(*CondBranch, *Offset);
918 
919       // Remove the unused successor which may be eliminated later
920       // if there are no other users.
921       PredBB->removeSuccessor(BB);
922       // Update BB execution count
923       if (CTCTakenFreq && CTCTakenFreq <= BB->getKnownExecutionCount())
924         BB->setExecutionCount(BB->getExecutionCount() - CTCTakenFreq);
925       else if (CTCTakenFreq > BB->getKnownExecutionCount())
926         BB->setExecutionCount(0);
927 
928       ++NumLocalCTCs;
929       LocalCTCTakenCount += CTCTakenFreq;
930       LocalCTCExecCount += PredBB->getKnownExecutionCount();
931     }
932 
933     // Remove the block from CFG if all predecessors were removed.
934     BB->markValid(isValid(BB));
935   }
936 
937   // Add unconditional branches at the end of BBs to new successors
938   // as long as the successor is not a fallthrough.
939   for (auto &Entry : NeedsUncondBranch) {
940     BinaryBasicBlock *PredBB = Entry.first;
941     const BinaryBasicBlock *CondSucc = Entry.second;
942 
943     const MCSymbol *TBB = nullptr;
944     const MCSymbol *FBB = nullptr;
945     MCInst *CondBranch = nullptr;
946     MCInst *UncondBranch = nullptr;
947     PredBB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
948 
949     // Find the next valid block.  Invalid blocks will be deleted
950     // so they shouldn't be considered fallthrough targets.
951     const BinaryBasicBlock *NextBlock =
952         BF.getLayout().getBasicBlockAfter(PredBB, false);
953     while (NextBlock && !isValid(NextBlock))
954       NextBlock = BF.getLayout().getBasicBlockAfter(NextBlock, false);
955 
956     // Get the unconditional successor to this block.
957     const BinaryBasicBlock *PredSucc = PredBB->getSuccessor();
958     assert(PredSucc && "The other branch should be a tail call");
959 
960     const bool HasFallthrough = (NextBlock && PredSucc == NextBlock);
961 
962     if (UncondBranch) {
963       if (HasFallthrough)
964         PredBB->eraseInstruction(PredBB->findInstruction(UncondBranch));
965       else
966         MIB->replaceBranchTarget(*UncondBranch, CondSucc->getLabel(), Ctx);
967     } else if (!HasFallthrough) {
968       MCInst Branch;
969       MIB->createUncondBranch(Branch, CondSucc->getLabel(), Ctx);
970       PredBB->addInstruction(Branch);
971     }
972   }
973 
974   if (NumLocalCTCs > 0) {
975     NumDoubleJumps += fixDoubleJumps(BF, true);
976     // Clean-up unreachable tail-call blocks.
977     const std::pair<unsigned, uint64_t> Stats = BF.eraseInvalidBBs();
978     DeletedBlocks += Stats.first;
979     DeletedBytes += Stats.second;
980 
981     assert(BF.validateCFG());
982   }
983 
984   LLVM_DEBUG(dbgs() << "BOLT: created " << NumLocalCTCs
985                     << " conditional tail calls from a total of "
986                     << NumLocalCTCCandidates << " candidates in function " << BF
987                     << ". CTCs execution count for this function is "
988                     << LocalCTCExecCount << " and CTC taken count is "
989                     << LocalCTCTakenCount << "\n";);
990 
991   NumTailCallsPatched += NumLocalCTCs;
992   NumCandidateTailCalls += NumLocalCTCCandidates;
993   CTCExecCount += LocalCTCExecCount;
994   CTCTakenCount += LocalCTCTakenCount;
995 
996   return NumLocalCTCs > 0;
997 }
998 
999 Error SimplifyConditionalTailCalls::runOnFunctions(BinaryContext &BC) {
1000   if (!BC.isX86())
1001     return Error::success();
1002 
1003   for (auto &It : BC.getBinaryFunctions()) {
1004     BinaryFunction &Function = It.second;
1005 
1006     if (!shouldOptimize(Function))
1007       continue;
1008 
1009     if (fixTailCalls(Function)) {
1010       Modified.insert(&Function);
1011       Function.setHasCanonicalCFG(false);
1012     }
1013   }
1014 
1015   if (NumTailCallsPatched)
1016     BC.outs() << "BOLT-INFO: SCTC: patched " << NumTailCallsPatched
1017               << " tail calls (" << NumOrigForwardBranches << " forward)"
1018               << " tail calls (" << NumOrigBackwardBranches << " backward)"
1019               << " from a total of " << NumCandidateTailCalls
1020               << " while removing " << NumDoubleJumps << " double jumps"
1021               << " and removing " << DeletedBlocks << " basic blocks"
1022               << " totalling " << DeletedBytes
1023               << " bytes of code. CTCs total execution count is "
1024               << CTCExecCount << " and the number of times CTCs are taken is "
1025               << CTCTakenCount << "\n";
1026   return Error::success();
1027 }
1028 
1029 uint64_t ShortenInstructions::shortenInstructions(BinaryFunction &Function) {
1030   uint64_t Count = 0;
1031   const BinaryContext &BC = Function.getBinaryContext();
1032   for (BinaryBasicBlock &BB : Function) {
1033     for (MCInst &Inst : BB) {
1034       // Skip shortening instructions with Size annotation.
1035       if (BC.MIB->getSize(Inst))
1036         continue;
1037 
1038       MCInst OriginalInst;
1039       if (opts::Verbosity > 2)
1040         OriginalInst = Inst;
1041 
1042       if (!BC.MIB->shortenInstruction(Inst, *BC.STI))
1043         continue;
1044 
1045       if (opts::Verbosity > 2) {
1046         BC.scopeLock();
1047         BC.outs() << "BOLT-INFO: shortening:\nBOLT-INFO:    ";
1048         BC.printInstruction(BC.outs(), OriginalInst, 0, &Function);
1049         BC.outs() << "BOLT-INFO: to:";
1050         BC.printInstruction(BC.outs(), Inst, 0, &Function);
1051       }
1052 
1053       ++Count;
1054     }
1055   }
1056 
1057   return Count;
1058 }
1059 
1060 Error ShortenInstructions::runOnFunctions(BinaryContext &BC) {
1061   std::atomic<uint64_t> NumShortened{0};
1062   if (!BC.isX86())
1063     return Error::success();
1064 
1065   ParallelUtilities::runOnEachFunction(
1066       BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR,
1067       [&](BinaryFunction &BF) { NumShortened += shortenInstructions(BF); },
1068       nullptr, "ShortenInstructions");
1069 
1070   if (NumShortened)
1071     BC.outs() << "BOLT-INFO: " << NumShortened
1072               << " instructions were shortened\n";
1073   return Error::success();
1074 }
1075 
1076 void Peepholes::addTailcallTraps(BinaryFunction &Function) {
1077   MCPlusBuilder *MIB = Function.getBinaryContext().MIB.get();
1078   for (BinaryBasicBlock &BB : Function) {
1079     MCInst *Inst = BB.getLastNonPseudoInstr();
1080     if (Inst && MIB->isTailCall(*Inst) && MIB->isIndirectBranch(*Inst)) {
1081       MCInst Trap;
1082       MIB->createTrap(Trap);
1083       BB.addInstruction(Trap);
1084       ++TailCallTraps;
1085     }
1086   }
1087 }
1088 
1089 void Peepholes::removeUselessCondBranches(BinaryFunction &Function) {
1090   for (BinaryBasicBlock &BB : Function) {
1091     if (BB.succ_size() != 2)
1092       continue;
1093 
1094     BinaryBasicBlock *CondBB = BB.getConditionalSuccessor(true);
1095     BinaryBasicBlock *UncondBB = BB.getConditionalSuccessor(false);
1096     if (CondBB != UncondBB)
1097       continue;
1098 
1099     const MCSymbol *TBB = nullptr;
1100     const MCSymbol *FBB = nullptr;
1101     MCInst *CondBranch = nullptr;
1102     MCInst *UncondBranch = nullptr;
1103     bool Result = BB.analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
1104 
1105     // analyzeBranch() can fail due to unusual branch instructions,
1106     // e.g. jrcxz, or jump tables (indirect jump).
1107     if (!Result || !CondBranch)
1108       continue;
1109 
1110     BB.removeDuplicateConditionalSuccessor(CondBranch);
1111     ++NumUselessCondBranches;
1112   }
1113 }
1114 
1115 Error Peepholes::runOnFunctions(BinaryContext &BC) {
1116   const char Opts =
1117       std::accumulate(opts::Peepholes.begin(), opts::Peepholes.end(), 0,
1118                       [](const char A, const PeepholeOpts B) { return A | B; });
1119   if (Opts == PEEP_NONE)
1120     return Error::success();
1121 
1122   for (auto &It : BC.getBinaryFunctions()) {
1123     BinaryFunction &Function = It.second;
1124     if (shouldOptimize(Function)) {
1125       if (Opts & PEEP_DOUBLE_JUMPS)
1126         NumDoubleJumps += fixDoubleJumps(Function, false);
1127       if (Opts & PEEP_TAILCALL_TRAPS)
1128         addTailcallTraps(Function);
1129       if (Opts & PEEP_USELESS_BRANCHES)
1130         removeUselessCondBranches(Function);
1131       assert(Function.validateCFG());
1132     }
1133   }
1134   BC.outs() << "BOLT-INFO: Peephole: " << NumDoubleJumps
1135             << " double jumps patched.\n"
1136             << "BOLT-INFO: Peephole: " << TailCallTraps
1137             << " tail call traps inserted.\n"
1138             << "BOLT-INFO: Peephole: " << NumUselessCondBranches
1139             << " useless conditional branches removed.\n";
1140   return Error::success();
1141 }
1142 
1143 bool SimplifyRODataLoads::simplifyRODataLoads(BinaryFunction &BF) {
1144   BinaryContext &BC = BF.getBinaryContext();
1145   MCPlusBuilder *MIB = BC.MIB.get();
1146 
1147   uint64_t NumLocalLoadsSimplified = 0;
1148   uint64_t NumDynamicLocalLoadsSimplified = 0;
1149   uint64_t NumLocalLoadsFound = 0;
1150   uint64_t NumDynamicLocalLoadsFound = 0;
1151 
1152   for (BinaryBasicBlock *BB : BF.getLayout().blocks()) {
1153     for (MCInst &Inst : *BB) {
1154       unsigned Opcode = Inst.getOpcode();
1155       const MCInstrDesc &Desc = BC.MII->get(Opcode);
1156 
1157       // Skip instructions that do not load from memory.
1158       if (!Desc.mayLoad())
1159         continue;
1160 
1161       // Try to statically evaluate the target memory address;
1162       uint64_t TargetAddress;
1163 
1164       if (MIB->hasPCRelOperand(Inst)) {
1165         // Try to find the symbol that corresponds to the PC-relative operand.
1166         MCOperand *DispOpI = MIB->getMemOperandDisp(Inst);
1167         assert(DispOpI != Inst.end() && "expected PC-relative displacement");
1168         assert(DispOpI->isExpr() &&
1169                "found PC-relative with non-symbolic displacement");
1170 
1171         // Get displacement symbol.
1172         const MCSymbol *DisplSymbol;
1173         uint64_t DisplOffset;
1174 
1175         std::tie(DisplSymbol, DisplOffset) =
1176             MIB->getTargetSymbolInfo(DispOpI->getExpr());
1177 
1178         if (!DisplSymbol)
1179           continue;
1180 
1181         // Look up the symbol address in the global symbols map of the binary
1182         // context object.
1183         BinaryData *BD = BC.getBinaryDataByName(DisplSymbol->getName());
1184         if (!BD)
1185           continue;
1186         TargetAddress = BD->getAddress() + DisplOffset;
1187       } else if (!MIB->evaluateMemOperandTarget(Inst, TargetAddress)) {
1188         continue;
1189       }
1190 
1191       // Get the contents of the section containing the target address of the
1192       // memory operand. We are only interested in read-only sections.
1193       ErrorOr<BinarySection &> DataSection =
1194           BC.getSectionForAddress(TargetAddress);
1195       if (!DataSection || DataSection->isWritable())
1196         continue;
1197 
1198       if (BC.getRelocationAt(TargetAddress) ||
1199           BC.getDynamicRelocationAt(TargetAddress))
1200         continue;
1201 
1202       uint32_t Offset = TargetAddress - DataSection->getAddress();
1203       StringRef ConstantData = DataSection->getContents();
1204 
1205       ++NumLocalLoadsFound;
1206       if (BB->hasProfile())
1207         NumDynamicLocalLoadsFound += BB->getExecutionCount();
1208 
1209       if (MIB->replaceMemOperandWithImm(Inst, ConstantData, Offset)) {
1210         ++NumLocalLoadsSimplified;
1211         if (BB->hasProfile())
1212           NumDynamicLocalLoadsSimplified += BB->getExecutionCount();
1213       }
1214     }
1215   }
1216 
1217   NumLoadsFound += NumLocalLoadsFound;
1218   NumDynamicLoadsFound += NumDynamicLocalLoadsFound;
1219   NumLoadsSimplified += NumLocalLoadsSimplified;
1220   NumDynamicLoadsSimplified += NumDynamicLocalLoadsSimplified;
1221 
1222   return NumLocalLoadsSimplified > 0;
1223 }
1224 
1225 Error SimplifyRODataLoads::runOnFunctions(BinaryContext &BC) {
1226   for (auto &It : BC.getBinaryFunctions()) {
1227     BinaryFunction &Function = It.second;
1228     if (shouldOptimize(Function) && simplifyRODataLoads(Function))
1229       Modified.insert(&Function);
1230   }
1231 
1232   BC.outs() << "BOLT-INFO: simplified " << NumLoadsSimplified << " out of "
1233             << NumLoadsFound << " loads from a statically computed address.\n"
1234             << "BOLT-INFO: dynamic loads simplified: "
1235             << NumDynamicLoadsSimplified << "\n"
1236             << "BOLT-INFO: dynamic loads found: " << NumDynamicLoadsFound
1237             << "\n";
1238   return Error::success();
1239 }
1240 
1241 Error AssignSections::runOnFunctions(BinaryContext &BC) {
1242   for (BinaryFunction *Function : BC.getInjectedBinaryFunctions()) {
1243     Function->setCodeSectionName(BC.getInjectedCodeSectionName());
1244     Function->setColdCodeSectionName(BC.getInjectedColdCodeSectionName());
1245   }
1246 
1247   // In non-relocation mode functions have pre-assigned section names.
1248   if (!BC.HasRelocations)
1249     return Error::success();
1250 
1251   const bool UseColdSection =
1252       BC.NumProfiledFuncs > 0 ||
1253       opts::ReorderFunctions == ReorderFunctions::RT_USER;
1254   for (auto &BFI : BC.getBinaryFunctions()) {
1255     BinaryFunction &Function = BFI.second;
1256     if (opts::isHotTextMover(Function)) {
1257       Function.setCodeSectionName(BC.getHotTextMoverSectionName());
1258       Function.setColdCodeSectionName(BC.getHotTextMoverSectionName());
1259       continue;
1260     }
1261 
1262     if (!UseColdSection || Function.hasValidIndex())
1263       Function.setCodeSectionName(BC.getMainCodeSectionName());
1264     else
1265       Function.setCodeSectionName(BC.getColdCodeSectionName());
1266 
1267     if (Function.isSplit())
1268       Function.setColdCodeSectionName(BC.getColdCodeSectionName());
1269   }
1270   return Error::success();
1271 }
1272 
1273 Error PrintProfileStats::runOnFunctions(BinaryContext &BC) {
1274   double FlowImbalanceMean = 0.0;
1275   size_t NumBlocksConsidered = 0;
1276   double WorstBias = 0.0;
1277   const BinaryFunction *WorstBiasFunc = nullptr;
1278 
1279   // For each function CFG, we fill an IncomingMap with the sum of the frequency
1280   // of incoming edges for each BB. Likewise for each OutgoingMap and the sum
1281   // of the frequency of outgoing edges.
1282   using FlowMapTy = std::unordered_map<const BinaryBasicBlock *, uint64_t>;
1283   std::unordered_map<const BinaryFunction *, FlowMapTy> TotalIncomingMaps;
1284   std::unordered_map<const BinaryFunction *, FlowMapTy> TotalOutgoingMaps;
1285 
1286   // Compute mean
1287   for (const auto &BFI : BC.getBinaryFunctions()) {
1288     const BinaryFunction &Function = BFI.second;
1289     if (Function.empty() || !Function.isSimple())
1290       continue;
1291     FlowMapTy &IncomingMap = TotalIncomingMaps[&Function];
1292     FlowMapTy &OutgoingMap = TotalOutgoingMaps[&Function];
1293     for (const BinaryBasicBlock &BB : Function) {
1294       uint64_t TotalOutgoing = 0ULL;
1295       auto SuccBIIter = BB.branch_info_begin();
1296       for (BinaryBasicBlock *Succ : BB.successors()) {
1297         uint64_t Count = SuccBIIter->Count;
1298         if (Count == BinaryBasicBlock::COUNT_NO_PROFILE || Count == 0) {
1299           ++SuccBIIter;
1300           continue;
1301         }
1302         TotalOutgoing += Count;
1303         IncomingMap[Succ] += Count;
1304         ++SuccBIIter;
1305       }
1306       OutgoingMap[&BB] = TotalOutgoing;
1307     }
1308 
1309     size_t NumBlocks = 0;
1310     double Mean = 0.0;
1311     for (const BinaryBasicBlock &BB : Function) {
1312       // Do not compute score for low frequency blocks, entry or exit blocks
1313       if (IncomingMap[&BB] < 100 || OutgoingMap[&BB] == 0 || BB.isEntryPoint())
1314         continue;
1315       ++NumBlocks;
1316       const double Difference = (double)OutgoingMap[&BB] - IncomingMap[&BB];
1317       Mean += fabs(Difference / IncomingMap[&BB]);
1318     }
1319 
1320     FlowImbalanceMean += Mean;
1321     NumBlocksConsidered += NumBlocks;
1322     if (!NumBlocks)
1323       continue;
1324     double FuncMean = Mean / NumBlocks;
1325     if (FuncMean > WorstBias) {
1326       WorstBias = FuncMean;
1327       WorstBiasFunc = &Function;
1328     }
1329   }
1330   if (NumBlocksConsidered > 0)
1331     FlowImbalanceMean /= NumBlocksConsidered;
1332 
1333   // Compute standard deviation
1334   NumBlocksConsidered = 0;
1335   double FlowImbalanceVar = 0.0;
1336   for (const auto &BFI : BC.getBinaryFunctions()) {
1337     const BinaryFunction &Function = BFI.second;
1338     if (Function.empty() || !Function.isSimple())
1339       continue;
1340     FlowMapTy &IncomingMap = TotalIncomingMaps[&Function];
1341     FlowMapTy &OutgoingMap = TotalOutgoingMaps[&Function];
1342     for (const BinaryBasicBlock &BB : Function) {
1343       if (IncomingMap[&BB] < 100 || OutgoingMap[&BB] == 0)
1344         continue;
1345       ++NumBlocksConsidered;
1346       const double Difference = (double)OutgoingMap[&BB] - IncomingMap[&BB];
1347       FlowImbalanceVar +=
1348           pow(fabs(Difference / IncomingMap[&BB]) - FlowImbalanceMean, 2);
1349     }
1350   }
1351   if (NumBlocksConsidered) {
1352     FlowImbalanceVar /= NumBlocksConsidered;
1353     FlowImbalanceVar = sqrt(FlowImbalanceVar);
1354   }
1355 
1356   // Report to user
1357   BC.outs() << format("BOLT-INFO: Profile bias score: %.4lf%% StDev: %.4lf%%\n",
1358                       (100.0 * FlowImbalanceMean), (100.0 * FlowImbalanceVar));
1359   if (WorstBiasFunc && opts::Verbosity >= 1) {
1360     BC.outs() << "Worst average bias observed in "
1361               << WorstBiasFunc->getPrintName() << "\n";
1362     LLVM_DEBUG(WorstBiasFunc->dump());
1363   }
1364   return Error::success();
1365 }
1366 
1367 Error PrintProgramStats::runOnFunctions(BinaryContext &BC) {
1368   uint64_t NumRegularFunctions = 0;
1369   uint64_t NumStaleProfileFunctions = 0;
1370   uint64_t NumAllStaleFunctions = 0;
1371   uint64_t NumInferredFunctions = 0;
1372   uint64_t NumNonSimpleProfiledFunctions = 0;
1373   uint64_t NumUnknownControlFlowFunctions = 0;
1374   uint64_t TotalSampleCount = 0;
1375   uint64_t StaleSampleCount = 0;
1376   uint64_t InferredSampleCount = 0;
1377   std::vector<const BinaryFunction *> ProfiledFunctions;
1378   const char *StaleFuncsHeader = "BOLT-INFO: Functions with stale profile:\n";
1379   for (auto &BFI : BC.getBinaryFunctions()) {
1380     const BinaryFunction &Function = BFI.second;
1381 
1382     // Ignore PLT functions for stats.
1383     if (Function.isPLTFunction())
1384       continue;
1385 
1386     ++NumRegularFunctions;
1387 
1388     if (!Function.isSimple()) {
1389       if (Function.hasProfile())
1390         ++NumNonSimpleProfiledFunctions;
1391       continue;
1392     }
1393 
1394     if (Function.hasUnknownControlFlow()) {
1395       if (opts::PrintUnknownCFG)
1396         Function.dump();
1397       else if (opts::PrintUnknown)
1398         BC.errs() << "function with unknown control flow: " << Function << '\n';
1399 
1400       ++NumUnknownControlFlowFunctions;
1401     }
1402 
1403     if (!Function.hasProfile())
1404       continue;
1405 
1406     uint64_t SampleCount = Function.getRawBranchCount();
1407     TotalSampleCount += SampleCount;
1408 
1409     if (Function.hasValidProfile()) {
1410       ProfiledFunctions.push_back(&Function);
1411       if (Function.hasInferredProfile()) {
1412         ++NumInferredFunctions;
1413         InferredSampleCount += SampleCount;
1414         ++NumAllStaleFunctions;
1415       }
1416     } else {
1417       if (opts::ReportStaleFuncs) {
1418         BC.outs() << StaleFuncsHeader;
1419         StaleFuncsHeader = "";
1420         BC.outs() << "  " << Function << '\n';
1421       }
1422       ++NumStaleProfileFunctions;
1423       StaleSampleCount += SampleCount;
1424       ++NumAllStaleFunctions;
1425     }
1426   }
1427   BC.NumProfiledFuncs = ProfiledFunctions.size();
1428   BC.NumStaleProfileFuncs = NumStaleProfileFunctions;
1429 
1430   const size_t NumAllProfiledFunctions =
1431       ProfiledFunctions.size() + NumStaleProfileFunctions;
1432   BC.outs() << "BOLT-INFO: " << NumAllProfiledFunctions << " out of "
1433             << NumRegularFunctions << " functions in the binary ("
1434             << format("%.1f", NumAllProfiledFunctions /
1435                                   (float)NumRegularFunctions * 100.0f)
1436             << "%) have non-empty execution profile\n";
1437   if (NumNonSimpleProfiledFunctions) {
1438     BC.outs() << "BOLT-INFO: " << NumNonSimpleProfiledFunctions << " function"
1439               << (NumNonSimpleProfiledFunctions == 1 ? "" : "s")
1440               << " with profile could not be optimized\n";
1441   }
1442   if (NumAllStaleFunctions) {
1443     const float PctStale =
1444         NumAllStaleFunctions / (float)NumAllProfiledFunctions * 100.0f;
1445     const float PctStaleFuncsWithEqualBlockCount =
1446         (float)BC.Stats.NumStaleFuncsWithEqualBlockCount /
1447         NumAllStaleFunctions * 100.0f;
1448     const float PctStaleBlocksWithEqualIcount =
1449         (float)BC.Stats.NumStaleBlocksWithEqualIcount /
1450         BC.Stats.NumStaleBlocks * 100.0f;
1451     auto printErrorOrWarning = [&]() {
1452       if (PctStale > opts::StaleThreshold)
1453         BC.errs() << "BOLT-ERROR: ";
1454       else
1455         BC.errs() << "BOLT-WARNING: ";
1456     };
1457     printErrorOrWarning();
1458     BC.errs() << NumAllStaleFunctions
1459               << format(" (%.1f%% of all profiled)", PctStale) << " function"
1460               << (NumAllStaleFunctions == 1 ? "" : "s")
1461               << " have invalid (possibly stale) profile."
1462                  " Use -report-stale to see the list.\n";
1463     if (TotalSampleCount > 0) {
1464       printErrorOrWarning();
1465       BC.errs() << (StaleSampleCount + InferredSampleCount) << " out of "
1466                 << TotalSampleCount << " samples in the binary ("
1467                 << format("%.1f",
1468                           ((100.0f * (StaleSampleCount + InferredSampleCount)) /
1469                            TotalSampleCount))
1470                 << "%) belong to functions with invalid"
1471                    " (possibly stale) profile.\n";
1472     }
1473     BC.outs() << "BOLT-INFO: " << BC.Stats.NumStaleFuncsWithEqualBlockCount
1474               << " stale function"
1475               << (BC.Stats.NumStaleFuncsWithEqualBlockCount == 1 ? "" : "s")
1476               << format(" (%.1f%% of all stale)",
1477                         PctStaleFuncsWithEqualBlockCount)
1478               << " have matching block count.\n";
1479     BC.outs() << "BOLT-INFO: " << BC.Stats.NumStaleBlocksWithEqualIcount
1480               << " stale block"
1481               << (BC.Stats.NumStaleBlocksWithEqualIcount == 1 ? "" : "s")
1482               << format(" (%.1f%% of all stale)", PctStaleBlocksWithEqualIcount)
1483               << " have matching icount.\n";
1484     if (PctStale > opts::StaleThreshold) {
1485       return createFatalBOLTError(
1486           Twine("BOLT-ERROR: stale functions exceed specified threshold of ") +
1487           Twine(opts::StaleThreshold.getValue()) + Twine("%. Exiting.\n"));
1488     }
1489   }
1490   if (NumInferredFunctions) {
1491     BC.outs() << format(
1492         "BOLT-INFO: inferred profile for %d (%.2f%% of profiled, "
1493         "%.2f%% of stale) functions responsible for %.2f%% samples"
1494         " (%zu out of %zu)\n",
1495         NumInferredFunctions,
1496         100.0 * NumInferredFunctions / NumAllProfiledFunctions,
1497         100.0 * NumInferredFunctions / NumAllStaleFunctions,
1498         100.0 * InferredSampleCount / TotalSampleCount, InferredSampleCount,
1499         TotalSampleCount);
1500     BC.outs() << format(
1501         "BOLT-INFO: inference found an exact match for %.2f%% of basic blocks"
1502         " (%zu out of %zu stale) responsible for %.2f%% samples"
1503         " (%zu out of %zu stale)\n",
1504         100.0 * BC.Stats.NumMatchedBlocks / BC.Stats.NumStaleBlocks,
1505         BC.Stats.NumMatchedBlocks, BC.Stats.NumStaleBlocks,
1506         100.0 * BC.Stats.MatchedSampleCount / BC.Stats.StaleSampleCount,
1507         BC.Stats.MatchedSampleCount, BC.Stats.StaleSampleCount);
1508   }
1509 
1510   if (const uint64_t NumUnusedObjects = BC.getNumUnusedProfiledObjects()) {
1511     BC.outs() << "BOLT-INFO: profile for " << NumUnusedObjects
1512               << " objects was ignored\n";
1513   }
1514 
1515   if (ProfiledFunctions.size() > 10) {
1516     if (opts::Verbosity >= 1) {
1517       BC.outs() << "BOLT-INFO: top called functions are:\n";
1518       llvm::sort(ProfiledFunctions,
1519                  [](const BinaryFunction *A, const BinaryFunction *B) {
1520                    return B->getExecutionCount() < A->getExecutionCount();
1521                  });
1522       auto SFI = ProfiledFunctions.begin();
1523       auto SFIend = ProfiledFunctions.end();
1524       for (unsigned I = 0u; I < opts::TopCalledLimit && SFI != SFIend;
1525            ++SFI, ++I)
1526         BC.outs() << "  " << **SFI << " : " << (*SFI)->getExecutionCount()
1527                   << '\n';
1528     }
1529   }
1530 
1531   if (!opts::PrintSortedBy.empty()) {
1532     std::vector<BinaryFunction *> Functions;
1533     std::map<const BinaryFunction *, DynoStats> Stats;
1534 
1535     for (auto &BFI : BC.getBinaryFunctions()) {
1536       BinaryFunction &BF = BFI.second;
1537       if (shouldOptimize(BF) && BF.hasValidProfile()) {
1538         Functions.push_back(&BF);
1539         Stats.emplace(&BF, getDynoStats(BF));
1540       }
1541     }
1542 
1543     const bool SortAll =
1544         llvm::is_contained(opts::PrintSortedBy, DynoStats::LAST_DYNO_STAT);
1545 
1546     const bool Ascending =
1547         opts::DynoStatsSortOrderOpt == opts::DynoStatsSortOrder::Ascending;
1548 
1549     if (SortAll) {
1550       llvm::stable_sort(Functions,
1551                         [Ascending, &Stats](const BinaryFunction *A,
1552                                             const BinaryFunction *B) {
1553                           return Ascending ? Stats.at(A) < Stats.at(B)
1554                                            : Stats.at(B) < Stats.at(A);
1555                         });
1556     } else {
1557       llvm::stable_sort(
1558           Functions, [Ascending, &Stats](const BinaryFunction *A,
1559                                          const BinaryFunction *B) {
1560             const DynoStats &StatsA = Stats.at(A);
1561             const DynoStats &StatsB = Stats.at(B);
1562             return Ascending ? StatsA.lessThan(StatsB, opts::PrintSortedBy)
1563                              : StatsB.lessThan(StatsA, opts::PrintSortedBy);
1564           });
1565     }
1566 
1567     BC.outs() << "BOLT-INFO: top functions sorted by ";
1568     if (SortAll) {
1569       BC.outs() << "dyno stats";
1570     } else {
1571       BC.outs() << "(";
1572       bool PrintComma = false;
1573       for (const DynoStats::Category Category : opts::PrintSortedBy) {
1574         if (PrintComma)
1575           BC.outs() << ", ";
1576         BC.outs() << DynoStats::Description(Category);
1577         PrintComma = true;
1578       }
1579       BC.outs() << ")";
1580     }
1581 
1582     BC.outs() << " are:\n";
1583     auto SFI = Functions.begin();
1584     for (unsigned I = 0; I < 100 && SFI != Functions.end(); ++SFI, ++I) {
1585       const DynoStats Stats = getDynoStats(**SFI);
1586       BC.outs() << "  " << **SFI;
1587       if (!SortAll) {
1588         BC.outs() << " (";
1589         bool PrintComma = false;
1590         for (const DynoStats::Category Category : opts::PrintSortedBy) {
1591           if (PrintComma)
1592             BC.outs() << ", ";
1593           BC.outs() << dynoStatsOptName(Category) << "=" << Stats[Category];
1594           PrintComma = true;
1595         }
1596         BC.outs() << ")";
1597       }
1598       BC.outs() << "\n";
1599     }
1600   }
1601 
1602   if (!BC.TrappedFunctions.empty()) {
1603     BC.errs() << "BOLT-WARNING: " << BC.TrappedFunctions.size() << " function"
1604               << (BC.TrappedFunctions.size() > 1 ? "s" : "")
1605               << " will trap on entry. Use -trap-avx512=0 to disable"
1606                  " traps.";
1607     if (opts::Verbosity >= 1 || BC.TrappedFunctions.size() <= 5) {
1608       BC.errs() << '\n';
1609       for (const BinaryFunction *Function : BC.TrappedFunctions)
1610         BC.errs() << "  " << *Function << '\n';
1611     } else {
1612       BC.errs() << " Use -v=1 to see the list.\n";
1613     }
1614   }
1615 
1616   // Print information on missed macro-fusion opportunities seen on input.
1617   if (BC.Stats.MissedMacroFusionPairs) {
1618     BC.outs() << format(
1619         "BOLT-INFO: the input contains %zu (dynamic count : %zu)"
1620         " opportunities for macro-fusion optimization",
1621         BC.Stats.MissedMacroFusionPairs, BC.Stats.MissedMacroFusionExecCount);
1622     switch (opts::AlignMacroOpFusion) {
1623     case MFT_NONE:
1624       BC.outs() << ". Use -align-macro-fusion to fix.\n";
1625       break;
1626     case MFT_HOT:
1627       BC.outs() << ". Will fix instances on a hot path.\n";
1628       break;
1629     case MFT_ALL:
1630       BC.outs() << " that are going to be fixed\n";
1631       break;
1632     }
1633   }
1634 
1635   // Collect and print information about suboptimal code layout on input.
1636   if (opts::ReportBadLayout) {
1637     std::vector<BinaryFunction *> SuboptimalFuncs;
1638     for (auto &BFI : BC.getBinaryFunctions()) {
1639       BinaryFunction &BF = BFI.second;
1640       if (!BF.hasValidProfile())
1641         continue;
1642 
1643       const uint64_t HotThreshold =
1644           std::max<uint64_t>(BF.getKnownExecutionCount(), 1);
1645       bool HotSeen = false;
1646       for (const BinaryBasicBlock *BB : BF.getLayout().rblocks()) {
1647         if (!HotSeen && BB->getKnownExecutionCount() > HotThreshold) {
1648           HotSeen = true;
1649           continue;
1650         }
1651         if (HotSeen && BB->getKnownExecutionCount() == 0) {
1652           SuboptimalFuncs.push_back(&BF);
1653           break;
1654         }
1655       }
1656     }
1657 
1658     if (!SuboptimalFuncs.empty()) {
1659       llvm::sort(SuboptimalFuncs,
1660                  [](const BinaryFunction *A, const BinaryFunction *B) {
1661                    return A->getKnownExecutionCount() / A->getSize() >
1662                           B->getKnownExecutionCount() / B->getSize();
1663                  });
1664 
1665       BC.outs() << "BOLT-INFO: " << SuboptimalFuncs.size()
1666                 << " functions have "
1667                    "cold code in the middle of hot code. Top functions are:\n";
1668       for (unsigned I = 0;
1669            I < std::min(static_cast<size_t>(opts::ReportBadLayout),
1670                         SuboptimalFuncs.size());
1671            ++I)
1672         SuboptimalFuncs[I]->print(BC.outs());
1673     }
1674   }
1675 
1676   if (NumUnknownControlFlowFunctions) {
1677     BC.outs() << "BOLT-INFO: " << NumUnknownControlFlowFunctions
1678               << " functions have instructions with unknown control flow";
1679     if (!opts::PrintUnknown)
1680       BC.outs() << ". Use -print-unknown to see the list.";
1681     BC.outs() << '\n';
1682   }
1683   return Error::success();
1684 }
1685 
1686 Error InstructionLowering::runOnFunctions(BinaryContext &BC) {
1687   for (auto &BFI : BC.getBinaryFunctions())
1688     for (BinaryBasicBlock &BB : BFI.second)
1689       for (MCInst &Instruction : BB)
1690         BC.MIB->lowerTailCall(Instruction);
1691   return Error::success();
1692 }
1693 
1694 Error StripRepRet::runOnFunctions(BinaryContext &BC) {
1695   if (!BC.isX86())
1696     return Error::success();
1697 
1698   uint64_t NumPrefixesRemoved = 0;
1699   uint64_t NumBytesSaved = 0;
1700   for (auto &BFI : BC.getBinaryFunctions()) {
1701     for (BinaryBasicBlock &BB : BFI.second) {
1702       auto LastInstRIter = BB.getLastNonPseudo();
1703       if (LastInstRIter == BB.rend() || !BC.MIB->isReturn(*LastInstRIter) ||
1704           !BC.MIB->deleteREPPrefix(*LastInstRIter))
1705         continue;
1706 
1707       NumPrefixesRemoved += BB.getKnownExecutionCount();
1708       ++NumBytesSaved;
1709     }
1710   }
1711 
1712   if (NumBytesSaved)
1713     BC.outs() << "BOLT-INFO: removed " << NumBytesSaved
1714               << " 'repz' prefixes"
1715                  " with estimated execution count of "
1716               << NumPrefixesRemoved << " times.\n";
1717   return Error::success();
1718 }
1719 
1720 Error InlineMemcpy::runOnFunctions(BinaryContext &BC) {
1721   if (!BC.isX86())
1722     return Error::success();
1723 
1724   uint64_t NumInlined = 0;
1725   uint64_t NumInlinedDyno = 0;
1726   for (auto &BFI : BC.getBinaryFunctions()) {
1727     for (BinaryBasicBlock &BB : BFI.second) {
1728       for (auto II = BB.begin(); II != BB.end(); ++II) {
1729         MCInst &Inst = *II;
1730 
1731         if (!BC.MIB->isCall(Inst) || MCPlus::getNumPrimeOperands(Inst) != 1 ||
1732             !Inst.getOperand(0).isExpr())
1733           continue;
1734 
1735         const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(Inst);
1736         if (CalleeSymbol->getName() != "memcpy" &&
1737             CalleeSymbol->getName() != "memcpy@PLT" &&
1738             CalleeSymbol->getName() != "_memcpy8")
1739           continue;
1740 
1741         const bool IsMemcpy8 = (CalleeSymbol->getName() == "_memcpy8");
1742         const bool IsTailCall = BC.MIB->isTailCall(Inst);
1743 
1744         const InstructionListType NewCode =
1745             BC.MIB->createInlineMemcpy(IsMemcpy8);
1746         II = BB.replaceInstruction(II, NewCode);
1747         std::advance(II, NewCode.size() - 1);
1748         if (IsTailCall) {
1749           MCInst Return;
1750           BC.MIB->createReturn(Return);
1751           II = BB.insertInstruction(std::next(II), std::move(Return));
1752         }
1753 
1754         ++NumInlined;
1755         NumInlinedDyno += BB.getKnownExecutionCount();
1756       }
1757     }
1758   }
1759 
1760   if (NumInlined) {
1761     BC.outs() << "BOLT-INFO: inlined " << NumInlined << " memcpy() calls";
1762     if (NumInlinedDyno)
1763       BC.outs() << ". The calls were executed " << NumInlinedDyno
1764                 << " times based on profile.";
1765     BC.outs() << '\n';
1766   }
1767   return Error::success();
1768 }
1769 
1770 bool SpecializeMemcpy1::shouldOptimize(const BinaryFunction &Function) const {
1771   if (!BinaryFunctionPass::shouldOptimize(Function))
1772     return false;
1773 
1774   for (const std::string &FunctionSpec : Spec) {
1775     StringRef FunctionName = StringRef(FunctionSpec).split(':').first;
1776     if (Function.hasNameRegex(FunctionName))
1777       return true;
1778   }
1779 
1780   return false;
1781 }
1782 
1783 std::set<size_t> SpecializeMemcpy1::getCallSitesToOptimize(
1784     const BinaryFunction &Function) const {
1785   StringRef SitesString;
1786   for (const std::string &FunctionSpec : Spec) {
1787     StringRef FunctionName;
1788     std::tie(FunctionName, SitesString) = StringRef(FunctionSpec).split(':');
1789     if (Function.hasNameRegex(FunctionName))
1790       break;
1791     SitesString = "";
1792   }
1793 
1794   std::set<size_t> Sites;
1795   SmallVector<StringRef, 4> SitesVec;
1796   SitesString.split(SitesVec, ':');
1797   for (StringRef SiteString : SitesVec) {
1798     if (SiteString.empty())
1799       continue;
1800     size_t Result;
1801     if (!SiteString.getAsInteger(10, Result))
1802       Sites.emplace(Result);
1803   }
1804 
1805   return Sites;
1806 }
1807 
1808 Error SpecializeMemcpy1::runOnFunctions(BinaryContext &BC) {
1809   if (!BC.isX86())
1810     return Error::success();
1811 
1812   uint64_t NumSpecialized = 0;
1813   uint64_t NumSpecializedDyno = 0;
1814   for (auto &BFI : BC.getBinaryFunctions()) {
1815     BinaryFunction &Function = BFI.second;
1816     if (!shouldOptimize(Function))
1817       continue;
1818 
1819     std::set<size_t> CallsToOptimize = getCallSitesToOptimize(Function);
1820     auto shouldOptimize = [&](size_t N) {
1821       return CallsToOptimize.empty() || CallsToOptimize.count(N);
1822     };
1823 
1824     std::vector<BinaryBasicBlock *> Blocks(Function.pbegin(), Function.pend());
1825     size_t CallSiteID = 0;
1826     for (BinaryBasicBlock *CurBB : Blocks) {
1827       for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
1828         MCInst &Inst = *II;
1829 
1830         if (!BC.MIB->isCall(Inst) || MCPlus::getNumPrimeOperands(Inst) != 1 ||
1831             !Inst.getOperand(0).isExpr())
1832           continue;
1833 
1834         const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(Inst);
1835         if (CalleeSymbol->getName() != "memcpy" &&
1836             CalleeSymbol->getName() != "memcpy@PLT")
1837           continue;
1838 
1839         if (BC.MIB->isTailCall(Inst))
1840           continue;
1841 
1842         ++CallSiteID;
1843 
1844         if (!shouldOptimize(CallSiteID))
1845           continue;
1846 
1847         // Create a copy of a call to memcpy(dest, src, size).
1848         MCInst MemcpyInstr = Inst;
1849 
1850         BinaryBasicBlock *OneByteMemcpyBB = CurBB->splitAt(II);
1851 
1852         BinaryBasicBlock *NextBB = nullptr;
1853         if (OneByteMemcpyBB->getNumNonPseudos() > 1) {
1854           NextBB = OneByteMemcpyBB->splitAt(OneByteMemcpyBB->begin());
1855           NextBB->eraseInstruction(NextBB->begin());
1856         } else {
1857           NextBB = OneByteMemcpyBB->getSuccessor();
1858           OneByteMemcpyBB->eraseInstruction(OneByteMemcpyBB->begin());
1859           assert(NextBB && "unexpected call to memcpy() with no return");
1860         }
1861 
1862         BinaryBasicBlock *MemcpyBB = Function.addBasicBlock();
1863         MemcpyBB->setOffset(CurBB->getInputOffset());
1864         InstructionListType CmpJCC =
1865             BC.MIB->createCmpJE(BC.MIB->getIntArgRegister(2), 1,
1866                                 OneByteMemcpyBB->getLabel(), BC.Ctx.get());
1867         CurBB->addInstructions(CmpJCC);
1868         CurBB->addSuccessor(MemcpyBB);
1869 
1870         MemcpyBB->addInstruction(std::move(MemcpyInstr));
1871         MemcpyBB->addSuccessor(NextBB);
1872         MemcpyBB->setCFIState(NextBB->getCFIState());
1873         MemcpyBB->setExecutionCount(0);
1874 
1875         // To prevent the actual call from being moved to cold, we set its
1876         // execution count to 1.
1877         if (CurBB->getKnownExecutionCount() > 0)
1878           MemcpyBB->setExecutionCount(1);
1879 
1880         InstructionListType OneByteMemcpy = BC.MIB->createOneByteMemcpy();
1881         OneByteMemcpyBB->addInstructions(OneByteMemcpy);
1882 
1883         ++NumSpecialized;
1884         NumSpecializedDyno += CurBB->getKnownExecutionCount();
1885 
1886         CurBB = NextBB;
1887 
1888         // Note: we don't expect the next instruction to be a call to memcpy.
1889         II = CurBB->begin();
1890       }
1891     }
1892   }
1893 
1894   if (NumSpecialized) {
1895     BC.outs() << "BOLT-INFO: specialized " << NumSpecialized
1896               << " memcpy() call sites for size 1";
1897     if (NumSpecializedDyno)
1898       BC.outs() << ". The calls were executed " << NumSpecializedDyno
1899                 << " times based on profile.";
1900     BC.outs() << '\n';
1901   }
1902   return Error::success();
1903 }
1904 
1905 void RemoveNops::runOnFunction(BinaryFunction &BF) {
1906   const BinaryContext &BC = BF.getBinaryContext();
1907   for (BinaryBasicBlock &BB : BF) {
1908     for (int64_t I = BB.size() - 1; I >= 0; --I) {
1909       MCInst &Inst = BB.getInstructionAtIndex(I);
1910       if (BC.MIB->isNoop(Inst) && BC.MIB->hasAnnotation(Inst, "NOP"))
1911         BB.eraseInstructionAtIndex(I);
1912     }
1913   }
1914 }
1915 
1916 Error RemoveNops::runOnFunctions(BinaryContext &BC) {
1917   ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) {
1918     runOnFunction(BF);
1919   };
1920 
1921   ParallelUtilities::PredicateTy SkipFunc = [&](const BinaryFunction &BF) {
1922     return BF.shouldPreserveNops();
1923   };
1924 
1925   ParallelUtilities::runOnEachFunction(
1926       BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun,
1927       SkipFunc, "RemoveNops");
1928   return Error::success();
1929 }
1930 
1931 } // namespace bolt
1932 } // namespace llvm
1933