xref: /llvm-project/bolt/lib/Core/BinaryFunction.cpp (revision 70e76e0982a9dc27b8c252353609e3a778c2bec0)
1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===//
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 BinaryFunction class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/BinaryFunction.h"
14 #include "bolt/Core/BinaryBasicBlock.h"
15 #include "bolt/Core/BinaryDomTree.h"
16 #include "bolt/Core/DynoStats.h"
17 #include "bolt/Core/HashUtilities.h"
18 #include "bolt/Core/MCPlusBuilder.h"
19 #include "bolt/Utils/NameResolver.h"
20 #include "bolt/Utils/NameShortener.h"
21 #include "bolt/Utils/Utils.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Demangle/Demangle.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCAsmLayout.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstPrinter.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Object/ObjectFile.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/Regex.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <functional>
45 #include <limits>
46 #include <numeric>
47 #include <string>
48 
49 #define DEBUG_TYPE "bolt"
50 
51 using namespace llvm;
52 using namespace bolt;
53 
54 namespace opts {
55 
56 extern cl::OptionCategory BoltCategory;
57 extern cl::OptionCategory BoltOptCategory;
58 extern cl::OptionCategory BoltRelocCategory;
59 
60 extern cl::opt<bool> EnableBAT;
61 extern cl::opt<bool> Instrument;
62 extern cl::opt<bool> StrictMode;
63 extern cl::opt<bool> UpdateDebugSections;
64 extern cl::opt<unsigned> Verbosity;
65 
66 extern bool processAllFunctions();
67 
68 cl::opt<bool> CheckEncoding(
69     "check-encoding",
70     cl::desc("perform verification of LLVM instruction encoding/decoding. "
71              "Every instruction in the input is decoded and re-encoded. "
72              "If the resulting bytes do not match the input, a warning message "
73              "is printed."),
74     cl::Hidden, cl::cat(BoltCategory));
75 
76 static cl::opt<bool> DotToolTipCode(
77     "dot-tooltip-code",
78     cl::desc("add basic block instructions as tool tips on nodes"), cl::Hidden,
79     cl::cat(BoltCategory));
80 
81 cl::opt<JumpTableSupportLevel>
82 JumpTables("jump-tables",
83   cl::desc("jump tables support (default=basic)"),
84   cl::init(JTS_BASIC),
85   cl::values(
86       clEnumValN(JTS_NONE, "none",
87                  "do not optimize functions with jump tables"),
88       clEnumValN(JTS_BASIC, "basic",
89                  "optimize functions with jump tables"),
90       clEnumValN(JTS_MOVE, "move",
91                  "move jump tables to a separate section"),
92       clEnumValN(JTS_SPLIT, "split",
93                  "split jump tables section into hot and cold based on "
94                  "function execution frequency"),
95       clEnumValN(JTS_AGGRESSIVE, "aggressive",
96                  "aggressively split jump tables section based on usage "
97                  "of the tables")),
98   cl::ZeroOrMore,
99   cl::cat(BoltOptCategory));
100 
101 static cl::opt<bool> NoScan(
102     "no-scan",
103     cl::desc(
104         "do not scan cold functions for external references (may result in "
105         "slower binary)"),
106     cl::Hidden, cl::cat(BoltOptCategory));
107 
108 cl::opt<bool>
109     PreserveBlocksAlignment("preserve-blocks-alignment",
110                             cl::desc("try to preserve basic block alignment"),
111                             cl::cat(BoltOptCategory));
112 
113 cl::opt<bool>
114 PrintDynoStats("dyno-stats",
115   cl::desc("print execution info based on profile"),
116   cl::cat(BoltCategory));
117 
118 static cl::opt<bool>
119 PrintDynoStatsOnly("print-dyno-stats-only",
120   cl::desc("while printing functions output dyno-stats and skip instructions"),
121   cl::init(false),
122   cl::Hidden,
123   cl::cat(BoltCategory));
124 
125 static cl::list<std::string>
126 PrintOnly("print-only",
127   cl::CommaSeparated,
128   cl::desc("list of functions to print"),
129   cl::value_desc("func1,func2,func3,..."),
130   cl::Hidden,
131   cl::cat(BoltCategory));
132 
133 cl::opt<bool>
134     TimeBuild("time-build",
135               cl::desc("print time spent constructing binary functions"),
136               cl::Hidden, cl::cat(BoltCategory));
137 
138 cl::opt<bool>
139 TrapOnAVX512("trap-avx512",
140   cl::desc("in relocation mode trap upon entry to any function that uses "
141             "AVX-512 instructions"),
142   cl::init(false),
143   cl::ZeroOrMore,
144   cl::Hidden,
145   cl::cat(BoltCategory));
146 
147 bool shouldPrint(const BinaryFunction &Function) {
148   if (Function.isIgnored())
149     return false;
150 
151   if (PrintOnly.empty())
152     return true;
153 
154   for (std::string &Name : opts::PrintOnly) {
155     if (Function.hasNameRegex(Name)) {
156       return true;
157     }
158   }
159 
160   return false;
161 }
162 
163 } // namespace opts
164 
165 namespace llvm {
166 namespace bolt {
167 
168 constexpr unsigned BinaryFunction::MinAlign;
169 
170 template <typename R> static bool emptyRange(const R &Range) {
171   return Range.begin() == Range.end();
172 }
173 
174 /// Gets debug line information for the instruction located at the given
175 /// address in the original binary. The SMLoc's pointer is used
176 /// to point to this information, which is represented by a
177 /// DebugLineTableRowRef. The returned pointer is null if no debug line
178 /// information for this instruction was found.
179 static SMLoc findDebugLineInformationForInstructionAt(
180     uint64_t Address, DWARFUnit *Unit,
181     const DWARFDebugLine::LineTable *LineTable) {
182   // We use the pointer in SMLoc to store an instance of DebugLineTableRowRef,
183   // which occupies 64 bits. Thus, we can only proceed if the struct fits into
184   // the pointer itself.
185   assert(sizeof(decltype(SMLoc().getPointer())) >=
186              sizeof(DebugLineTableRowRef) &&
187          "Cannot fit instruction debug line information into SMLoc's pointer");
188 
189   SMLoc NullResult = DebugLineTableRowRef::NULL_ROW.toSMLoc();
190   uint32_t RowIndex = LineTable->lookupAddress(
191       {Address, object::SectionedAddress::UndefSection});
192   if (RowIndex == LineTable->UnknownRowIndex)
193     return NullResult;
194 
195   assert(RowIndex < LineTable->Rows.size() &&
196          "Line Table lookup returned invalid index.");
197 
198   decltype(SMLoc().getPointer()) Ptr;
199   DebugLineTableRowRef *InstructionLocation =
200       reinterpret_cast<DebugLineTableRowRef *>(&Ptr);
201 
202   InstructionLocation->DwCompileUnitIndex = Unit->getOffset();
203   InstructionLocation->RowIndex = RowIndex + 1;
204 
205   return SMLoc::getFromPointer(Ptr);
206 }
207 
208 static std::string buildSectionName(StringRef Prefix, StringRef Name,
209                                     const BinaryContext &BC) {
210   if (BC.isELF())
211     return (Prefix + Name).str();
212   static NameShortener NS;
213   return (Prefix + Twine(NS.getID(Name))).str();
214 }
215 
216 static raw_ostream &operator<<(raw_ostream &OS,
217                                const BinaryFunction::State State) {
218   switch (State) {
219   case BinaryFunction::State::Empty:         OS << "empty"; break;
220   case BinaryFunction::State::Disassembled:  OS << "disassembled"; break;
221   case BinaryFunction::State::CFG:           OS << "CFG constructed"; break;
222   case BinaryFunction::State::CFG_Finalized: OS << "CFG finalized"; break;
223   case BinaryFunction::State::EmittedCFG:    OS << "emitted with CFG"; break;
224   case BinaryFunction::State::Emitted:       OS << "emitted"; break;
225   }
226 
227   return OS;
228 }
229 
230 std::string BinaryFunction::buildCodeSectionName(StringRef Name,
231                                                  const BinaryContext &BC) {
232   return buildSectionName(BC.isELF() ? ".local.text." : ".l.text.", Name, BC);
233 }
234 
235 std::string BinaryFunction::buildColdCodeSectionName(StringRef Name,
236                                                      const BinaryContext &BC) {
237   return buildSectionName(BC.isELF() ? ".local.cold.text." : ".l.c.text.", Name,
238                           BC);
239 }
240 
241 uint64_t BinaryFunction::Count = 0;
242 
243 std::optional<StringRef>
244 BinaryFunction::hasNameRegex(const StringRef Name) const {
245   const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
246   Regex MatchName(RegexName);
247   return forEachName(
248       [&MatchName](StringRef Name) { return MatchName.match(Name); });
249 }
250 
251 std::optional<StringRef>
252 BinaryFunction::hasRestoredNameRegex(const StringRef Name) const {
253   const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
254   Regex MatchName(RegexName);
255   return forEachName([&MatchName](StringRef Name) {
256     return MatchName.match(NameResolver::restore(Name));
257   });
258 }
259 
260 std::string BinaryFunction::getDemangledName() const {
261   StringRef MangledName = NameResolver::restore(getOneName());
262   return demangle(MangledName.str());
263 }
264 
265 BinaryBasicBlock *
266 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset) {
267   if (Offset > Size)
268     return nullptr;
269 
270   if (BasicBlockOffsets.empty())
271     return nullptr;
272 
273   /*
274    * This is commented out because it makes BOLT too slow.
275    * assert(std::is_sorted(BasicBlockOffsets.begin(),
276    *                       BasicBlockOffsets.end(),
277    *                       CompareBasicBlockOffsets())));
278    */
279   auto I =
280       llvm::upper_bound(BasicBlockOffsets, BasicBlockOffset(Offset, nullptr),
281                         CompareBasicBlockOffsets());
282   assert(I != BasicBlockOffsets.begin() && "first basic block not at offset 0");
283   --I;
284   BinaryBasicBlock *BB = I->second;
285   return (Offset < BB->getOffset() + BB->getOriginalSize()) ? BB : nullptr;
286 }
287 
288 void BinaryFunction::markUnreachableBlocks() {
289   std::stack<BinaryBasicBlock *> Stack;
290 
291   for (BinaryBasicBlock &BB : blocks())
292     BB.markValid(false);
293 
294   // Add all entries and landing pads as roots.
295   for (BinaryBasicBlock *BB : BasicBlocks) {
296     if (isEntryPoint(*BB) || BB->isLandingPad()) {
297       Stack.push(BB);
298       BB->markValid(true);
299       continue;
300     }
301     // FIXME:
302     // Also mark BBs with indirect jumps as reachable, since we do not
303     // support removing unused jump tables yet (GH-issue20).
304     for (const MCInst &Inst : *BB) {
305       if (BC.MIB->getJumpTable(Inst)) {
306         Stack.push(BB);
307         BB->markValid(true);
308         break;
309       }
310     }
311   }
312 
313   // Determine reachable BBs from the entry point
314   while (!Stack.empty()) {
315     BinaryBasicBlock *BB = Stack.top();
316     Stack.pop();
317     for (BinaryBasicBlock *Succ : BB->successors()) {
318       if (Succ->isValid())
319         continue;
320       Succ->markValid(true);
321       Stack.push(Succ);
322     }
323   }
324 }
325 
326 // Any unnecessary fallthrough jumps revealed after calling eraseInvalidBBs
327 // will be cleaned up by fixBranches().
328 std::pair<unsigned, uint64_t> BinaryFunction::eraseInvalidBBs() {
329   DenseSet<const BinaryBasicBlock *> InvalidBBs;
330   unsigned Count = 0;
331   uint64_t Bytes = 0;
332   for (BinaryBasicBlock *const BB : BasicBlocks) {
333     if (!BB->isValid()) {
334       assert(!isEntryPoint(*BB) && "all entry blocks must be valid");
335       InvalidBBs.insert(BB);
336       ++Count;
337       Bytes += BC.computeCodeSize(BB->begin(), BB->end());
338     }
339   }
340 
341   Layout.eraseBasicBlocks(InvalidBBs);
342 
343   BasicBlockListType NewBasicBlocks;
344   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
345     BinaryBasicBlock *BB = *I;
346     if (InvalidBBs.contains(BB)) {
347       // Make sure the block is removed from the list of predecessors.
348       BB->removeAllSuccessors();
349       DeletedBasicBlocks.push_back(BB);
350     } else {
351       NewBasicBlocks.push_back(BB);
352     }
353   }
354   BasicBlocks = std::move(NewBasicBlocks);
355 
356   assert(BasicBlocks.size() == Layout.block_size());
357 
358   // Update CFG state if needed
359   if (Count > 0)
360     recomputeLandingPads();
361 
362   return std::make_pair(Count, Bytes);
363 }
364 
365 bool BinaryFunction::isForwardCall(const MCSymbol *CalleeSymbol) const {
366   // This function should work properly before and after function reordering.
367   // In order to accomplish this, we use the function index (if it is valid).
368   // If the function indices are not valid, we fall back to the original
369   // addresses.  This should be ok because the functions without valid indices
370   // should have been ordered with a stable sort.
371   const BinaryFunction *CalleeBF = BC.getFunctionForSymbol(CalleeSymbol);
372   if (CalleeBF) {
373     if (CalleeBF->isInjected())
374       return true;
375 
376     if (hasValidIndex() && CalleeBF->hasValidIndex()) {
377       return getIndex() < CalleeBF->getIndex();
378     } else if (hasValidIndex() && !CalleeBF->hasValidIndex()) {
379       return true;
380     } else if (!hasValidIndex() && CalleeBF->hasValidIndex()) {
381       return false;
382     } else {
383       return getAddress() < CalleeBF->getAddress();
384     }
385   } else {
386     // Absolute symbol.
387     ErrorOr<uint64_t> CalleeAddressOrError = BC.getSymbolValue(*CalleeSymbol);
388     assert(CalleeAddressOrError && "unregistered symbol found");
389     return *CalleeAddressOrError > getAddress();
390   }
391 }
392 
393 void BinaryFunction::dump() const {
394   // getDynoStats calls FunctionLayout::updateLayoutIndices and
395   // BasicBlock::analyzeBranch. The former cannot be const, but should be
396   // removed, the latter should be made const, but seems to require refactoring.
397   // Forcing all callers to have a non-const reference to BinaryFunction to call
398   // dump non-const however is not ideal either. Adding this const_cast is right
399   // now the best solution. It is safe, because BinaryFunction itself is not
400   // modified. Only BinaryBasicBlocks are actually modified (if it all) and we
401   // have mutable pointers to those regardless whether this function is
402   // const-qualified or not.
403   const_cast<BinaryFunction &>(*this).print(dbgs(), "");
404 }
405 
406 void BinaryFunction::print(raw_ostream &OS, std::string Annotation) {
407   if (!opts::shouldPrint(*this))
408     return;
409 
410   StringRef SectionName =
411       OriginSection ? OriginSection->getName() : "<no origin section>";
412   OS << "Binary Function \"" << *this << "\" " << Annotation << " {";
413   std::vector<StringRef> AllNames = getNames();
414   if (AllNames.size() > 1) {
415     OS << "\n  All names   : ";
416     const char *Sep = "";
417     for (const StringRef &Name : AllNames) {
418       OS << Sep << Name;
419       Sep = "\n                ";
420     }
421   }
422   OS << "\n  Number      : " << FunctionNumber;
423   OS << "\n  State       : " << CurrentState;
424   OS << "\n  Address     : 0x" << Twine::utohexstr(Address);
425   OS << "\n  Size        : 0x" << Twine::utohexstr(Size);
426   OS << "\n  MaxSize     : 0x" << Twine::utohexstr(MaxSize);
427   OS << "\n  Offset      : 0x" << Twine::utohexstr(getFileOffset());
428   OS << "\n  Section     : " << SectionName;
429   OS << "\n  Orc Section : " << getCodeSectionName();
430   OS << "\n  LSDA        : 0x" << Twine::utohexstr(getLSDAAddress());
431   OS << "\n  IsSimple    : " << IsSimple;
432   OS << "\n  IsMultiEntry: " << isMultiEntry();
433   OS << "\n  IsSplit     : " << isSplit();
434   OS << "\n  BB Count    : " << size();
435 
436   if (HasFixedIndirectBranch)
437     OS << "\n  HasFixedIndirectBranch : true";
438   if (HasUnknownControlFlow)
439     OS << "\n  Unknown CF  : true";
440   if (getPersonalityFunction())
441     OS << "\n  Personality : " << getPersonalityFunction()->getName();
442   if (IsFragment)
443     OS << "\n  IsFragment  : true";
444   if (isFolded())
445     OS << "\n  FoldedInto  : " << *getFoldedIntoFunction();
446   for (BinaryFunction *ParentFragment : ParentFragments)
447     OS << "\n  Parent      : " << *ParentFragment;
448   if (!Fragments.empty()) {
449     OS << "\n  Fragments   : ";
450     ListSeparator LS;
451     for (BinaryFunction *Frag : Fragments)
452       OS << LS << *Frag;
453   }
454   if (hasCFG())
455     OS << "\n  Hash        : " << Twine::utohexstr(computeHash());
456   if (isMultiEntry()) {
457     OS << "\n  Secondary Entry Points : ";
458     ListSeparator LS;
459     for (const auto &KV : SecondaryEntryPoints)
460       OS << LS << KV.second->getName();
461   }
462   if (FrameInstructions.size())
463     OS << "\n  CFI Instrs  : " << FrameInstructions.size();
464   if (!Layout.block_empty()) {
465     OS << "\n  BB Layout   : ";
466     ListSeparator LS;
467     for (const BinaryBasicBlock *BB : Layout.blocks())
468       OS << LS << BB->getName();
469   }
470   if (getImageAddress())
471     OS << "\n  Image       : 0x" << Twine::utohexstr(getImageAddress());
472   if (ExecutionCount != COUNT_NO_PROFILE) {
473     OS << "\n  Exec Count  : " << ExecutionCount;
474     OS << "\n  Branch Count: " << RawBranchCount;
475     OS << "\n  Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f);
476   }
477 
478   if (opts::PrintDynoStats && !getLayout().block_empty()) {
479     OS << '\n';
480     DynoStats dynoStats = getDynoStats(*this);
481     OS << dynoStats;
482   }
483 
484   OS << "\n}\n";
485 
486   if (opts::PrintDynoStatsOnly || !BC.InstPrinter)
487     return;
488 
489   // Offset of the instruction in function.
490   uint64_t Offset = 0;
491 
492   if (BasicBlocks.empty() && !Instructions.empty()) {
493     // Print before CFG was built.
494     for (const std::pair<const uint32_t, MCInst> &II : Instructions) {
495       Offset = II.first;
496 
497       // Print label if exists at this offset.
498       auto LI = Labels.find(Offset);
499       if (LI != Labels.end()) {
500         if (const MCSymbol *EntrySymbol =
501                 getSecondaryEntryPointSymbol(LI->second))
502           OS << EntrySymbol->getName() << " (Entry Point):\n";
503         OS << LI->second->getName() << ":\n";
504       }
505 
506       BC.printInstruction(OS, II.second, Offset, this);
507     }
508   }
509 
510   StringRef SplitPointMsg = "";
511   for (const FunctionFragment &FF : Layout.fragments()) {
512     OS << SplitPointMsg;
513     SplitPointMsg = "-------   HOT-COLD SPLIT POINT   -------\n\n";
514     for (const BinaryBasicBlock *BB : FF) {
515       OS << BB->getName() << " (" << BB->size()
516          << " instructions, align : " << BB->getAlignment() << ")\n";
517 
518       if (isEntryPoint(*BB)) {
519         if (MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB))
520           OS << "  Secondary Entry Point: " << EntrySymbol->getName() << '\n';
521         else
522           OS << "  Entry Point\n";
523       }
524 
525       if (BB->isLandingPad())
526         OS << "  Landing Pad\n";
527 
528       uint64_t BBExecCount = BB->getExecutionCount();
529       if (hasValidProfile()) {
530         OS << "  Exec Count : ";
531         if (BB->getExecutionCount() != BinaryBasicBlock::COUNT_NO_PROFILE)
532           OS << BBExecCount << '\n';
533         else
534           OS << "<unknown>\n";
535       }
536       if (BB->getCFIState() >= 0)
537         OS << "  CFI State : " << BB->getCFIState() << '\n';
538       if (opts::EnableBAT) {
539         OS << "  Input offset: " << Twine::utohexstr(BB->getInputOffset())
540            << "\n";
541       }
542       if (!BB->pred_empty()) {
543         OS << "  Predecessors: ";
544         ListSeparator LS;
545         for (BinaryBasicBlock *Pred : BB->predecessors())
546           OS << LS << Pred->getName();
547         OS << '\n';
548       }
549       if (!BB->throw_empty()) {
550         OS << "  Throwers: ";
551         ListSeparator LS;
552         for (BinaryBasicBlock *Throw : BB->throwers())
553           OS << LS << Throw->getName();
554         OS << '\n';
555       }
556 
557       Offset = alignTo(Offset, BB->getAlignment());
558 
559       // Note: offsets are imprecise since this is happening prior to
560       // relaxation.
561       Offset = BC.printInstructions(OS, BB->begin(), BB->end(), Offset, this);
562 
563       if (!BB->succ_empty()) {
564         OS << "  Successors: ";
565         // For more than 2 successors, sort them based on frequency.
566         std::vector<uint64_t> Indices(BB->succ_size());
567         std::iota(Indices.begin(), Indices.end(), 0);
568         if (BB->succ_size() > 2 && BB->getKnownExecutionCount()) {
569           llvm::stable_sort(Indices, [&](const uint64_t A, const uint64_t B) {
570             return BB->BranchInfo[B] < BB->BranchInfo[A];
571           });
572         }
573         ListSeparator LS;
574         for (unsigned I = 0; I < Indices.size(); ++I) {
575           BinaryBasicBlock *Succ = BB->Successors[Indices[I]];
576           const BinaryBasicBlock::BinaryBranchInfo &BI =
577               BB->BranchInfo[Indices[I]];
578           OS << LS << Succ->getName();
579           if (ExecutionCount != COUNT_NO_PROFILE &&
580               BI.MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
581             OS << " (mispreds: " << BI.MispredictedCount
582                << ", count: " << BI.Count << ")";
583           } else if (ExecutionCount != COUNT_NO_PROFILE &&
584                      BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
585             OS << " (inferred count: " << BI.Count << ")";
586           }
587         }
588         OS << '\n';
589       }
590 
591       if (!BB->lp_empty()) {
592         OS << "  Landing Pads: ";
593         ListSeparator LS;
594         for (BinaryBasicBlock *LP : BB->landing_pads()) {
595           OS << LS << LP->getName();
596           if (ExecutionCount != COUNT_NO_PROFILE) {
597             OS << " (count: " << LP->getExecutionCount() << ")";
598           }
599         }
600         OS << '\n';
601       }
602 
603       // In CFG_Finalized state we can miscalculate CFI state at exit.
604       if (CurrentState == State::CFG) {
605         const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
606         if (CFIStateAtExit >= 0)
607           OS << "  CFI State: " << CFIStateAtExit << '\n';
608       }
609 
610       OS << '\n';
611     }
612   }
613 
614   // Dump new exception ranges for the function.
615   if (!CallSites.empty()) {
616     OS << "EH table:\n";
617     for (const FunctionFragment &FF : getLayout().fragments()) {
618       for (const auto &FCSI : getCallSites(FF.getFragmentNum())) {
619         const CallSite &CSI = FCSI.second;
620         OS << "  [" << *CSI.Start << ", " << *CSI.End << ") landing pad : ";
621         if (CSI.LP)
622           OS << *CSI.LP;
623         else
624           OS << "0";
625         OS << ", action : " << CSI.Action << '\n';
626       }
627     }
628     OS << '\n';
629   }
630 
631   // Print all jump tables.
632   for (const std::pair<const uint64_t, JumpTable *> &JTI : JumpTables)
633     JTI.second->print(OS);
634 
635   OS << "DWARF CFI Instructions:\n";
636   if (OffsetToCFI.size()) {
637     // Pre-buildCFG information
638     for (const std::pair<const uint32_t, uint32_t> &Elmt : OffsetToCFI) {
639       OS << format("    %08x:\t", Elmt.first);
640       assert(Elmt.second < FrameInstructions.size() && "Incorrect CFI offset");
641       BinaryContext::printCFI(OS, FrameInstructions[Elmt.second]);
642       OS << "\n";
643     }
644   } else {
645     // Post-buildCFG information
646     for (uint32_t I = 0, E = FrameInstructions.size(); I != E; ++I) {
647       const MCCFIInstruction &CFI = FrameInstructions[I];
648       OS << format("    %d:\t", I);
649       BinaryContext::printCFI(OS, CFI);
650       OS << "\n";
651     }
652   }
653   if (FrameInstructions.empty())
654     OS << "    <empty>\n";
655 
656   OS << "End of Function \"" << *this << "\"\n\n";
657 }
658 
659 void BinaryFunction::printRelocations(raw_ostream &OS, uint64_t Offset,
660                                       uint64_t Size) const {
661   const char *Sep = " # Relocs: ";
662 
663   auto RI = Relocations.lower_bound(Offset);
664   while (RI != Relocations.end() && RI->first < Offset + Size) {
665     OS << Sep << "(R: " << RI->second << ")";
666     Sep = ", ";
667     ++RI;
668   }
669 }
670 
671 static std::string mutateDWARFExpressionTargetReg(const MCCFIInstruction &Instr,
672                                                   MCPhysReg NewReg) {
673   StringRef ExprBytes = Instr.getValues();
674   assert(ExprBytes.size() > 1 && "DWARF expression CFI is too short");
675   uint8_t Opcode = ExprBytes[0];
676   assert((Opcode == dwarf::DW_CFA_expression ||
677           Opcode == dwarf::DW_CFA_val_expression) &&
678          "invalid DWARF expression CFI");
679   (void)Opcode;
680   const uint8_t *const Start =
681       reinterpret_cast<const uint8_t *>(ExprBytes.drop_front(1).data());
682   const uint8_t *const End =
683       reinterpret_cast<const uint8_t *>(Start + ExprBytes.size() - 1);
684   unsigned Size = 0;
685   decodeULEB128(Start, &Size, End);
686   assert(Size > 0 && "Invalid reg encoding for DWARF expression CFI");
687   SmallString<8> Tmp;
688   raw_svector_ostream OSE(Tmp);
689   encodeULEB128(NewReg, OSE);
690   return Twine(ExprBytes.slice(0, 1))
691       .concat(OSE.str())
692       .concat(ExprBytes.drop_front(1 + Size))
693       .str();
694 }
695 
696 void BinaryFunction::mutateCFIRegisterFor(const MCInst &Instr,
697                                           MCPhysReg NewReg) {
698   const MCCFIInstruction *OldCFI = getCFIFor(Instr);
699   assert(OldCFI && "invalid CFI instr");
700   switch (OldCFI->getOperation()) {
701   default:
702     llvm_unreachable("Unexpected instruction");
703   case MCCFIInstruction::OpDefCfa:
704     setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, NewReg,
705                                                  OldCFI->getOffset()));
706     break;
707   case MCCFIInstruction::OpDefCfaRegister:
708     setCFIFor(Instr, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg));
709     break;
710   case MCCFIInstruction::OpOffset:
711     setCFIFor(Instr, MCCFIInstruction::createOffset(nullptr, NewReg,
712                                                     OldCFI->getOffset()));
713     break;
714   case MCCFIInstruction::OpRegister:
715     setCFIFor(Instr, MCCFIInstruction::createRegister(nullptr, NewReg,
716                                                       OldCFI->getRegister2()));
717     break;
718   case MCCFIInstruction::OpSameValue:
719     setCFIFor(Instr, MCCFIInstruction::createSameValue(nullptr, NewReg));
720     break;
721   case MCCFIInstruction::OpEscape:
722     setCFIFor(Instr,
723               MCCFIInstruction::createEscape(
724                   nullptr,
725                   StringRef(mutateDWARFExpressionTargetReg(*OldCFI, NewReg))));
726     break;
727   case MCCFIInstruction::OpRestore:
728     setCFIFor(Instr, MCCFIInstruction::createRestore(nullptr, NewReg));
729     break;
730   case MCCFIInstruction::OpUndefined:
731     setCFIFor(Instr, MCCFIInstruction::createUndefined(nullptr, NewReg));
732     break;
733   }
734 }
735 
736 const MCCFIInstruction *BinaryFunction::mutateCFIOffsetFor(const MCInst &Instr,
737                                                            int64_t NewOffset) {
738   const MCCFIInstruction *OldCFI = getCFIFor(Instr);
739   assert(OldCFI && "invalid CFI instr");
740   switch (OldCFI->getOperation()) {
741   default:
742     llvm_unreachable("Unexpected instruction");
743   case MCCFIInstruction::OpDefCfaOffset:
744     setCFIFor(Instr, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset));
745     break;
746   case MCCFIInstruction::OpAdjustCfaOffset:
747     setCFIFor(Instr,
748               MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset));
749     break;
750   case MCCFIInstruction::OpDefCfa:
751     setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI->getRegister(),
752                                                  NewOffset));
753     break;
754   case MCCFIInstruction::OpOffset:
755     setCFIFor(Instr, MCCFIInstruction::createOffset(
756                          nullptr, OldCFI->getRegister(), NewOffset));
757     break;
758   }
759   return getCFIFor(Instr);
760 }
761 
762 IndirectBranchType
763 BinaryFunction::processIndirectBranch(MCInst &Instruction, unsigned Size,
764                                       uint64_t Offset,
765                                       uint64_t &TargetAddress) {
766   const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
767 
768   // The instruction referencing memory used by the branch instruction.
769   // It could be the branch instruction itself or one of the instructions
770   // setting the value of the register used by the branch.
771   MCInst *MemLocInstr;
772 
773   // Address of the table referenced by MemLocInstr. Could be either an
774   // array of function pointers, or a jump table.
775   uint64_t ArrayStart = 0;
776 
777   unsigned BaseRegNum, IndexRegNum;
778   int64_t DispValue;
779   const MCExpr *DispExpr;
780 
781   // In AArch, identify the instruction adding the PC-relative offset to
782   // jump table entries to correctly decode it.
783   MCInst *PCRelBaseInstr;
784   uint64_t PCRelAddr = 0;
785 
786   auto Begin = Instructions.begin();
787   if (BC.isAArch64()) {
788     PreserveNops = BC.HasRelocations;
789     // Start at the last label as an approximation of the current basic block.
790     // This is a heuristic, since the full set of labels have yet to be
791     // determined
792     for (const uint32_t Offset :
793          llvm::make_first_range(llvm::reverse(Labels))) {
794       auto II = Instructions.find(Offset);
795       if (II != Instructions.end()) {
796         Begin = II;
797         break;
798       }
799     }
800   }
801 
802   IndirectBranchType BranchType = BC.MIB->analyzeIndirectBranch(
803       Instruction, Begin, Instructions.end(), PtrSize, MemLocInstr, BaseRegNum,
804       IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
805 
806   if (BranchType == IndirectBranchType::UNKNOWN && !MemLocInstr)
807     return BranchType;
808 
809   if (MemLocInstr != &Instruction)
810     IndexRegNum = BC.MIB->getNoRegister();
811 
812   if (BC.isAArch64()) {
813     const MCSymbol *Sym = BC.MIB->getTargetSymbol(*PCRelBaseInstr, 1);
814     assert(Sym && "Symbol extraction failed");
815     ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*Sym);
816     if (SymValueOrError) {
817       PCRelAddr = *SymValueOrError;
818     } else {
819       for (std::pair<const uint32_t, MCSymbol *> &Elmt : Labels) {
820         if (Elmt.second == Sym) {
821           PCRelAddr = Elmt.first + getAddress();
822           break;
823         }
824       }
825     }
826     uint64_t InstrAddr = 0;
827     for (auto II = Instructions.rbegin(); II != Instructions.rend(); ++II) {
828       if (&II->second == PCRelBaseInstr) {
829         InstrAddr = II->first + getAddress();
830         break;
831       }
832     }
833     assert(InstrAddr != 0 && "instruction not found");
834     // We do this to avoid spurious references to code locations outside this
835     // function (for example, if the indirect jump lives in the last basic
836     // block of the function, it will create a reference to the next function).
837     // This replaces a symbol reference with an immediate.
838     BC.MIB->replaceMemOperandDisp(*PCRelBaseInstr,
839                                   MCOperand::createImm(PCRelAddr - InstrAddr));
840     // FIXME: Disable full jump table processing for AArch64 until we have a
841     // proper way of determining the jump table limits.
842     return IndirectBranchType::UNKNOWN;
843   }
844 
845   // RIP-relative addressing should be converted to symbol form by now
846   // in processed instructions (but not in jump).
847   if (DispExpr) {
848     const MCSymbol *TargetSym;
849     uint64_t TargetOffset;
850     std::tie(TargetSym, TargetOffset) = BC.MIB->getTargetSymbolInfo(DispExpr);
851     ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*TargetSym);
852     assert(SymValueOrError && "global symbol needs a value");
853     ArrayStart = *SymValueOrError + TargetOffset;
854     BaseRegNum = BC.MIB->getNoRegister();
855     if (BC.isAArch64()) {
856       ArrayStart &= ~0xFFFULL;
857       ArrayStart += DispValue & 0xFFFULL;
858     }
859   } else {
860     ArrayStart = static_cast<uint64_t>(DispValue);
861   }
862 
863   if (BaseRegNum == BC.MRI->getProgramCounter())
864     ArrayStart += getAddress() + Offset + Size;
865 
866   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addressed memory is 0x"
867                     << Twine::utohexstr(ArrayStart) << '\n');
868 
869   ErrorOr<BinarySection &> Section = BC.getSectionForAddress(ArrayStart);
870   if (!Section) {
871     // No section - possibly an absolute address. Since we don't allow
872     // internal function addresses to escape the function scope - we
873     // consider it a tail call.
874     if (opts::Verbosity >= 1) {
875       errs() << "BOLT-WARNING: no section for address 0x"
876              << Twine::utohexstr(ArrayStart) << " referenced from function "
877              << *this << '\n';
878     }
879     return IndirectBranchType::POSSIBLE_TAIL_CALL;
880   }
881   if (Section->isVirtual()) {
882     // The contents are filled at runtime.
883     return IndirectBranchType::POSSIBLE_TAIL_CALL;
884   }
885 
886   if (BranchType == IndirectBranchType::POSSIBLE_FIXED_BRANCH) {
887     ErrorOr<uint64_t> Value = BC.getPointerAtAddress(ArrayStart);
888     if (!Value)
889       return IndirectBranchType::UNKNOWN;
890 
891     if (BC.getSectionForAddress(ArrayStart)->isWritable())
892       return IndirectBranchType::UNKNOWN;
893 
894     outs() << "BOLT-INFO: fixed indirect branch detected in " << *this
895            << " at 0x" << Twine::utohexstr(getAddress() + Offset)
896            << " referencing data at 0x" << Twine::utohexstr(ArrayStart)
897            << " the destination value is 0x" << Twine::utohexstr(*Value)
898            << '\n';
899 
900     TargetAddress = *Value;
901     return BranchType;
902   }
903 
904   // Check if there's already a jump table registered at this address.
905   MemoryContentsType MemType;
906   if (JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart)) {
907     switch (JT->Type) {
908     case JumpTable::JTT_NORMAL:
909       MemType = MemoryContentsType::POSSIBLE_JUMP_TABLE;
910       break;
911     case JumpTable::JTT_PIC:
912       MemType = MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
913       break;
914     }
915   } else {
916     MemType = BC.analyzeMemoryAt(ArrayStart, *this);
917   }
918 
919   // Check that jump table type in instruction pattern matches memory contents.
920   JumpTable::JumpTableType JTType;
921   if (BranchType == IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE) {
922     if (MemType != MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
923       return IndirectBranchType::UNKNOWN;
924     JTType = JumpTable::JTT_PIC;
925   } else {
926     if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
927       return IndirectBranchType::UNKNOWN;
928 
929     if (MemType == MemoryContentsType::UNKNOWN)
930       return IndirectBranchType::POSSIBLE_TAIL_CALL;
931 
932     BranchType = IndirectBranchType::POSSIBLE_JUMP_TABLE;
933     JTType = JumpTable::JTT_NORMAL;
934   }
935 
936   // Convert the instruction into jump table branch.
937   const MCSymbol *JTLabel = BC.getOrCreateJumpTable(*this, ArrayStart, JTType);
938   BC.MIB->replaceMemOperandDisp(*MemLocInstr, JTLabel, BC.Ctx.get());
939   BC.MIB->setJumpTable(Instruction, ArrayStart, IndexRegNum);
940 
941   JTSites.emplace_back(Offset, ArrayStart);
942 
943   return BranchType;
944 }
945 
946 MCSymbol *BinaryFunction::getOrCreateLocalLabel(uint64_t Address,
947                                                 bool CreatePastEnd) {
948   const uint64_t Offset = Address - getAddress();
949 
950   if ((Offset == getSize()) && CreatePastEnd)
951     return getFunctionEndLabel();
952 
953   auto LI = Labels.find(Offset);
954   if (LI != Labels.end())
955     return LI->second;
956 
957   // For AArch64, check if this address is part of a constant island.
958   if (BC.isAArch64()) {
959     if (MCSymbol *IslandSym = getOrCreateIslandAccess(Address))
960       return IslandSym;
961   }
962 
963   MCSymbol *Label = BC.Ctx->createNamedTempSymbol();
964   Labels[Offset] = Label;
965 
966   return Label;
967 }
968 
969 ErrorOr<ArrayRef<uint8_t>> BinaryFunction::getData() const {
970   BinarySection &Section = *getOriginSection();
971   assert(Section.containsRange(getAddress(), getMaxSize()) &&
972          "wrong section for function");
973 
974   if (!Section.isText() || Section.isVirtual() || !Section.getSize())
975     return std::make_error_code(std::errc::bad_address);
976 
977   StringRef SectionContents = Section.getContents();
978 
979   assert(SectionContents.size() == Section.getSize() &&
980          "section size mismatch");
981 
982   // Function offset from the section start.
983   uint64_t Offset = getAddress() - Section.getAddress();
984   auto *Bytes = reinterpret_cast<const uint8_t *>(SectionContents.data());
985   return ArrayRef<uint8_t>(Bytes + Offset, getMaxSize());
986 }
987 
988 size_t BinaryFunction::getSizeOfDataInCodeAt(uint64_t Offset) const {
989   if (!Islands)
990     return 0;
991 
992   if (!llvm::is_contained(Islands->DataOffsets, Offset))
993     return 0;
994 
995   auto Iter = Islands->CodeOffsets.upper_bound(Offset);
996   if (Iter != Islands->CodeOffsets.end())
997     return *Iter - Offset;
998   return getSize() - Offset;
999 }
1000 
1001 bool BinaryFunction::isZeroPaddingAt(uint64_t Offset) const {
1002   ArrayRef<uint8_t> FunctionData = *getData();
1003   uint64_t EndOfCode = getSize();
1004   if (Islands) {
1005     auto Iter = Islands->DataOffsets.upper_bound(Offset);
1006     if (Iter != Islands->DataOffsets.end())
1007       EndOfCode = *Iter;
1008   }
1009   for (uint64_t I = Offset; I < EndOfCode; ++I)
1010     if (FunctionData[I] != 0)
1011       return false;
1012 
1013   return true;
1014 }
1015 
1016 void BinaryFunction::handlePCRelOperand(MCInst &Instruction, uint64_t Address,
1017                                         uint64_t Size) {
1018   auto &MIB = BC.MIB;
1019   uint64_t TargetAddress = 0;
1020   if (!MIB->evaluateMemOperandTarget(Instruction, TargetAddress, Address,
1021                                      Size)) {
1022     errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
1023     BC.InstPrinter->printInst(&Instruction, 0, "", *BC.STI, errs());
1024     errs() << '\n';
1025     Instruction.dump_pretty(errs(), BC.InstPrinter.get());
1026     errs() << '\n';
1027     errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
1028            << Twine::utohexstr(Address) << ". Skipping function " << *this
1029            << ".\n";
1030     if (BC.HasRelocations)
1031       exit(1);
1032     IsSimple = false;
1033     return;
1034   }
1035   if (TargetAddress == 0 && opts::Verbosity >= 1) {
1036     outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
1037            << '\n';
1038   }
1039 
1040   const MCSymbol *TargetSymbol;
1041   uint64_t TargetOffset;
1042   std::tie(TargetSymbol, TargetOffset) =
1043       BC.handleAddressRef(TargetAddress, *this, /*IsPCRel*/ true);
1044 
1045   bool ReplaceSuccess = MIB->replaceMemOperandDisp(
1046       Instruction, TargetSymbol, static_cast<int64_t>(TargetOffset), &*BC.Ctx);
1047   (void)ReplaceSuccess;
1048   assert(ReplaceSuccess && "Failed to replace mem operand with symbol+off.");
1049 }
1050 
1051 MCSymbol *BinaryFunction::handleExternalReference(MCInst &Instruction,
1052                                                   uint64_t Size,
1053                                                   uint64_t Offset,
1054                                                   uint64_t TargetAddress,
1055                                                   bool &IsCall) {
1056   auto &MIB = BC.MIB;
1057 
1058   const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1059   BC.addInterproceduralReference(this, TargetAddress);
1060   if (opts::Verbosity >= 2 && !IsCall && Size == 2 && !BC.HasRelocations) {
1061     errs() << "BOLT-WARNING: relaxed tail call detected at 0x"
1062            << Twine::utohexstr(AbsoluteInstrAddr) << " in function " << *this
1063            << ". Code size will be increased.\n";
1064   }
1065 
1066   assert(!MIB->isTailCall(Instruction) &&
1067          "synthetic tail call instruction found");
1068 
1069   // This is a call regardless of the opcode.
1070   // Assign proper opcode for tail calls, so that they could be
1071   // treated as calls.
1072   if (!IsCall) {
1073     if (!MIB->convertJmpToTailCall(Instruction)) {
1074       assert(MIB->isConditionalBranch(Instruction) &&
1075              "unknown tail call instruction");
1076       if (opts::Verbosity >= 2) {
1077         errs() << "BOLT-WARNING: conditional tail call detected in "
1078                << "function " << *this << " at 0x"
1079                << Twine::utohexstr(AbsoluteInstrAddr) << ".\n";
1080       }
1081     }
1082     IsCall = true;
1083   }
1084 
1085   if (opts::Verbosity >= 2 && TargetAddress == 0) {
1086     // We actually see calls to address 0 in presence of weak
1087     // symbols originating from libraries. This code is never meant
1088     // to be executed.
1089     outs() << "BOLT-INFO: Function " << *this
1090            << " has a call to address zero.\n";
1091   }
1092 
1093   return BC.getOrCreateGlobalSymbol(TargetAddress, "FUNCat");
1094 }
1095 
1096 void BinaryFunction::handleIndirectBranch(MCInst &Instruction, uint64_t Size,
1097                                           uint64_t Offset) {
1098   auto &MIB = BC.MIB;
1099   uint64_t IndirectTarget = 0;
1100   IndirectBranchType Result =
1101       processIndirectBranch(Instruction, Size, Offset, IndirectTarget);
1102   switch (Result) {
1103   default:
1104     llvm_unreachable("unexpected result");
1105   case IndirectBranchType::POSSIBLE_TAIL_CALL: {
1106     bool Result = MIB->convertJmpToTailCall(Instruction);
1107     (void)Result;
1108     assert(Result);
1109     break;
1110   }
1111   case IndirectBranchType::POSSIBLE_JUMP_TABLE:
1112   case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE:
1113     if (opts::JumpTables == JTS_NONE)
1114       IsSimple = false;
1115     break;
1116   case IndirectBranchType::POSSIBLE_FIXED_BRANCH: {
1117     if (containsAddress(IndirectTarget)) {
1118       const MCSymbol *TargetSymbol = getOrCreateLocalLabel(IndirectTarget);
1119       Instruction.clear();
1120       MIB->createUncondBranch(Instruction, TargetSymbol, BC.Ctx.get());
1121       TakenBranches.emplace_back(Offset, IndirectTarget - getAddress());
1122       HasFixedIndirectBranch = true;
1123     } else {
1124       MIB->convertJmpToTailCall(Instruction);
1125       BC.addInterproceduralReference(this, IndirectTarget);
1126     }
1127     break;
1128   }
1129   case IndirectBranchType::UNKNOWN:
1130     // Keep processing. We'll do more checks and fixes in
1131     // postProcessIndirectBranches().
1132     UnknownIndirectBranchOffsets.emplace(Offset);
1133     break;
1134   }
1135 }
1136 
1137 void BinaryFunction::handleAArch64IndirectCall(MCInst &Instruction,
1138                                                const uint64_t Offset) {
1139   auto &MIB = BC.MIB;
1140   const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1141   MCInst *TargetHiBits, *TargetLowBits;
1142   uint64_t TargetAddress, Count;
1143   Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1144                                  AbsoluteInstrAddr, Instruction, TargetHiBits,
1145                                  TargetLowBits, TargetAddress);
1146   if (Count) {
1147     MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1148     --Count;
1149     for (auto It = std::prev(Instructions.end()); Count != 0;
1150          It = std::prev(It), --Count) {
1151       MIB->addAnnotation(It->second, "AArch64Veneer", true);
1152     }
1153 
1154     BC.addAdrpAddRelocAArch64(*this, *TargetLowBits, *TargetHiBits,
1155                               TargetAddress);
1156   }
1157 }
1158 
1159 bool BinaryFunction::disassemble() {
1160   NamedRegionTimer T("disassemble", "Disassemble function", "buildfuncs",
1161                      "Build Binary Functions", opts::TimeBuild);
1162   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1163   assert(ErrorOrFunctionData && "function data is not available");
1164   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1165   assert(FunctionData.size() == getMaxSize() &&
1166          "function size does not match raw data size");
1167 
1168   auto &Ctx = BC.Ctx;
1169   auto &MIB = BC.MIB;
1170 
1171   BC.SymbolicDisAsm->setSymbolizer(MIB->createTargetSymbolizer(*this));
1172 
1173   // Insert a label at the beginning of the function. This will be our first
1174   // basic block.
1175   Labels[0] = Ctx->createNamedTempSymbol("BB0");
1176 
1177   uint64_t Size = 0; // instruction size
1178   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1179     MCInst Instruction;
1180     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1181 
1182     // Check for data inside code and ignore it
1183     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1184       Size = DataInCodeSize;
1185       continue;
1186     }
1187 
1188     if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1189                                            FunctionData.slice(Offset),
1190                                            AbsoluteInstrAddr, nulls())) {
1191       // Functions with "soft" boundaries, e.g. coming from assembly source,
1192       // can have 0-byte padding at the end.
1193       if (isZeroPaddingAt(Offset))
1194         break;
1195 
1196       errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1197              << Twine::utohexstr(Offset) << " (address 0x"
1198              << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this
1199              << '\n';
1200       // Some AVX-512 instructions could not be disassembled at all.
1201       if (BC.HasRelocations && opts::TrapOnAVX512 && BC.isX86()) {
1202         setTrapOnEntry();
1203         BC.TrappedFunctions.push_back(this);
1204       } else {
1205         setIgnored();
1206       }
1207 
1208       break;
1209     }
1210 
1211     // Check integrity of LLVM assembler/disassembler.
1212     if (opts::CheckEncoding && !BC.MIB->isBranch(Instruction) &&
1213         !BC.MIB->isCall(Instruction) && !BC.MIB->isNoop(Instruction)) {
1214       if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) {
1215         errs() << "BOLT-WARNING: mismatching LLVM encoding detected in "
1216                << "function " << *this << " for instruction :\n";
1217         BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1218         errs() << '\n';
1219       }
1220     }
1221 
1222     // Special handling for AVX-512 instructions.
1223     if (MIB->hasEVEXEncoding(Instruction)) {
1224       if (BC.HasRelocations && opts::TrapOnAVX512) {
1225         setTrapOnEntry();
1226         BC.TrappedFunctions.push_back(this);
1227         break;
1228       }
1229 
1230       if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) {
1231         errs() << "BOLT-WARNING: internal assembler/disassembler error "
1232                   "detected for AVX512 instruction:\n";
1233         BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1234         errs() << " in function " << *this << '\n';
1235         setIgnored();
1236         break;
1237       }
1238     }
1239 
1240     if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) {
1241       uint64_t TargetAddress = 0;
1242       if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1243                               TargetAddress)) {
1244         // Check if the target is within the same function. Otherwise it's
1245         // a call, possibly a tail call.
1246         //
1247         // If the target *is* the function address it could be either a branch
1248         // or a recursive call.
1249         bool IsCall = MIB->isCall(Instruction);
1250         const bool IsCondBranch = MIB->isConditionalBranch(Instruction);
1251         MCSymbol *TargetSymbol = nullptr;
1252 
1253         if (BC.MIB->isUnsupportedBranch(Instruction)) {
1254           setIgnored();
1255           if (BinaryFunction *TargetFunc =
1256                   BC.getBinaryFunctionContainingAddress(TargetAddress))
1257             TargetFunc->setIgnored();
1258         }
1259 
1260         if (IsCall && containsAddress(TargetAddress)) {
1261           if (TargetAddress == getAddress()) {
1262             // Recursive call.
1263             TargetSymbol = getSymbol();
1264           } else {
1265             if (BC.isX86()) {
1266               // Dangerous old-style x86 PIC code. We may need to freeze this
1267               // function, so preserve the function as is for now.
1268               PreserveNops = true;
1269             } else {
1270               errs() << "BOLT-WARNING: internal call detected at 0x"
1271                      << Twine::utohexstr(AbsoluteInstrAddr) << " in function "
1272                      << *this << ". Skipping.\n";
1273               IsSimple = false;
1274             }
1275           }
1276         }
1277 
1278         if (!TargetSymbol) {
1279           // Create either local label or external symbol.
1280           if (containsAddress(TargetAddress)) {
1281             TargetSymbol = getOrCreateLocalLabel(TargetAddress);
1282           } else {
1283             if (TargetAddress == getAddress() + getSize() &&
1284                 TargetAddress < getAddress() + getMaxSize() &&
1285                 !(BC.isAArch64() &&
1286                   BC.handleAArch64Veneer(TargetAddress, /*MatchOnly*/ true))) {
1287               // Result of __builtin_unreachable().
1288               LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x"
1289                                 << Twine::utohexstr(AbsoluteInstrAddr)
1290                                 << " in function " << *this
1291                                 << " : replacing with nop.\n");
1292               BC.MIB->createNoop(Instruction);
1293               if (IsCondBranch) {
1294                 // Register branch offset for profile validation.
1295                 IgnoredBranches.emplace_back(Offset, Offset + Size);
1296               }
1297               goto add_instruction;
1298             }
1299             // May update Instruction and IsCall
1300             TargetSymbol = handleExternalReference(Instruction, Size, Offset,
1301                                                    TargetAddress, IsCall);
1302           }
1303         }
1304 
1305         if (!IsCall) {
1306           // Add taken branch info.
1307           TakenBranches.emplace_back(Offset, TargetAddress - getAddress());
1308         }
1309         BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx);
1310 
1311         // Mark CTC.
1312         if (IsCondBranch && IsCall)
1313           MIB->setConditionalTailCall(Instruction, TargetAddress);
1314       } else {
1315         // Could not evaluate branch. Should be an indirect call or an
1316         // indirect branch. Bail out on the latter case.
1317         if (MIB->isIndirectBranch(Instruction))
1318           handleIndirectBranch(Instruction, Size, Offset);
1319         // Indirect call. We only need to fix it if the operand is RIP-relative.
1320         if (IsSimple && MIB->hasPCRelOperand(Instruction))
1321           handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1322 
1323         if (BC.isAArch64())
1324           handleAArch64IndirectCall(Instruction, Offset);
1325       }
1326     } else if (BC.isAArch64() || BC.isRISCV()) {
1327       // Check if there's a relocation associated with this instruction.
1328       bool UsedReloc = false;
1329       for (auto Itr = Relocations.lower_bound(Offset),
1330                 ItrE = Relocations.lower_bound(Offset + Size);
1331            Itr != ItrE; ++Itr) {
1332         const Relocation &Relocation = Itr->second;
1333         int64_t Value = Relocation.Value;
1334         const bool Result = BC.MIB->replaceImmWithSymbolRef(
1335             Instruction, Relocation.Symbol, Relocation.Addend, Ctx.get(), Value,
1336             Relocation.Type);
1337         (void)Result;
1338         assert(Result && "cannot replace immediate with relocation");
1339 
1340         // For aarch64, if we replaced an immediate with a symbol from a
1341         // relocation, we mark it so we do not try to further process a
1342         // pc-relative operand. All we need is the symbol.
1343         UsedReloc = true;
1344       }
1345 
1346       if (!BC.isRISCV() && MIB->hasPCRelOperand(Instruction) && !UsedReloc)
1347         handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1348     }
1349 
1350 add_instruction:
1351     if (getDWARFLineTable()) {
1352       Instruction.setLoc(findDebugLineInformationForInstructionAt(
1353           AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable()));
1354     }
1355 
1356     // Record offset of the instruction for profile matching.
1357     if (BC.keepOffsetForInstruction(Instruction))
1358       MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
1359 
1360     if (BC.MIB->isNoop(Instruction)) {
1361       // NOTE: disassembly loses the correct size information for noops.
1362       //       E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
1363       //       5 bytes. Preserve the size info using annotations.
1364       MIB->addAnnotation(Instruction, "Size", static_cast<uint32_t>(Size));
1365     }
1366 
1367     addInstruction(Offset, std::move(Instruction));
1368   }
1369 
1370   // Reset symbolizer for the disassembler.
1371   BC.SymbolicDisAsm->setSymbolizer(nullptr);
1372 
1373   if (uint64_t Offset = getFirstInstructionOffset())
1374     Labels[Offset] = BC.Ctx->createNamedTempSymbol();
1375 
1376   clearList(Relocations);
1377 
1378   if (!IsSimple) {
1379     clearList(Instructions);
1380     return false;
1381   }
1382 
1383   updateState(State::Disassembled);
1384 
1385   return true;
1386 }
1387 
1388 bool BinaryFunction::scanExternalRefs() {
1389   bool Success = true;
1390   bool DisassemblyFailed = false;
1391 
1392   // Ignore pseudo functions.
1393   if (isPseudo())
1394     return Success;
1395 
1396   if (opts::NoScan) {
1397     clearList(Relocations);
1398     clearList(ExternallyReferencedOffsets);
1399 
1400     return false;
1401   }
1402 
1403   // List of external references for this function.
1404   std::vector<Relocation> FunctionRelocations;
1405 
1406   static BinaryContext::IndependentCodeEmitter Emitter =
1407       BC.createIndependentMCCodeEmitter();
1408 
1409   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1410   assert(ErrorOrFunctionData && "function data is not available");
1411   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1412   assert(FunctionData.size() == getMaxSize() &&
1413          "function size does not match raw data size");
1414 
1415   BC.SymbolicDisAsm->setSymbolizer(
1416       BC.MIB->createTargetSymbolizer(*this, /*CreateSymbols*/ false));
1417 
1418   // Disassemble contents of the function. Detect code entry points and create
1419   // relocations for references to code that will be moved.
1420   uint64_t Size = 0; // instruction size
1421   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1422     // Check for data inside code and ignore it
1423     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1424       Size = DataInCodeSize;
1425       continue;
1426     }
1427 
1428     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1429     MCInst Instruction;
1430     if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1431                                            FunctionData.slice(Offset),
1432                                            AbsoluteInstrAddr, nulls())) {
1433       if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) {
1434         errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1435                << Twine::utohexstr(Offset) << " (address 0x"
1436                << Twine::utohexstr(AbsoluteInstrAddr) << ") in function "
1437                << *this << '\n';
1438       }
1439       Success = false;
1440       DisassemblyFailed = true;
1441       break;
1442     }
1443 
1444     // Return true if we can skip handling the Target function reference.
1445     auto ignoreFunctionRef = [&](const BinaryFunction &Target) {
1446       if (&Target == this)
1447         return true;
1448 
1449       // Note that later we may decide not to emit Target function. In that
1450       // case, we conservatively create references that will be ignored or
1451       // resolved to the same function.
1452       if (!BC.shouldEmit(Target))
1453         return true;
1454 
1455       return false;
1456     };
1457 
1458     // Return true if we can ignore reference to the symbol.
1459     auto ignoreReference = [&](const MCSymbol *TargetSymbol) {
1460       if (!TargetSymbol)
1461         return true;
1462 
1463       if (BC.forceSymbolRelocations(TargetSymbol->getName()))
1464         return false;
1465 
1466       BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol);
1467       if (!TargetFunction)
1468         return true;
1469 
1470       return ignoreFunctionRef(*TargetFunction);
1471     };
1472 
1473     // Handle calls and branches separately as symbolization doesn't work for
1474     // them yet.
1475     MCSymbol *BranchTargetSymbol = nullptr;
1476     if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) {
1477       uint64_t TargetAddress = 0;
1478       BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1479                              TargetAddress);
1480 
1481       // Create an entry point at reference address if needed.
1482       BinaryFunction *TargetFunction =
1483           BC.getBinaryFunctionContainingAddress(TargetAddress);
1484 
1485       if (!TargetFunction || ignoreFunctionRef(*TargetFunction))
1486         continue;
1487 
1488       const uint64_t FunctionOffset =
1489           TargetAddress - TargetFunction->getAddress();
1490       BranchTargetSymbol =
1491           FunctionOffset ? TargetFunction->addEntryPointAtOffset(FunctionOffset)
1492                          : TargetFunction->getSymbol();
1493     }
1494 
1495     // Can't find more references. Not creating relocations since we are not
1496     // moving code.
1497     if (!BC.HasRelocations)
1498       continue;
1499 
1500     if (BranchTargetSymbol) {
1501       BC.MIB->replaceBranchTarget(Instruction, BranchTargetSymbol,
1502                                   Emitter.LocalCtx.get());
1503     } else if (!llvm::any_of(Instruction,
1504                              [](const MCOperand &Op) { return Op.isExpr(); })) {
1505       // Skip assembly if the instruction may not have any symbolic operands.
1506       continue;
1507     }
1508 
1509     // Emit the instruction using temp emitter and generate relocations.
1510     SmallString<256> Code;
1511     SmallVector<MCFixup, 4> Fixups;
1512     Emitter.MCE->encodeInstruction(Instruction, Code, Fixups, *BC.STI);
1513 
1514     // Create relocation for every fixup.
1515     for (const MCFixup &Fixup : Fixups) {
1516       std::optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB);
1517       if (!Rel) {
1518         Success = false;
1519         continue;
1520       }
1521 
1522       if (ignoreReference(Rel->Symbol))
1523         continue;
1524 
1525       if (Relocation::getSizeForType(Rel->Type) < 4) {
1526         // If the instruction uses a short form, then we might not be able
1527         // to handle the rewrite without relaxation, and hence cannot reliably
1528         // create an external reference relocation.
1529         Success = false;
1530         continue;
1531       }
1532       Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset;
1533       FunctionRelocations.push_back(*Rel);
1534     }
1535 
1536     if (!Success)
1537       break;
1538   }
1539 
1540   // Reset symbolizer for the disassembler.
1541   BC.SymbolicDisAsm->setSymbolizer(nullptr);
1542 
1543   // Add relocations unless disassembly failed for this function.
1544   if (!DisassemblyFailed)
1545     for (Relocation &Rel : FunctionRelocations)
1546       getOriginSection()->addPendingRelocation(Rel);
1547 
1548   // Inform BinaryContext that this function symbols will not be defined and
1549   // relocations should not be created against them.
1550   if (BC.HasRelocations) {
1551     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
1552       BC.UndefinedSymbols.insert(LI.second);
1553     for (MCSymbol *const EndLabel : FunctionEndLabels)
1554       if (EndLabel)
1555         BC.UndefinedSymbols.insert(EndLabel);
1556   }
1557 
1558   clearList(Relocations);
1559   clearList(ExternallyReferencedOffsets);
1560 
1561   if (Success && BC.HasRelocations)
1562     HasExternalRefRelocations = true;
1563 
1564   if (opts::Verbosity >= 1 && !Success)
1565     outs() << "BOLT-INFO: failed to scan refs for  " << *this << '\n';
1566 
1567   return Success;
1568 }
1569 
1570 void BinaryFunction::postProcessEntryPoints() {
1571   if (!isSimple())
1572     return;
1573 
1574   for (auto &KV : Labels) {
1575     MCSymbol *Label = KV.second;
1576     if (!getSecondaryEntryPointSymbol(Label))
1577       continue;
1578 
1579     // In non-relocation mode there's potentially an external undetectable
1580     // reference to the entry point and hence we cannot move this entry
1581     // point. Optimizing without moving could be difficult.
1582     if (!BC.HasRelocations)
1583       setSimple(false);
1584 
1585     const uint32_t Offset = KV.first;
1586 
1587     // If we are at Offset 0 and there is no instruction associated with it,
1588     // this means this is an empty function. Just ignore. If we find an
1589     // instruction at this offset, this entry point is valid.
1590     if (!Offset || getInstructionAtOffset(Offset))
1591       continue;
1592 
1593     // On AArch64 there are legitimate reasons to have references past the
1594     // end of the function, e.g. jump tables.
1595     if (BC.isAArch64() && Offset == getSize())
1596       continue;
1597 
1598     errs() << "BOLT-WARNING: reference in the middle of instruction "
1599               "detected in function "
1600            << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n';
1601     if (BC.HasRelocations)
1602       setIgnored();
1603     setSimple(false);
1604     return;
1605   }
1606 }
1607 
1608 void BinaryFunction::postProcessJumpTables() {
1609   // Create labels for all entries.
1610   for (auto &JTI : JumpTables) {
1611     JumpTable &JT = *JTI.second;
1612     if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) {
1613       opts::JumpTables = JTS_MOVE;
1614       outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was "
1615                 "detected in function "
1616              << *this << '\n';
1617     }
1618     const uint64_t BDSize =
1619         BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1620     if (!BDSize) {
1621       BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1622     } else {
1623       assert(BDSize >= JT.getSize() &&
1624              "jump table cannot be larger than the containing object");
1625     }
1626     if (!JT.Entries.empty())
1627       continue;
1628 
1629     bool HasOneParent = (JT.Parents.size() == 1);
1630     for (uint64_t EntryAddress : JT.EntriesAsAddress) {
1631       // builtin_unreachable does not belong to any function
1632       // Need to handle separately
1633       bool IsBuiltinUnreachable =
1634           llvm::any_of(JT.Parents, [&](const BinaryFunction *Parent) {
1635             return EntryAddress == Parent->getAddress() + Parent->getSize();
1636           });
1637       if (IsBuiltinUnreachable) {
1638         MCSymbol *Label = getOrCreateLocalLabel(EntryAddress, true);
1639         JT.Entries.push_back(Label);
1640         continue;
1641       }
1642       // Create a local label for targets that cannot be reached by other
1643       // fragments. Otherwise, create a secondary entry point in the target
1644       // function.
1645       BinaryFunction *TargetBF =
1646           BC.getBinaryFunctionContainingAddress(EntryAddress);
1647       MCSymbol *Label;
1648       if (HasOneParent && TargetBF == this) {
1649         Label = getOrCreateLocalLabel(EntryAddress, true);
1650       } else {
1651         const uint64_t Offset = EntryAddress - TargetBF->getAddress();
1652         Label = Offset ? TargetBF->addEntryPointAtOffset(Offset)
1653                        : TargetBF->getSymbol();
1654       }
1655       JT.Entries.push_back(Label);
1656     }
1657   }
1658 
1659   // Add TakenBranches from JumpTables.
1660   //
1661   // We want to do it after initial processing since we don't know jump tables'
1662   // boundaries until we process them all.
1663   for (auto &JTSite : JTSites) {
1664     const uint64_t JTSiteOffset = JTSite.first;
1665     const uint64_t JTAddress = JTSite.second;
1666     const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1667     assert(JT && "cannot find jump table for address");
1668 
1669     uint64_t EntryOffset = JTAddress - JT->getAddress();
1670     while (EntryOffset < JT->getSize()) {
1671       uint64_t EntryAddress = JT->EntriesAsAddress[EntryOffset / JT->EntrySize];
1672       uint64_t TargetOffset = EntryAddress - getAddress();
1673       if (TargetOffset < getSize()) {
1674         TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1675 
1676         if (opts::StrictMode)
1677           registerReferencedOffset(TargetOffset);
1678       }
1679 
1680       EntryOffset += JT->EntrySize;
1681 
1682       // A label at the next entry means the end of this jump table.
1683       if (JT->Labels.count(EntryOffset))
1684         break;
1685     }
1686   }
1687   clearList(JTSites);
1688 
1689   // Conservatively populate all possible destinations for unknown indirect
1690   // branches.
1691   if (opts::StrictMode && hasInternalReference()) {
1692     for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1693       for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1694         // Ignore __builtin_unreachable().
1695         if (PossibleDestination == getSize())
1696           continue;
1697         TakenBranches.emplace_back(Offset, PossibleDestination);
1698       }
1699     }
1700   }
1701 
1702   // Remove duplicates branches. We can get a bunch of them from jump tables.
1703   // Without doing jump table value profiling we don't have use for extra
1704   // (duplicate) branches.
1705   llvm::sort(TakenBranches);
1706   auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
1707   TakenBranches.erase(NewEnd, TakenBranches.end());
1708 }
1709 
1710 bool BinaryFunction::validateExternallyReferencedOffsets() {
1711   SmallPtrSet<MCSymbol *, 4> JTTargets;
1712   for (const JumpTable *JT : llvm::make_second_range(JumpTables))
1713     JTTargets.insert(JT->Entries.begin(), JT->Entries.end());
1714 
1715   bool HasUnclaimedReference = false;
1716   for (uint64_t Destination : ExternallyReferencedOffsets) {
1717     // Ignore __builtin_unreachable().
1718     if (Destination == getSize())
1719       continue;
1720     // Ignore constant islands
1721     if (isInConstantIsland(Destination + getAddress()))
1722       continue;
1723 
1724     if (BinaryBasicBlock *BB = getBasicBlockAtOffset(Destination)) {
1725       // Check if the externally referenced offset is a recognized jump table
1726       // target.
1727       if (JTTargets.contains(BB->getLabel()))
1728         continue;
1729 
1730       if (opts::Verbosity >= 1) {
1731         errs() << "BOLT-WARNING: unclaimed data to code reference (possibly "
1732                << "an unrecognized jump table entry) to " << BB->getName()
1733                << " in " << *this << "\n";
1734       }
1735       auto L = BC.scopeLock();
1736       addEntryPoint(*BB);
1737     } else {
1738       errs() << "BOLT-WARNING: unknown data to code reference to offset "
1739              << Twine::utohexstr(Destination) << " in " << *this << "\n";
1740       setIgnored();
1741     }
1742     HasUnclaimedReference = true;
1743   }
1744   return !HasUnclaimedReference;
1745 }
1746 
1747 bool BinaryFunction::postProcessIndirectBranches(
1748     MCPlusBuilder::AllocatorIdTy AllocId) {
1749   auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
1750     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding unknown control flow in " << *this
1751                       << " for " << BB.getName() << "\n");
1752     HasUnknownControlFlow = true;
1753     BB.removeAllSuccessors();
1754     for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1755       if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1756         BB.addSuccessor(SuccBB);
1757   };
1758 
1759   uint64_t NumIndirectJumps = 0;
1760   MCInst *LastIndirectJump = nullptr;
1761   BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1762   uint64_t LastJT = 0;
1763   uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1764   for (BinaryBasicBlock &BB : blocks()) {
1765     for (MCInst &Instr : BB) {
1766       if (!BC.MIB->isIndirectBranch(Instr))
1767         continue;
1768 
1769       // If there's an indirect branch in a single-block function -
1770       // it must be a tail call.
1771       if (BasicBlocks.size() == 1) {
1772         BC.MIB->convertJmpToTailCall(Instr);
1773         return true;
1774       }
1775 
1776       ++NumIndirectJumps;
1777 
1778       if (opts::StrictMode && !hasInternalReference()) {
1779         BC.MIB->convertJmpToTailCall(Instr);
1780         break;
1781       }
1782 
1783       // Validate the tail call or jump table assumptions now that we know
1784       // basic block boundaries.
1785       if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1786         const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1787         MCInst *MemLocInstr;
1788         unsigned BaseRegNum, IndexRegNum;
1789         int64_t DispValue;
1790         const MCExpr *DispExpr;
1791         MCInst *PCRelBaseInstr;
1792         IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
1793             Instr, BB.begin(), BB.end(), PtrSize, MemLocInstr, BaseRegNum,
1794             IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
1795         if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1796           continue;
1797 
1798         if (!opts::StrictMode)
1799           return false;
1800 
1801         if (BC.MIB->isTailCall(Instr)) {
1802           BC.MIB->convertTailCallToJmp(Instr);
1803         } else {
1804           LastIndirectJump = &Instr;
1805           LastIndirectJumpBB = &BB;
1806           LastJT = BC.MIB->getJumpTable(Instr);
1807           LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1808           BC.MIB->unsetJumpTable(Instr);
1809 
1810           JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1811           if (JT->Type == JumpTable::JTT_NORMAL) {
1812             // Invalidating the jump table may also invalidate other jump table
1813             // boundaries. Until we have/need a support for this, mark the
1814             // function as non-simple.
1815             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1816                               << JT->getName() << " in " << *this << '\n');
1817             return false;
1818           }
1819         }
1820 
1821         addUnknownControlFlow(BB);
1822         continue;
1823       }
1824 
1825       // If this block contains an epilogue code and has an indirect branch,
1826       // then most likely it's a tail call. Otherwise, we cannot tell for sure
1827       // what it is and conservatively reject the function's CFG.
1828       bool IsEpilogue = llvm::any_of(BB, [&](const MCInst &Instr) {
1829         return BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr);
1830       });
1831       if (IsEpilogue) {
1832         BC.MIB->convertJmpToTailCall(Instr);
1833         BB.removeAllSuccessors();
1834         continue;
1835       }
1836 
1837       if (opts::Verbosity >= 2) {
1838         outs() << "BOLT-INFO: rejected potential indirect tail call in "
1839                << "function " << *this << " in basic block " << BB.getName()
1840                << ".\n";
1841         LLVM_DEBUG(BC.printInstructions(dbgs(), BB.begin(), BB.end(),
1842                                         BB.getOffset(), this, true));
1843       }
1844 
1845       if (!opts::StrictMode)
1846         return false;
1847 
1848       addUnknownControlFlow(BB);
1849     }
1850   }
1851 
1852   if (HasInternalLabelReference)
1853     return false;
1854 
1855   // If there's only one jump table, and one indirect jump, and no other
1856   // references, then we should be able to derive the jump table even if we
1857   // fail to match the pattern.
1858   if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
1859       JumpTables.size() == 1 && LastIndirectJump &&
1860       !BC.getJumpTableContainingAddress(LastJT)->IsSplit) {
1861     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: unsetting unknown control flow in "
1862                       << *this << '\n');
1863     BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1864     HasUnknownControlFlow = false;
1865 
1866     LastIndirectJumpBB->updateJumpTableSuccessors();
1867   }
1868 
1869   if (HasFixedIndirectBranch)
1870     return false;
1871 
1872   // Validate that all data references to function offsets are claimed by
1873   // recognized jump tables. Register externally referenced blocks as entry
1874   // points.
1875   if (!opts::StrictMode && hasInternalReference()) {
1876     if (!validateExternallyReferencedOffsets())
1877       return false;
1878   }
1879 
1880   if (HasUnknownControlFlow && !BC.HasRelocations)
1881     return false;
1882 
1883   return true;
1884 }
1885 
1886 void BinaryFunction::recomputeLandingPads() {
1887   updateBBIndices(0);
1888 
1889   for (BinaryBasicBlock *BB : BasicBlocks) {
1890     BB->LandingPads.clear();
1891     BB->Throwers.clear();
1892   }
1893 
1894   for (BinaryBasicBlock *BB : BasicBlocks) {
1895     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1896     for (MCInst &Instr : *BB) {
1897       if (!BC.MIB->isInvoke(Instr))
1898         continue;
1899 
1900       const std::optional<MCPlus::MCLandingPad> EHInfo =
1901           BC.MIB->getEHInfo(Instr);
1902       if (!EHInfo || !EHInfo->first)
1903         continue;
1904 
1905       BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1906       if (!BBLandingPads.count(LPBlock)) {
1907         BBLandingPads.insert(LPBlock);
1908         BB->LandingPads.emplace_back(LPBlock);
1909         LPBlock->Throwers.emplace_back(BB);
1910       }
1911     }
1912   }
1913 }
1914 
1915 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1916   auto &MIB = BC.MIB;
1917 
1918   if (!isSimple()) {
1919     assert(!BC.HasRelocations &&
1920            "cannot process file with non-simple function in relocs mode");
1921     return false;
1922   }
1923 
1924   if (CurrentState != State::Disassembled)
1925     return false;
1926 
1927   assert(BasicBlocks.empty() && "basic block list should be empty");
1928   assert((Labels.find(getFirstInstructionOffset()) != Labels.end()) &&
1929          "first instruction should always have a label");
1930 
1931   // Create basic blocks in the original layout order:
1932   //
1933   //  * Every instruction with associated label marks
1934   //    the beginning of a basic block.
1935   //  * Conditional instruction marks the end of a basic block,
1936   //    except when the following instruction is an
1937   //    unconditional branch, and the unconditional branch is not
1938   //    a destination of another branch. In the latter case, the
1939   //    basic block will consist of a single unconditional branch
1940   //    (missed "double-jump" optimization).
1941   //
1942   // Created basic blocks are sorted in layout order since they are
1943   // created in the same order as instructions, and instructions are
1944   // sorted by offsets.
1945   BinaryBasicBlock *InsertBB = nullptr;
1946   BinaryBasicBlock *PrevBB = nullptr;
1947   bool IsLastInstrNop = false;
1948   // Offset of the last non-nop instruction.
1949   uint64_t LastInstrOffset = 0;
1950 
1951   auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1952                                    BinaryBasicBlock *InsertBB) {
1953     for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1954               FE = OffsetToCFI.upper_bound(CFIOffset);
1955          FI != FE; ++FI) {
1956       addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1957     }
1958   };
1959 
1960   // For profiling purposes we need to save the offset of the last instruction
1961   // in the basic block.
1962   // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1963   //       older profiles ignored nops.
1964   auto updateOffset = [&](uint64_t Offset) {
1965     assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
1966     MCInst *LastNonNop = nullptr;
1967     for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
1968                                             E = PrevBB->rend();
1969          RII != E; ++RII) {
1970       if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
1971         LastNonNop = &*RII;
1972         break;
1973       }
1974     }
1975     if (LastNonNop && !MIB->getOffset(*LastNonNop))
1976       MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId);
1977   };
1978 
1979   for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
1980     const uint32_t Offset = I->first;
1981     MCInst &Instr = I->second;
1982 
1983     auto LI = Labels.find(Offset);
1984     if (LI != Labels.end()) {
1985       // Always create new BB at branch destination.
1986       PrevBB = InsertBB ? InsertBB : PrevBB;
1987       InsertBB = addBasicBlockAt(LI->first, LI->second);
1988       if (opts::PreserveBlocksAlignment && IsLastInstrNop)
1989         InsertBB->setDerivedAlignment();
1990 
1991       if (PrevBB)
1992         updateOffset(LastInstrOffset);
1993     }
1994 
1995     // Mark all nops with Offset for profile tracking purposes.
1996     if (MIB->isNoop(Instr) && !MIB->getOffset(Instr)) {
1997       // If "Offset" annotation is not present, set it and mark the nop for
1998       // deletion.
1999       MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId);
2000       // Annotate ordinary nops, so we can safely delete them if required.
2001       MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2002     }
2003 
2004     if (!InsertBB) {
2005       // It must be a fallthrough or unreachable code. Create a new block unless
2006       // we see an unconditional branch following a conditional one. The latter
2007       // should not be a conditional tail call.
2008       assert(PrevBB && "no previous basic block for a fall through");
2009       MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2010       assert(PrevInstr && "no previous instruction for a fall through");
2011       if (MIB->isUnconditionalBranch(Instr) &&
2012           !MIB->isIndirectBranch(*PrevInstr) &&
2013           !MIB->isUnconditionalBranch(*PrevInstr) &&
2014           !MIB->getConditionalTailCall(*PrevInstr) &&
2015           !MIB->isReturn(*PrevInstr)) {
2016         // Temporarily restore inserter basic block.
2017         InsertBB = PrevBB;
2018       } else {
2019         MCSymbol *Label;
2020         {
2021           auto L = BC.scopeLock();
2022           Label = BC.Ctx->createNamedTempSymbol("FT");
2023         }
2024         InsertBB = addBasicBlockAt(Offset, Label);
2025         if (opts::PreserveBlocksAlignment && IsLastInstrNop)
2026           InsertBB->setDerivedAlignment();
2027         updateOffset(LastInstrOffset);
2028       }
2029     }
2030     if (Offset == getFirstInstructionOffset()) {
2031       // Add associated CFI pseudos in the first offset
2032       addCFIPlaceholders(Offset, InsertBB);
2033     }
2034 
2035     const bool IsBlockEnd = MIB->isTerminator(Instr);
2036     IsLastInstrNop = MIB->isNoop(Instr);
2037     if (!IsLastInstrNop)
2038       LastInstrOffset = Offset;
2039     InsertBB->addInstruction(std::move(Instr));
2040 
2041     // Add associated CFI instrs. We always add the CFI instruction that is
2042     // located immediately after this instruction, since the next CFI
2043     // instruction reflects the change in state caused by this instruction.
2044     auto NextInstr = std::next(I);
2045     uint64_t CFIOffset;
2046     if (NextInstr != E)
2047       CFIOffset = NextInstr->first;
2048     else
2049       CFIOffset = getSize();
2050 
2051     // Note: this potentially invalidates instruction pointers/iterators.
2052     addCFIPlaceholders(CFIOffset, InsertBB);
2053 
2054     if (IsBlockEnd) {
2055       PrevBB = InsertBB;
2056       InsertBB = nullptr;
2057     }
2058   }
2059 
2060   if (BasicBlocks.empty()) {
2061     setSimple(false);
2062     return false;
2063   }
2064 
2065   // Intermediate dump.
2066   LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2067 
2068   // TODO: handle properly calls to no-return functions,
2069   // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2070   // blocks.
2071 
2072   for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2073     LLVM_DEBUG(dbgs() << "registering branch [0x"
2074                       << Twine::utohexstr(Branch.first) << "] -> [0x"
2075                       << Twine::utohexstr(Branch.second) << "]\n");
2076     BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2077     BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2078     if (!FromBB || !ToBB) {
2079       if (!FromBB)
2080         errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2081       if (!ToBB)
2082         errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2083       BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2084                            *this);
2085     }
2086 
2087     FromBB->addSuccessor(ToBB);
2088   }
2089 
2090   // Add fall-through branches.
2091   PrevBB = nullptr;
2092   bool IsPrevFT = false; // Is previous block a fall-through.
2093   for (BinaryBasicBlock *BB : BasicBlocks) {
2094     if (IsPrevFT)
2095       PrevBB->addSuccessor(BB);
2096 
2097     if (BB->empty()) {
2098       IsPrevFT = true;
2099       PrevBB = BB;
2100       continue;
2101     }
2102 
2103     MCInst *LastInstr = BB->getLastNonPseudoInstr();
2104     assert(LastInstr &&
2105            "should have non-pseudo instruction in non-empty block");
2106 
2107     if (BB->succ_size() == 0) {
2108       // Since there's no existing successors, we know the last instruction is
2109       // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2110       // fall-through.
2111       //
2112       // Conditional tail call is a special case since we don't add a taken
2113       // branch successor for it.
2114       IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2115                  MIB->getConditionalTailCall(*LastInstr);
2116     } else if (BB->succ_size() == 1) {
2117       IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2118     } else {
2119       IsPrevFT = false;
2120     }
2121 
2122     PrevBB = BB;
2123   }
2124 
2125   // Assign landing pads and throwers info.
2126   recomputeLandingPads();
2127 
2128   // Assign CFI information to each BB entry.
2129   annotateCFIState();
2130 
2131   // Annotate invoke instructions with GNU_args_size data.
2132   propagateGnuArgsSizeInfo(AllocatorId);
2133 
2134   // Set the basic block layout to the original order and set end offsets.
2135   PrevBB = nullptr;
2136   for (BinaryBasicBlock *BB : BasicBlocks) {
2137     Layout.addBasicBlock(BB);
2138     if (PrevBB)
2139       PrevBB->setEndOffset(BB->getOffset());
2140     PrevBB = BB;
2141   }
2142   PrevBB->setEndOffset(getSize());
2143 
2144   Layout.updateLayoutIndices();
2145 
2146   normalizeCFIState();
2147 
2148   // Clean-up memory taken by intermediate structures.
2149   //
2150   // NB: don't clear Labels list as we may need them if we mark the function
2151   //     as non-simple later in the process of discovering extra entry points.
2152   clearList(Instructions);
2153   clearList(OffsetToCFI);
2154   clearList(TakenBranches);
2155 
2156   // Update the state.
2157   CurrentState = State::CFG;
2158 
2159   // Make any necessary adjustments for indirect branches.
2160   if (!postProcessIndirectBranches(AllocatorId)) {
2161     if (opts::Verbosity) {
2162       errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2163              << *this << '\n';
2164     }
2165     // In relocation mode we want to keep processing the function but avoid
2166     // optimizing it.
2167     setSimple(false);
2168   }
2169 
2170   clearList(ExternallyReferencedOffsets);
2171   clearList(UnknownIndirectBranchOffsets);
2172 
2173   return true;
2174 }
2175 
2176 void BinaryFunction::postProcessCFG() {
2177   if (isSimple() && !BasicBlocks.empty()) {
2178     // Convert conditional tail call branches to conditional branches that jump
2179     // to a tail call.
2180     removeConditionalTailCalls();
2181 
2182     postProcessProfile();
2183 
2184     // Eliminate inconsistencies between branch instructions and CFG.
2185     postProcessBranches();
2186   }
2187 
2188   calculateMacroOpFusionStats();
2189 
2190   // The final cleanup of intermediate structures.
2191   clearList(IgnoredBranches);
2192 
2193   // Remove "Offset" annotations, unless we need an address-translation table
2194   // later. This has no cost, since annotations are allocated by a bumpptr
2195   // allocator and won't be released anyway until late in the pipeline.
2196   if (!requiresAddressTranslation() && !opts::Instrument) {
2197     for (BinaryBasicBlock &BB : blocks())
2198       for (MCInst &Inst : BB)
2199         BC.MIB->clearOffset(Inst);
2200   }
2201 
2202   assert((!isSimple() || validateCFG()) &&
2203          "invalid CFG detected after post-processing");
2204 }
2205 
2206 void BinaryFunction::calculateMacroOpFusionStats() {
2207   if (!getBinaryContext().isX86())
2208     return;
2209   for (const BinaryBasicBlock &BB : blocks()) {
2210     auto II = BB.getMacroOpFusionPair();
2211     if (II == BB.end())
2212       continue;
2213 
2214     // Check offset of the second instruction.
2215     // FIXME: arch-specific.
2216     const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2217     if (!Offset || (getAddress() + Offset) % 64)
2218       continue;
2219 
2220     LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2221                       << Twine::utohexstr(getAddress() + Offset)
2222                       << " in function " << *this << "; executed "
2223                       << BB.getKnownExecutionCount() << " times.\n");
2224     ++BC.Stats.MissedMacroFusionPairs;
2225     BC.Stats.MissedMacroFusionExecCount += BB.getKnownExecutionCount();
2226   }
2227 }
2228 
2229 void BinaryFunction::removeTagsFromProfile() {
2230   for (BinaryBasicBlock *BB : BasicBlocks) {
2231     if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2232       BB->ExecutionCount = 0;
2233     for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2234       if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2235           BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2236         continue;
2237       BI.Count = 0;
2238       BI.MispredictedCount = 0;
2239     }
2240   }
2241 }
2242 
2243 void BinaryFunction::removeConditionalTailCalls() {
2244   // Blocks to be appended at the end.
2245   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2246 
2247   for (auto BBI = begin(); BBI != end(); ++BBI) {
2248     BinaryBasicBlock &BB = *BBI;
2249     MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2250     if (!CTCInstr)
2251       continue;
2252 
2253     std::optional<uint64_t> TargetAddressOrNone =
2254         BC.MIB->getConditionalTailCall(*CTCInstr);
2255     if (!TargetAddressOrNone)
2256       continue;
2257 
2258     // Gather all necessary information about CTC instruction before
2259     // annotations are destroyed.
2260     const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2261     uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2262     uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2263     if (hasValidProfile()) {
2264       CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2265           *CTCInstr, "CTCTakenCount");
2266       CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2267           *CTCInstr, "CTCMispredCount");
2268     }
2269 
2270     // Assert that the tail call does not throw.
2271     assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2272            "found tail call with associated landing pad");
2273 
2274     // Create a basic block with an unconditional tail call instruction using
2275     // the same destination.
2276     const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2277     assert(CTCTargetLabel && "symbol expected for conditional tail call");
2278     MCInst TailCallInstr;
2279     BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2280     // Link new BBs to the original input offset of the BB where the CTC
2281     // is, so we can map samples recorded in new BBs back to the original BB
2282     // seem in the input binary (if using BAT)
2283     std::unique_ptr<BinaryBasicBlock> TailCallBB =
2284         createBasicBlock(BC.Ctx->createNamedTempSymbol("TC"));
2285     TailCallBB->setOffset(BB.getInputOffset());
2286     TailCallBB->addInstruction(TailCallInstr);
2287     TailCallBB->setCFIState(CFIStateBeforeCTC);
2288 
2289     // Add CFG edge with profile info from BB to TailCallBB.
2290     BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2291 
2292     // Add execution count for the block.
2293     TailCallBB->setExecutionCount(CTCTakenCount);
2294 
2295     BC.MIB->convertTailCallToJmp(*CTCInstr);
2296 
2297     BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2298                                 BC.Ctx.get());
2299 
2300     // Add basic block to the list that will be added to the end.
2301     NewBlocks.emplace_back(std::move(TailCallBB));
2302 
2303     // Swap edges as the TailCallBB corresponds to the taken branch.
2304     BB.swapConditionalSuccessors();
2305 
2306     // This branch is no longer a conditional tail call.
2307     BC.MIB->unsetConditionalTailCall(*CTCInstr);
2308 
2309     // Move offset from CTCInstr to TailCallInstr.
2310     if (std::optional<uint32_t> Offset = BC.MIB->getOffset(*CTCInstr)) {
2311       BC.MIB->setOffset(TailCallInstr, *Offset);
2312       BC.MIB->clearOffset(*CTCInstr);
2313     }
2314   }
2315 
2316   insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2317                     /* UpdateLayout */ true,
2318                     /* UpdateCFIState */ false);
2319 }
2320 
2321 uint64_t BinaryFunction::getFunctionScore() const {
2322   if (FunctionScore != -1)
2323     return FunctionScore;
2324 
2325   if (!isSimple() || !hasValidProfile()) {
2326     FunctionScore = 0;
2327     return FunctionScore;
2328   }
2329 
2330   uint64_t TotalScore = 0ULL;
2331   for (const BinaryBasicBlock &BB : blocks()) {
2332     uint64_t BBExecCount = BB.getExecutionCount();
2333     if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2334       continue;
2335     TotalScore += BBExecCount * BB.getNumNonPseudos();
2336   }
2337   FunctionScore = TotalScore;
2338   return FunctionScore;
2339 }
2340 
2341 void BinaryFunction::annotateCFIState() {
2342   assert(CurrentState == State::Disassembled && "unexpected function state");
2343   assert(!BasicBlocks.empty() && "basic block list should not be empty");
2344 
2345   // This is an index of the last processed CFI in FDE CFI program.
2346   uint32_t State = 0;
2347 
2348   // This is an index of RememberState CFI reflecting effective state right
2349   // after execution of RestoreState CFI.
2350   //
2351   // It differs from State iff the CFI at (State-1)
2352   // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2353   //
2354   // This allows us to generate shorter replay sequences when producing new
2355   // CFI programs.
2356   uint32_t EffectiveState = 0;
2357 
2358   // For tracking RememberState/RestoreState sequences.
2359   std::stack<uint32_t> StateStack;
2360 
2361   for (BinaryBasicBlock *BB : BasicBlocks) {
2362     BB->setCFIState(EffectiveState);
2363 
2364     for (const MCInst &Instr : *BB) {
2365       const MCCFIInstruction *CFI = getCFIFor(Instr);
2366       if (!CFI)
2367         continue;
2368 
2369       ++State;
2370 
2371       switch (CFI->getOperation()) {
2372       case MCCFIInstruction::OpRememberState:
2373         StateStack.push(EffectiveState);
2374         EffectiveState = State;
2375         break;
2376       case MCCFIInstruction::OpRestoreState:
2377         assert(!StateStack.empty() && "corrupt CFI stack");
2378         EffectiveState = StateStack.top();
2379         StateStack.pop();
2380         break;
2381       case MCCFIInstruction::OpGnuArgsSize:
2382         // OpGnuArgsSize CFIs do not affect the CFI state.
2383         break;
2384       default:
2385         // Any other CFI updates the state.
2386         EffectiveState = State;
2387         break;
2388       }
2389     }
2390   }
2391 
2392   assert(StateStack.empty() && "corrupt CFI stack");
2393 }
2394 
2395 namespace {
2396 
2397 /// Our full interpretation of a DWARF CFI machine state at a given point
2398 struct CFISnapshot {
2399   /// CFA register number and offset defining the canonical frame at this
2400   /// point, or the number of a rule (CFI state) that computes it with a
2401   /// DWARF expression. This number will be negative if it refers to a CFI
2402   /// located in the CIE instead of the FDE.
2403   uint32_t CFAReg;
2404   int32_t CFAOffset;
2405   int32_t CFARule;
2406   /// Mapping of rules (CFI states) that define the location of each
2407   /// register. If absent, no rule defining the location of such register
2408   /// was ever read. This number will be negative if it refers to a CFI
2409   /// located in the CIE instead of the FDE.
2410   DenseMap<int32_t, int32_t> RegRule;
2411 
2412   /// References to CIE, FDE and expanded instructions after a restore state
2413   const BinaryFunction::CFIInstrMapType &CIE;
2414   const BinaryFunction::CFIInstrMapType &FDE;
2415   const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2416 
2417   /// Current FDE CFI number representing the state where the snapshot is at
2418   int32_t CurState;
2419 
2420   /// Used when we don't have information about which state/rule to apply
2421   /// to recover the location of either the CFA or a specific register
2422   constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2423 
2424 private:
2425   /// Update our snapshot by executing a single CFI
2426   void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2427     switch (Instr.getOperation()) {
2428     case MCCFIInstruction::OpSameValue:
2429     case MCCFIInstruction::OpRelOffset:
2430     case MCCFIInstruction::OpOffset:
2431     case MCCFIInstruction::OpRestore:
2432     case MCCFIInstruction::OpUndefined:
2433     case MCCFIInstruction::OpRegister:
2434       RegRule[Instr.getRegister()] = RuleNumber;
2435       break;
2436     case MCCFIInstruction::OpDefCfaRegister:
2437       CFAReg = Instr.getRegister();
2438       CFARule = UNKNOWN;
2439       break;
2440     case MCCFIInstruction::OpDefCfaOffset:
2441       CFAOffset = Instr.getOffset();
2442       CFARule = UNKNOWN;
2443       break;
2444     case MCCFIInstruction::OpDefCfa:
2445       CFAReg = Instr.getRegister();
2446       CFAOffset = Instr.getOffset();
2447       CFARule = UNKNOWN;
2448       break;
2449     case MCCFIInstruction::OpEscape: {
2450       std::optional<uint8_t> Reg =
2451           readDWARFExpressionTargetReg(Instr.getValues());
2452       // Handle DW_CFA_def_cfa_expression
2453       if (!Reg) {
2454         CFARule = RuleNumber;
2455         break;
2456       }
2457       RegRule[*Reg] = RuleNumber;
2458       break;
2459     }
2460     case MCCFIInstruction::OpAdjustCfaOffset:
2461     case MCCFIInstruction::OpWindowSave:
2462     case MCCFIInstruction::OpNegateRAState:
2463     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2464       llvm_unreachable("unsupported CFI opcode");
2465       break;
2466     case MCCFIInstruction::OpRememberState:
2467     case MCCFIInstruction::OpRestoreState:
2468     case MCCFIInstruction::OpGnuArgsSize:
2469       // do not affect CFI state
2470       break;
2471     }
2472   }
2473 
2474 public:
2475   /// Advance state reading FDE CFI instructions up to State number
2476   void advanceTo(int32_t State) {
2477     for (int32_t I = CurState, E = State; I != E; ++I) {
2478       const MCCFIInstruction &Instr = FDE[I];
2479       if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2480         update(Instr, I);
2481         continue;
2482       }
2483       // If restore state instruction, fetch the equivalent CFIs that have
2484       // the same effect of this restore. This is used to ensure remember-
2485       // restore pairs are completely removed.
2486       auto Iter = FrameRestoreEquivalents.find(I);
2487       if (Iter == FrameRestoreEquivalents.end())
2488         continue;
2489       for (int32_t RuleNumber : Iter->second)
2490         update(FDE[RuleNumber], RuleNumber);
2491     }
2492 
2493     assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2494             CFARule != UNKNOWN) &&
2495            "CIE did not define default CFA?");
2496 
2497     CurState = State;
2498   }
2499 
2500   /// Interpret all CIE and FDE instructions up until CFI State number and
2501   /// populate this snapshot
2502   CFISnapshot(
2503       const BinaryFunction::CFIInstrMapType &CIE,
2504       const BinaryFunction::CFIInstrMapType &FDE,
2505       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2506       int32_t State)
2507       : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2508     CFAReg = UNKNOWN;
2509     CFAOffset = UNKNOWN;
2510     CFARule = UNKNOWN;
2511     CurState = 0;
2512 
2513     for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2514       const MCCFIInstruction &Instr = CIE[I];
2515       update(Instr, -I);
2516     }
2517 
2518     advanceTo(State);
2519   }
2520 };
2521 
2522 /// A CFI snapshot with the capability of checking if incremental additions to
2523 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2524 /// back-to-back that are doing the same state change, or to avoid emitting a
2525 /// CFI at all when the state at that point would not be modified after that CFI
2526 struct CFISnapshotDiff : public CFISnapshot {
2527   bool RestoredCFAReg{false};
2528   bool RestoredCFAOffset{false};
2529   DenseMap<int32_t, bool> RestoredRegs;
2530 
2531   CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2532 
2533   CFISnapshotDiff(
2534       const BinaryFunction::CFIInstrMapType &CIE,
2535       const BinaryFunction::CFIInstrMapType &FDE,
2536       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2537       int32_t State)
2538       : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2539 
2540   /// Return true if applying Instr to this state is redundant and can be
2541   /// dismissed.
2542   bool isRedundant(const MCCFIInstruction &Instr) {
2543     switch (Instr.getOperation()) {
2544     case MCCFIInstruction::OpSameValue:
2545     case MCCFIInstruction::OpRelOffset:
2546     case MCCFIInstruction::OpOffset:
2547     case MCCFIInstruction::OpRestore:
2548     case MCCFIInstruction::OpUndefined:
2549     case MCCFIInstruction::OpRegister:
2550     case MCCFIInstruction::OpEscape: {
2551       uint32_t Reg;
2552       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2553         Reg = Instr.getRegister();
2554       } else {
2555         std::optional<uint8_t> R =
2556             readDWARFExpressionTargetReg(Instr.getValues());
2557         // Handle DW_CFA_def_cfa_expression
2558         if (!R) {
2559           if (RestoredCFAReg && RestoredCFAOffset)
2560             return true;
2561           RestoredCFAReg = true;
2562           RestoredCFAOffset = true;
2563           return false;
2564         }
2565         Reg = *R;
2566       }
2567       if (RestoredRegs[Reg])
2568         return true;
2569       RestoredRegs[Reg] = true;
2570       const int32_t CurRegRule = RegRule.contains(Reg) ? RegRule[Reg] : UNKNOWN;
2571       if (CurRegRule == UNKNOWN) {
2572         if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2573             Instr.getOperation() == MCCFIInstruction::OpSameValue)
2574           return true;
2575         return false;
2576       }
2577       const MCCFIInstruction &LastDef =
2578           CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2579       return LastDef == Instr;
2580     }
2581     case MCCFIInstruction::OpDefCfaRegister:
2582       if (RestoredCFAReg)
2583         return true;
2584       RestoredCFAReg = true;
2585       return CFAReg == Instr.getRegister();
2586     case MCCFIInstruction::OpDefCfaOffset:
2587       if (RestoredCFAOffset)
2588         return true;
2589       RestoredCFAOffset = true;
2590       return CFAOffset == Instr.getOffset();
2591     case MCCFIInstruction::OpDefCfa:
2592       if (RestoredCFAReg && RestoredCFAOffset)
2593         return true;
2594       RestoredCFAReg = true;
2595       RestoredCFAOffset = true;
2596       return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2597     case MCCFIInstruction::OpAdjustCfaOffset:
2598     case MCCFIInstruction::OpWindowSave:
2599     case MCCFIInstruction::OpNegateRAState:
2600     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2601       llvm_unreachable("unsupported CFI opcode");
2602       return false;
2603     case MCCFIInstruction::OpRememberState:
2604     case MCCFIInstruction::OpRestoreState:
2605     case MCCFIInstruction::OpGnuArgsSize:
2606       // do not affect CFI state
2607       return true;
2608     }
2609     return false;
2610   }
2611 };
2612 
2613 } // end anonymous namespace
2614 
2615 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2616                                      BinaryBasicBlock *InBB,
2617                                      BinaryBasicBlock::iterator InsertIt) {
2618   if (FromState == ToState)
2619     return true;
2620   assert(FromState < ToState && "can only replay CFIs forward");
2621 
2622   CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2623                           FrameRestoreEquivalents, FromState);
2624 
2625   std::vector<uint32_t> NewCFIs;
2626   for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2627     MCCFIInstruction *Instr = &FrameInstructions[CurState];
2628     if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2629       auto Iter = FrameRestoreEquivalents.find(CurState);
2630       assert(Iter != FrameRestoreEquivalents.end());
2631       NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2632       // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2633       // so we might as well fall-through here.
2634     }
2635     NewCFIs.push_back(CurState);
2636   }
2637 
2638   // Replay instructions while avoiding duplicates
2639   for (int32_t State : llvm::reverse(NewCFIs)) {
2640     if (CFIDiff.isRedundant(FrameInstructions[State]))
2641       continue;
2642     InsertIt = addCFIPseudo(InBB, InsertIt, State);
2643   }
2644 
2645   return true;
2646 }
2647 
2648 SmallVector<int32_t, 4>
2649 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2650                                BinaryBasicBlock *InBB,
2651                                BinaryBasicBlock::iterator &InsertIt) {
2652   SmallVector<int32_t, 4> NewStates;
2653 
2654   CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2655                          FrameRestoreEquivalents, ToState);
2656   CFISnapshotDiff FromCFITable(ToCFITable);
2657   FromCFITable.advanceTo(FromState);
2658 
2659   auto undoStateDefCfa = [&]() {
2660     if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2661       FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2662           nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2663       if (FromCFITable.isRedundant(FrameInstructions.back())) {
2664         FrameInstructions.pop_back();
2665         return;
2666       }
2667       NewStates.push_back(FrameInstructions.size() - 1);
2668       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2669       ++InsertIt;
2670     } else if (ToCFITable.CFARule < 0) {
2671       if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2672         return;
2673       NewStates.push_back(FrameInstructions.size());
2674       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2675       ++InsertIt;
2676       FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2677     } else if (!FromCFITable.isRedundant(
2678                    FrameInstructions[ToCFITable.CFARule])) {
2679       NewStates.push_back(ToCFITable.CFARule);
2680       InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2681       ++InsertIt;
2682     }
2683   };
2684 
2685   auto undoState = [&](const MCCFIInstruction &Instr) {
2686     switch (Instr.getOperation()) {
2687     case MCCFIInstruction::OpRememberState:
2688     case MCCFIInstruction::OpRestoreState:
2689       break;
2690     case MCCFIInstruction::OpSameValue:
2691     case MCCFIInstruction::OpRelOffset:
2692     case MCCFIInstruction::OpOffset:
2693     case MCCFIInstruction::OpRestore:
2694     case MCCFIInstruction::OpUndefined:
2695     case MCCFIInstruction::OpEscape:
2696     case MCCFIInstruction::OpRegister: {
2697       uint32_t Reg;
2698       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2699         Reg = Instr.getRegister();
2700       } else {
2701         std::optional<uint8_t> R =
2702             readDWARFExpressionTargetReg(Instr.getValues());
2703         // Handle DW_CFA_def_cfa_expression
2704         if (!R) {
2705           undoStateDefCfa();
2706           return;
2707         }
2708         Reg = *R;
2709       }
2710 
2711       if (!ToCFITable.RegRule.contains(Reg)) {
2712         FrameInstructions.emplace_back(
2713             MCCFIInstruction::createRestore(nullptr, Reg));
2714         if (FromCFITable.isRedundant(FrameInstructions.back())) {
2715           FrameInstructions.pop_back();
2716           break;
2717         }
2718         NewStates.push_back(FrameInstructions.size() - 1);
2719         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2720         ++InsertIt;
2721         break;
2722       }
2723       const int32_t Rule = ToCFITable.RegRule[Reg];
2724       if (Rule < 0) {
2725         if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2726           break;
2727         NewStates.push_back(FrameInstructions.size());
2728         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2729         ++InsertIt;
2730         FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2731         break;
2732       }
2733       if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2734         break;
2735       NewStates.push_back(Rule);
2736       InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2737       ++InsertIt;
2738       break;
2739     }
2740     case MCCFIInstruction::OpDefCfaRegister:
2741     case MCCFIInstruction::OpDefCfaOffset:
2742     case MCCFIInstruction::OpDefCfa:
2743       undoStateDefCfa();
2744       break;
2745     case MCCFIInstruction::OpAdjustCfaOffset:
2746     case MCCFIInstruction::OpWindowSave:
2747     case MCCFIInstruction::OpNegateRAState:
2748     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2749       llvm_unreachable("unsupported CFI opcode");
2750       break;
2751     case MCCFIInstruction::OpGnuArgsSize:
2752       // do not affect CFI state
2753       break;
2754     }
2755   };
2756 
2757   // Undo all modifications from ToState to FromState
2758   for (int32_t I = ToState, E = FromState; I != E; ++I) {
2759     const MCCFIInstruction &Instr = FrameInstructions[I];
2760     if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2761       undoState(Instr);
2762       continue;
2763     }
2764     auto Iter = FrameRestoreEquivalents.find(I);
2765     if (Iter == FrameRestoreEquivalents.end())
2766       continue;
2767     for (int32_t State : Iter->second)
2768       undoState(FrameInstructions[State]);
2769   }
2770 
2771   return NewStates;
2772 }
2773 
2774 void BinaryFunction::normalizeCFIState() {
2775   // Reordering blocks with remember-restore state instructions can be specially
2776   // tricky. When rewriting the CFI, we omit remember-restore state instructions
2777   // entirely. For restore state, we build a map expanding each restore to the
2778   // equivalent unwindCFIState sequence required at that point to achieve the
2779   // same effect of the restore. All remember state are then just ignored.
2780   std::stack<int32_t> Stack;
2781   for (BinaryBasicBlock *CurBB : Layout.blocks()) {
2782     for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2783       if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2784         if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2785           Stack.push(II->getOperand(0).getImm());
2786           continue;
2787         }
2788         if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2789           const int32_t RememberState = Stack.top();
2790           const int32_t CurState = II->getOperand(0).getImm();
2791           FrameRestoreEquivalents[CurState] =
2792               unwindCFIState(CurState, RememberState, CurBB, II);
2793           Stack.pop();
2794         }
2795       }
2796     }
2797   }
2798 }
2799 
2800 bool BinaryFunction::finalizeCFIState() {
2801   LLVM_DEBUG(
2802       dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2803   LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2804                     << ": ");
2805 
2806   const char *Sep = "";
2807   (void)Sep;
2808   for (FunctionFragment &FF : Layout.fragments()) {
2809     // Hot-cold border: at start of each region (with a different FDE) we need
2810     // to reset the CFI state.
2811     int32_t State = 0;
2812 
2813     for (BinaryBasicBlock *BB : FF) {
2814       const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2815 
2816       // We need to recover the correct state if it doesn't match expected
2817       // state at BB entry point.
2818       if (BB->getCFIState() < State) {
2819         // In this case, State is currently higher than what this BB expect it
2820         // to be. To solve this, we need to insert CFI instructions to undo
2821         // the effect of all CFI from BB's state to current State.
2822         auto InsertIt = BB->begin();
2823         unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2824       } else if (BB->getCFIState() > State) {
2825         // If BB's CFI state is greater than State, it means we are behind in
2826         // the state. Just emit all instructions to reach this state at the
2827         // beginning of this BB. If this sequence of instructions involve
2828         // remember state or restore state, bail out.
2829         if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2830           return false;
2831       }
2832 
2833       State = CFIStateAtExit;
2834       LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2835     }
2836   }
2837   LLVM_DEBUG(dbgs() << "\n");
2838 
2839   for (BinaryBasicBlock &BB : blocks()) {
2840     for (auto II = BB.begin(); II != BB.end();) {
2841       const MCCFIInstruction *CFI = getCFIFor(*II);
2842       if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2843                   CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2844         II = BB.eraseInstruction(II);
2845       } else {
2846         ++II;
2847       }
2848     }
2849   }
2850 
2851   return true;
2852 }
2853 
2854 bool BinaryFunction::requiresAddressTranslation() const {
2855   return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2856 }
2857 
2858 uint64_t BinaryFunction::getInstructionCount() const {
2859   uint64_t Count = 0;
2860   for (const BinaryBasicBlock &BB : blocks())
2861     Count += BB.getNumNonPseudos();
2862   return Count;
2863 }
2864 
2865 void BinaryFunction::clearDisasmState() {
2866   clearList(Instructions);
2867   clearList(IgnoredBranches);
2868   clearList(TakenBranches);
2869 
2870   if (BC.HasRelocations) {
2871     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2872       BC.UndefinedSymbols.insert(LI.second);
2873     for (MCSymbol *const EndLabel : FunctionEndLabels)
2874       if (EndLabel)
2875         BC.UndefinedSymbols.insert(EndLabel);
2876   }
2877 }
2878 
2879 void BinaryFunction::setTrapOnEntry() {
2880   clearDisasmState();
2881 
2882   forEachEntryPoint([&](uint64_t Offset, const MCSymbol *Label) -> bool {
2883     MCInst TrapInstr;
2884     BC.MIB->createTrap(TrapInstr);
2885     addInstruction(Offset, std::move(TrapInstr));
2886     return true;
2887   });
2888 
2889   TrapsOnEntry = true;
2890 }
2891 
2892 void BinaryFunction::setIgnored() {
2893   if (opts::processAllFunctions()) {
2894     // We can accept ignored functions before they've been disassembled.
2895     // In that case, they would still get disassembled and emited, but not
2896     // optimized.
2897     assert(CurrentState == State::Empty &&
2898            "cannot ignore non-empty functions in current mode");
2899     IsIgnored = true;
2900     return;
2901   }
2902 
2903   clearDisasmState();
2904 
2905   // Clear CFG state too.
2906   if (hasCFG()) {
2907     releaseCFG();
2908 
2909     for (BinaryBasicBlock *BB : BasicBlocks)
2910       delete BB;
2911     clearList(BasicBlocks);
2912 
2913     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2914       delete BB;
2915     clearList(DeletedBasicBlocks);
2916 
2917     Layout.clear();
2918   }
2919 
2920   CurrentState = State::Empty;
2921 
2922   IsIgnored = true;
2923   IsSimple = false;
2924   LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2925 }
2926 
2927 void BinaryFunction::duplicateConstantIslands() {
2928   assert(Islands && "function expected to have constant islands");
2929 
2930   for (BinaryBasicBlock *BB : getLayout().blocks()) {
2931     if (!BB->isCold())
2932       continue;
2933 
2934     for (MCInst &Inst : *BB) {
2935       int OpNum = 0;
2936       for (MCOperand &Operand : Inst) {
2937         if (!Operand.isExpr()) {
2938           ++OpNum;
2939           continue;
2940         }
2941         const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2942         // Check if this is an island symbol
2943         if (!Islands->Symbols.count(Symbol) &&
2944             !Islands->ProxySymbols.count(Symbol))
2945           continue;
2946 
2947         // Create cold symbol, if missing
2948         auto ISym = Islands->ColdSymbols.find(Symbol);
2949         MCSymbol *ColdSymbol;
2950         if (ISym != Islands->ColdSymbols.end()) {
2951           ColdSymbol = ISym->second;
2952         } else {
2953           ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
2954           Islands->ColdSymbols[Symbol] = ColdSymbol;
2955           // Check if this is a proxy island symbol and update owner proxy map
2956           if (Islands->ProxySymbols.count(Symbol)) {
2957             BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
2958             auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
2959             Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
2960           }
2961         }
2962 
2963         // Update instruction reference
2964         Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
2965             Inst,
2966             MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
2967                                     *BC.Ctx),
2968             *BC.Ctx, 0));
2969         ++OpNum;
2970       }
2971     }
2972   }
2973 }
2974 
2975 #ifndef MAX_PATH
2976 #define MAX_PATH 255
2977 #endif
2978 
2979 static std::string constructFilename(std::string Filename,
2980                                      std::string Annotation,
2981                                      std::string Suffix) {
2982   std::replace(Filename.begin(), Filename.end(), '/', '-');
2983   if (!Annotation.empty())
2984     Annotation.insert(0, "-");
2985   if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
2986     assert(Suffix.size() + Annotation.size() <= MAX_PATH);
2987     if (opts::Verbosity >= 1) {
2988       errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
2989              << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
2990     }
2991     Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
2992   }
2993   Filename += Annotation;
2994   Filename += Suffix;
2995   return Filename;
2996 }
2997 
2998 static std::string formatEscapes(const std::string &Str) {
2999   std::string Result;
3000   for (unsigned I = 0; I < Str.size(); ++I) {
3001     char C = Str[I];
3002     switch (C) {
3003     case '\n':
3004       Result += "&#13;";
3005       break;
3006     case '"':
3007       break;
3008     default:
3009       Result += C;
3010       break;
3011     }
3012   }
3013   return Result;
3014 }
3015 
3016 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3017   OS << "digraph \"" << getPrintName() << "\" {\n"
3018      << "node [fontname=courier, shape=box, style=filled, colorscheme=brbg9]\n";
3019   uint64_t Offset = Address;
3020   for (BinaryBasicBlock *BB : BasicBlocks) {
3021     auto LayoutPos = find(Layout.blocks(), BB);
3022     unsigned LayoutIndex = LayoutPos - Layout.block_begin();
3023     const char *ColdStr = BB->isCold() ? " (cold)" : "";
3024     std::vector<std::string> Attrs;
3025     // Bold box for entry points
3026     if (isEntryPoint(*BB))
3027       Attrs.push_back("penwidth=2");
3028     if (BLI && BLI->getLoopFor(BB)) {
3029       // Distinguish innermost loops
3030       const BinaryLoop *Loop = BLI->getLoopFor(BB);
3031       if (Loop->isInnermost())
3032         Attrs.push_back("fillcolor=6");
3033       else // some outer loop
3034         Attrs.push_back("fillcolor=4");
3035     } else { // non-loopy code
3036       Attrs.push_back("fillcolor=5");
3037     }
3038     ListSeparator LS;
3039     OS << "\"" << BB->getName() << "\" [";
3040     for (StringRef Attr : Attrs)
3041       OS << LS << Attr;
3042     OS << "]\n";
3043     OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u,CFI:%u)\\n",
3044                  BB->getName().data(), BB->getName().data(), ColdStr,
3045                  BB->getKnownExecutionCount(), BB->getOffset(), getIndex(BB),
3046                  LayoutIndex, BB->getCFIState());
3047 
3048     if (opts::DotToolTipCode) {
3049       std::string Str;
3050       raw_string_ostream CS(Str);
3051       Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this,
3052                                     /* PrintMCInst = */ false,
3053                                     /* PrintMemData = */ false,
3054                                     /* PrintRelocations = */ false,
3055                                     /* Endl = */ R"(\\l)");
3056       OS << formatEscapes(CS.str()) << '\n';
3057     }
3058     OS << "\"]\n";
3059 
3060     // analyzeBranch is just used to get the names of the branch
3061     // opcodes.
3062     const MCSymbol *TBB = nullptr;
3063     const MCSymbol *FBB = nullptr;
3064     MCInst *CondBranch = nullptr;
3065     MCInst *UncondBranch = nullptr;
3066     const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3067 
3068     const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3069     const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3070 
3071     auto BI = BB->branch_info_begin();
3072     for (BinaryBasicBlock *Succ : BB->successors()) {
3073       std::string Branch;
3074       if (Success) {
3075         if (Succ == BB->getConditionalSuccessor(true)) {
3076           Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3077                                     CondBranch->getOpcode()))
3078                               : "TB";
3079         } else if (Succ == BB->getConditionalSuccessor(false)) {
3080           Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3081                                       UncondBranch->getOpcode()))
3082                                 : "FB";
3083         } else {
3084           Branch = "FT";
3085         }
3086       }
3087       if (IsJumpTable)
3088         Branch = "JT";
3089       OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3090                    Succ->getName().data(), Branch.c_str());
3091 
3092       if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3093           BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3094         OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3095       } else if (ExecutionCount != COUNT_NO_PROFILE &&
3096                  BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3097         OS << "\\n(IC:" << BI->Count << ")";
3098       }
3099       OS << "\"]\n";
3100 
3101       ++BI;
3102     }
3103     for (BinaryBasicBlock *LP : BB->landing_pads()) {
3104       OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3105                    BB->getName().data(), LP->getName().data());
3106     }
3107   }
3108   OS << "}\n";
3109 }
3110 
3111 void BinaryFunction::viewGraph() const {
3112   SmallString<MAX_PATH> Filename;
3113   if (std::error_code EC =
3114           sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3115     errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3116            << " bolt-cfg-XXXXX.dot temporary file.\n";
3117     return;
3118   }
3119   dumpGraphToFile(std::string(Filename));
3120   if (DisplayGraph(Filename))
3121     errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3122   if (std::error_code EC = sys::fs::remove(Filename)) {
3123     errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3124            << Filename << "\n";
3125   }
3126 }
3127 
3128 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3129   if (!opts::shouldPrint(*this))
3130     return;
3131 
3132   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3133   if (opts::Verbosity >= 1)
3134     outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n";
3135   dumpGraphToFile(Filename);
3136 }
3137 
3138 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3139   std::error_code EC;
3140   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3141   if (EC) {
3142     if (opts::Verbosity >= 1) {
3143       errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3144              << Filename << " for output.\n";
3145     }
3146     return;
3147   }
3148   dumpGraph(of);
3149 }
3150 
3151 bool BinaryFunction::validateCFG() const {
3152   bool Valid = true;
3153   for (BinaryBasicBlock *BB : BasicBlocks)
3154     Valid &= BB->validateSuccessorInvariants();
3155 
3156   if (!Valid)
3157     return Valid;
3158 
3159   // Make sure all blocks in CFG are valid.
3160   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3161     if (!BB->isValid()) {
3162       errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3163              << " detected in:\n";
3164       this->dump();
3165       return false;
3166     }
3167     return true;
3168   };
3169   for (const BinaryBasicBlock *BB : BasicBlocks) {
3170     if (!validateBlock(BB, "block"))
3171       return false;
3172     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3173       if (!validateBlock(PredBB, "predecessor"))
3174         return false;
3175     for (const BinaryBasicBlock *SuccBB : BB->successors())
3176       if (!validateBlock(SuccBB, "successor"))
3177         return false;
3178     for (const BinaryBasicBlock *LP : BB->landing_pads())
3179       if (!validateBlock(LP, "landing pad"))
3180         return false;
3181     for (const BinaryBasicBlock *Thrower : BB->throwers())
3182       if (!validateBlock(Thrower, "thrower"))
3183         return false;
3184   }
3185 
3186   for (const BinaryBasicBlock *BB : BasicBlocks) {
3187     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3188     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3189       if (BBLandingPads.count(LP)) {
3190         errs() << "BOLT-ERROR: duplicate landing pad detected in"
3191                << BB->getName() << " in function " << *this << '\n';
3192         return false;
3193       }
3194       BBLandingPads.insert(LP);
3195     }
3196 
3197     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3198     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3199       if (BBThrowers.count(Thrower)) {
3200         errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3201                << " in function " << *this << '\n';
3202         return false;
3203       }
3204       BBThrowers.insert(Thrower);
3205     }
3206 
3207     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3208       if (!llvm::is_contained(LPBlock->throwers(), BB)) {
3209         errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3210                << ": " << BB->getName() << " is in LandingPads but not in "
3211                << LPBlock->getName() << " Throwers\n";
3212         return false;
3213       }
3214     }
3215     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3216       if (!llvm::is_contained(Thrower->landing_pads(), BB)) {
3217         errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3218                << ": " << BB->getName() << " is in Throwers list but not in "
3219                << Thrower->getName() << " LandingPads\n";
3220         return false;
3221       }
3222     }
3223   }
3224 
3225   return Valid;
3226 }
3227 
3228 void BinaryFunction::fixBranches() {
3229   auto &MIB = BC.MIB;
3230   MCContext *Ctx = BC.Ctx.get();
3231 
3232   for (BinaryBasicBlock *BB : BasicBlocks) {
3233     const MCSymbol *TBB = nullptr;
3234     const MCSymbol *FBB = nullptr;
3235     MCInst *CondBranch = nullptr;
3236     MCInst *UncondBranch = nullptr;
3237     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3238       continue;
3239 
3240     // We will create unconditional branch with correct destination if needed.
3241     if (UncondBranch)
3242       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3243 
3244     // Basic block that follows the current one in the final layout.
3245     const BinaryBasicBlock *NextBB =
3246         Layout.getBasicBlockAfter(BB, /*IgnoreSplits=*/false);
3247 
3248     if (BB->succ_size() == 1) {
3249       // __builtin_unreachable() could create a conditional branch that
3250       // falls-through into the next function - hence the block will have only
3251       // one valid successor. Since behaviour is undefined - we replace
3252       // the conditional branch with an unconditional if required.
3253       if (CondBranch)
3254         BB->eraseInstruction(BB->findInstruction(CondBranch));
3255       if (BB->getSuccessor() == NextBB)
3256         continue;
3257       BB->addBranchInstruction(BB->getSuccessor());
3258     } else if (BB->succ_size() == 2) {
3259       assert(CondBranch && "conditional branch expected");
3260       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3261       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3262       // Check whether we support reversing this branch direction
3263       const bool IsSupported = !MIB->isUnsupportedBranch(*CondBranch);
3264       if (NextBB && NextBB == TSuccessor && IsSupported) {
3265         std::swap(TSuccessor, FSuccessor);
3266         {
3267           auto L = BC.scopeLock();
3268           MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3269         }
3270         BB->swapConditionalSuccessors();
3271       } else {
3272         auto L = BC.scopeLock();
3273         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3274       }
3275       if (TSuccessor == FSuccessor)
3276         BB->removeDuplicateConditionalSuccessor(CondBranch);
3277       if (!NextBB ||
3278           ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3279         // If one of the branches is guaranteed to be "long" while the other
3280         // could be "short", then prioritize short for "taken". This will
3281         // generate a sequence 1 byte shorter on x86.
3282         if (IsSupported && BC.isX86() &&
3283             TSuccessor->getFragmentNum() != FSuccessor->getFragmentNum() &&
3284             BB->getFragmentNum() != TSuccessor->getFragmentNum()) {
3285           std::swap(TSuccessor, FSuccessor);
3286           {
3287             auto L = BC.scopeLock();
3288             MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3289                                         Ctx);
3290           }
3291           BB->swapConditionalSuccessors();
3292         }
3293         BB->addBranchInstruction(FSuccessor);
3294       }
3295     }
3296     // Cases where the number of successors is 0 (block ends with a
3297     // terminator) or more than 2 (switch table) don't require branch
3298     // instruction adjustments.
3299   }
3300   assert((!isSimple() || validateCFG()) &&
3301          "Invalid CFG detected after fixing branches");
3302 }
3303 
3304 void BinaryFunction::propagateGnuArgsSizeInfo(
3305     MCPlusBuilder::AllocatorIdTy AllocId) {
3306   assert(CurrentState == State::Disassembled && "unexpected function state");
3307 
3308   if (!hasEHRanges() || !usesGnuArgsSize())
3309     return;
3310 
3311   // The current value of DW_CFA_GNU_args_size affects all following
3312   // invoke instructions until the next CFI overrides it.
3313   // It is important to iterate basic blocks in the original order when
3314   // assigning the value.
3315   uint64_t CurrentGnuArgsSize = 0;
3316   for (BinaryBasicBlock *BB : BasicBlocks) {
3317     for (auto II = BB->begin(); II != BB->end();) {
3318       MCInst &Instr = *II;
3319       if (BC.MIB->isCFI(Instr)) {
3320         const MCCFIInstruction *CFI = getCFIFor(Instr);
3321         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3322           CurrentGnuArgsSize = CFI->getOffset();
3323           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3324           // during the final code emission. The information is embedded
3325           // inside call instructions.
3326           II = BB->erasePseudoInstruction(II);
3327           continue;
3328         }
3329       } else if (BC.MIB->isInvoke(Instr)) {
3330         // Add the value of GNU_args_size as an extra operand to invokes.
3331         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3332       }
3333       ++II;
3334     }
3335   }
3336 }
3337 
3338 void BinaryFunction::postProcessBranches() {
3339   if (!isSimple())
3340     return;
3341   for (BinaryBasicBlock &BB : blocks()) {
3342     auto LastInstrRI = BB.getLastNonPseudo();
3343     if (BB.succ_size() == 1) {
3344       if (LastInstrRI != BB.rend() &&
3345           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3346         // __builtin_unreachable() could create a conditional branch that
3347         // falls-through into the next function - hence the block will have only
3348         // one valid successor. Such behaviour is undefined and thus we remove
3349         // the conditional branch while leaving a valid successor.
3350         BB.eraseInstruction(std::prev(LastInstrRI.base()));
3351         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3352                           << BB.getName() << " in function " << *this << '\n');
3353       }
3354     } else if (BB.succ_size() == 0) {
3355       // Ignore unreachable basic blocks.
3356       if (BB.pred_size() == 0 || BB.isLandingPad())
3357         continue;
3358 
3359       // If it's the basic block that does not end up with a terminator - we
3360       // insert a return instruction unless it's a call instruction.
3361       if (LastInstrRI == BB.rend()) {
3362         LLVM_DEBUG(
3363             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3364                    << BB.getName() << " in function " << *this << '\n');
3365         continue;
3366       }
3367       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3368           !BC.MIB->isCall(*LastInstrRI)) {
3369         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3370                           << BB.getName() << " in function " << *this << '\n');
3371         MCInst ReturnInstr;
3372         BC.MIB->createReturn(ReturnInstr);
3373         BB.addInstruction(ReturnInstr);
3374       }
3375     }
3376   }
3377   assert(validateCFG() && "invalid CFG");
3378 }
3379 
3380 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3381   assert(Offset && "cannot add primary entry point");
3382   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3383 
3384   const uint64_t EntryPointAddress = getAddress() + Offset;
3385   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3386 
3387   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3388   if (EntrySymbol)
3389     return EntrySymbol;
3390 
3391   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3392     EntrySymbol = EntryBD->getSymbol();
3393   } else {
3394     EntrySymbol = BC.getOrCreateGlobalSymbol(
3395         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3396   }
3397   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3398 
3399   BC.setSymbolToFunctionMap(EntrySymbol, this);
3400 
3401   return EntrySymbol;
3402 }
3403 
3404 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3405   assert(CurrentState == State::CFG &&
3406          "basic block can be added as an entry only in a function with CFG");
3407 
3408   if (&BB == BasicBlocks.front())
3409     return getSymbol();
3410 
3411   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3412   if (EntrySymbol)
3413     return EntrySymbol;
3414 
3415   EntrySymbol =
3416       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3417 
3418   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3419 
3420   BC.setSymbolToFunctionMap(EntrySymbol, this);
3421 
3422   return EntrySymbol;
3423 }
3424 
3425 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3426   if (EntryID == 0)
3427     return getSymbol();
3428 
3429   if (!isMultiEntry())
3430     return nullptr;
3431 
3432   uint64_t NumEntries = 0;
3433   if (hasCFG()) {
3434     for (BinaryBasicBlock *BB : BasicBlocks) {
3435       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3436       if (!EntrySymbol)
3437         continue;
3438       if (NumEntries == EntryID)
3439         return EntrySymbol;
3440       ++NumEntries;
3441     }
3442   } else {
3443     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3444       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3445       if (!EntrySymbol)
3446         continue;
3447       if (NumEntries == EntryID)
3448         return EntrySymbol;
3449       ++NumEntries;
3450     }
3451   }
3452 
3453   return nullptr;
3454 }
3455 
3456 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3457   if (!isMultiEntry())
3458     return 0;
3459 
3460   for (const MCSymbol *FunctionSymbol : getSymbols())
3461     if (FunctionSymbol == Symbol)
3462       return 0;
3463 
3464   // Check all secondary entries available as either basic blocks or lables.
3465   uint64_t NumEntries = 0;
3466   for (const BinaryBasicBlock *BB : BasicBlocks) {
3467     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3468     if (!EntrySymbol)
3469       continue;
3470     if (EntrySymbol == Symbol)
3471       return NumEntries;
3472     ++NumEntries;
3473   }
3474   NumEntries = 0;
3475   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3476     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3477     if (!EntrySymbol)
3478       continue;
3479     if (EntrySymbol == Symbol)
3480       return NumEntries;
3481     ++NumEntries;
3482   }
3483 
3484   llvm_unreachable("symbol not found");
3485 }
3486 
3487 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3488   bool Status = Callback(0, getSymbol());
3489   if (!isMultiEntry())
3490     return Status;
3491 
3492   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3493     if (!Status)
3494       break;
3495 
3496     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3497     if (!EntrySymbol)
3498       continue;
3499 
3500     Status = Callback(KV.first, EntrySymbol);
3501   }
3502 
3503   return Status;
3504 }
3505 
3506 BinaryFunction::BasicBlockListType BinaryFunction::dfs() const {
3507   BasicBlockListType DFS;
3508   unsigned Index = 0;
3509   std::stack<BinaryBasicBlock *> Stack;
3510 
3511   // Push entry points to the stack in reverse order.
3512   //
3513   // NB: we rely on the original order of entries to match.
3514   SmallVector<BinaryBasicBlock *> EntryPoints;
3515   llvm::copy_if(BasicBlocks, std::back_inserter(EntryPoints),
3516           [&](const BinaryBasicBlock *const BB) { return isEntryPoint(*BB); });
3517   // Sort entry points by their offset to make sure we got them in the right
3518   // order.
3519   llvm::stable_sort(EntryPoints, [](const BinaryBasicBlock *const A,
3520                               const BinaryBasicBlock *const B) {
3521     return A->getOffset() < B->getOffset();
3522   });
3523   for (BinaryBasicBlock *const BB : reverse(EntryPoints))
3524     Stack.push(BB);
3525 
3526   for (BinaryBasicBlock &BB : blocks())
3527     BB.setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3528 
3529   while (!Stack.empty()) {
3530     BinaryBasicBlock *BB = Stack.top();
3531     Stack.pop();
3532 
3533     if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3534       continue;
3535 
3536     BB->setLayoutIndex(Index++);
3537     DFS.push_back(BB);
3538 
3539     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3540       Stack.push(SuccBB);
3541     }
3542 
3543     const MCSymbol *TBB = nullptr;
3544     const MCSymbol *FBB = nullptr;
3545     MCInst *CondBranch = nullptr;
3546     MCInst *UncondBranch = nullptr;
3547     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3548         BB->succ_size() == 2) {
3549       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3550               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3551         Stack.push(BB->getConditionalSuccessor(true));
3552         Stack.push(BB->getConditionalSuccessor(false));
3553       } else {
3554         Stack.push(BB->getConditionalSuccessor(false));
3555         Stack.push(BB->getConditionalSuccessor(true));
3556       }
3557     } else {
3558       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3559         Stack.push(SuccBB);
3560       }
3561     }
3562   }
3563 
3564   return DFS;
3565 }
3566 
3567 size_t BinaryFunction::computeHash(bool UseDFS,
3568                                    OperandHashFuncTy OperandHashFunc) const {
3569   if (size() == 0)
3570     return 0;
3571 
3572   assert(hasCFG() && "function is expected to have CFG");
3573 
3574   SmallVector<const BinaryBasicBlock *, 0> Order;
3575   if (UseDFS)
3576     llvm::copy(dfs(), std::back_inserter(Order));
3577   else
3578     llvm::copy(Layout.blocks(), std::back_inserter(Order));
3579 
3580   // The hash is computed by creating a string of all instruction opcodes and
3581   // possibly their operands and then hashing that string with std::hash.
3582   std::string HashString;
3583   for (const BinaryBasicBlock *BB : Order)
3584     HashString.append(hashBlock(BC, *BB, OperandHashFunc));
3585 
3586   return Hash = std::hash<std::string>{}(HashString);
3587 }
3588 
3589 void BinaryFunction::insertBasicBlocks(
3590     BinaryBasicBlock *Start,
3591     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3592     const bool UpdateLayout, const bool UpdateCFIState,
3593     const bool RecomputeLandingPads) {
3594   const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3595   const size_t NumNewBlocks = NewBBs.size();
3596 
3597   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3598                      nullptr);
3599 
3600   int64_t I = StartIndex + 1;
3601   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3602     assert(!BasicBlocks[I]);
3603     BasicBlocks[I++] = BB.release();
3604   }
3605 
3606   if (RecomputeLandingPads)
3607     recomputeLandingPads();
3608   else
3609     updateBBIndices(0);
3610 
3611   if (UpdateLayout)
3612     updateLayout(Start, NumNewBlocks);
3613 
3614   if (UpdateCFIState)
3615     updateCFIState(Start, NumNewBlocks);
3616 }
3617 
3618 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3619     BinaryFunction::iterator StartBB,
3620     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3621     const bool UpdateLayout, const bool UpdateCFIState,
3622     const bool RecomputeLandingPads) {
3623   const unsigned StartIndex = getIndex(&*StartBB);
3624   const size_t NumNewBlocks = NewBBs.size();
3625 
3626   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3627                      nullptr);
3628   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3629 
3630   unsigned I = StartIndex + 1;
3631   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3632     assert(!BasicBlocks[I]);
3633     BasicBlocks[I++] = BB.release();
3634   }
3635 
3636   if (RecomputeLandingPads)
3637     recomputeLandingPads();
3638   else
3639     updateBBIndices(0);
3640 
3641   if (UpdateLayout)
3642     updateLayout(*std::prev(RetIter), NumNewBlocks);
3643 
3644   if (UpdateCFIState)
3645     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3646 
3647   return RetIter;
3648 }
3649 
3650 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3651   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3652     BasicBlocks[I]->Index = I;
3653 }
3654 
3655 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3656                                     const unsigned NumNewBlocks) {
3657   const int32_t CFIState = Start->getCFIStateAtExit();
3658   const unsigned StartIndex = getIndex(Start) + 1;
3659   for (unsigned I = 0; I < NumNewBlocks; ++I)
3660     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3661 }
3662 
3663 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3664                                   const unsigned NumNewBlocks) {
3665   BasicBlockListType::iterator Begin;
3666   BasicBlockListType::iterator End;
3667 
3668   // If start not provided copy new blocks from the beginning of BasicBlocks
3669   if (!Start) {
3670     Begin = BasicBlocks.begin();
3671     End = BasicBlocks.begin() + NumNewBlocks;
3672   } else {
3673     unsigned StartIndex = getIndex(Start);
3674     Begin = std::next(BasicBlocks.begin(), StartIndex + 1);
3675     End = std::next(BasicBlocks.begin(), StartIndex + NumNewBlocks + 1);
3676   }
3677 
3678   // Insert new blocks in the layout immediately after Start.
3679   Layout.insertBasicBlocks(Start, {Begin, End});
3680   Layout.updateLayoutIndices();
3681 }
3682 
3683 bool BinaryFunction::checkForAmbiguousJumpTables() {
3684   SmallSet<uint64_t, 4> JumpTables;
3685   for (BinaryBasicBlock *&BB : BasicBlocks) {
3686     for (MCInst &Inst : *BB) {
3687       if (!BC.MIB->isIndirectBranch(Inst))
3688         continue;
3689       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3690       if (!JTAddress)
3691         continue;
3692       // This address can be inside another jump table, but we only consider
3693       // it ambiguous when the same start address is used, not the same JT
3694       // object.
3695       if (!JumpTables.count(JTAddress)) {
3696         JumpTables.insert(JTAddress);
3697         continue;
3698       }
3699       return true;
3700     }
3701   }
3702   return false;
3703 }
3704 
3705 void BinaryFunction::disambiguateJumpTables(
3706     MCPlusBuilder::AllocatorIdTy AllocId) {
3707   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3708   SmallPtrSet<JumpTable *, 4> JumpTables;
3709   for (BinaryBasicBlock *&BB : BasicBlocks) {
3710     for (MCInst &Inst : *BB) {
3711       if (!BC.MIB->isIndirectBranch(Inst))
3712         continue;
3713       JumpTable *JT = getJumpTable(Inst);
3714       if (!JT)
3715         continue;
3716       auto Iter = JumpTables.find(JT);
3717       if (Iter == JumpTables.end()) {
3718         JumpTables.insert(JT);
3719         continue;
3720       }
3721       // This instruction is an indirect jump using a jump table, but it is
3722       // using the same jump table of another jump. Try all our tricks to
3723       // extract the jump table symbol and make it point to a new, duplicated JT
3724       MCPhysReg BaseReg1;
3725       uint64_t Scale;
3726       const MCSymbol *Target;
3727       // In case we match if our first matcher, first instruction is the one to
3728       // patch
3729       MCInst *JTLoadInst = &Inst;
3730       // Try a standard indirect jump matcher, scale 8
3731       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3732           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3733                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3734                               /*Offset=*/BC.MIB->matchSymbol(Target));
3735       if (!IndJmpMatcher->match(
3736               *BC.MRI, *BC.MIB,
3737               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3738           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3739         MCPhysReg BaseReg2;
3740         uint64_t Offset;
3741         // Standard JT matching failed. Trying now:
3742         //     movq  "jt.2397/1"(,%rax,8), %rax
3743         //     jmpq  *%rax
3744         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3745             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3746                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3747                               /*Offset=*/BC.MIB->matchSymbol(Target));
3748         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3749         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3750             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3751         if (!IndJmpMatcher2->match(
3752                 *BC.MRI, *BC.MIB,
3753                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3754             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3755           // JT matching failed. Trying now:
3756           // PIC-style matcher, scale 4
3757           //    addq    %rdx, %rsi
3758           //    addq    %rdx, %rdi
3759           //    leaq    DATAat0x402450(%rip), %r11
3760           //    movslq  (%r11,%rdx,4), %rcx
3761           //    addq    %r11, %rcx
3762           //    jmpq    *%rcx # JUMPTABLE @0x402450
3763           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3764               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3765                   BC.MIB->matchReg(BaseReg1),
3766                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3767                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3768                                     BC.MIB->matchImm(Offset))));
3769           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3770               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3771           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3772           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3773               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3774                                                    BC.MIB->matchAnyOperand()));
3775           if (!PICIndJmpMatcher->match(
3776                   *BC.MRI, *BC.MIB,
3777                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3778               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3779               !PICBaseAddrMatcher->match(
3780                   *BC.MRI, *BC.MIB,
3781                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3782             llvm_unreachable("Failed to extract jump table base");
3783             continue;
3784           }
3785           // Matched PIC, identify the instruction with the reference to the JT
3786           JTLoadInst = LEAMatcher->CurInst;
3787         } else {
3788           // Matched non-PIC
3789           JTLoadInst = LoadMatcher->CurInst;
3790         }
3791       }
3792 
3793       uint64_t NewJumpTableID = 0;
3794       const MCSymbol *NewJTLabel;
3795       std::tie(NewJumpTableID, NewJTLabel) =
3796           BC.duplicateJumpTable(*this, JT, Target);
3797       {
3798         auto L = BC.scopeLock();
3799         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3800       }
3801       // We use a unique ID with the high bit set as address for this "injected"
3802       // jump table (not originally in the input binary).
3803       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3804     }
3805   }
3806 }
3807 
3808 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3809                                              BinaryBasicBlock *OldDest,
3810                                              BinaryBasicBlock *NewDest) {
3811   MCInst *Instr = BB->getLastNonPseudoInstr();
3812   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3813     return false;
3814   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3815   assert(JTAddress && "Invalid jump table address");
3816   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3817   assert(JT && "No jump table structure for this indirect branch");
3818   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3819                                         NewDest->getLabel());
3820   (void)Patched;
3821   assert(Patched && "Invalid entry to be replaced in jump table");
3822   return true;
3823 }
3824 
3825 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3826                                             BinaryBasicBlock *To) {
3827   // Create intermediate BB
3828   MCSymbol *Tmp;
3829   {
3830     auto L = BC.scopeLock();
3831     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3832   }
3833   // Link new BBs to the original input offset of the From BB, so we can map
3834   // samples recorded in new BBs back to the original BB seem in the input
3835   // binary (if using BAT)
3836   std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp);
3837   NewBB->setOffset(From->getInputOffset());
3838   BinaryBasicBlock *NewBBPtr = NewBB.get();
3839 
3840   // Update "From" BB
3841   auto I = From->succ_begin();
3842   auto BI = From->branch_info_begin();
3843   for (; I != From->succ_end(); ++I) {
3844     if (*I == To)
3845       break;
3846     ++BI;
3847   }
3848   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3849   uint64_t OrigCount = BI->Count;
3850   uint64_t OrigMispreds = BI->MispredictedCount;
3851   replaceJumpTableEntryIn(From, To, NewBBPtr);
3852   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3853 
3854   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3855   NewBB->setExecutionCount(OrigCount);
3856   NewBB->setIsCold(From->isCold());
3857 
3858   // Update CFI and BB layout with new intermediate BB
3859   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3860   NewBBs.emplace_back(std::move(NewBB));
3861   insertBasicBlocks(From, std::move(NewBBs), true, true,
3862                     /*RecomputeLandingPads=*/false);
3863   return NewBBPtr;
3864 }
3865 
3866 void BinaryFunction::deleteConservativeEdges() {
3867   // Our goal is to aggressively remove edges from the CFG that we believe are
3868   // wrong. This is used for instrumentation, where it is safe to remove
3869   // fallthrough edges because we won't reorder blocks.
3870   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3871     BinaryBasicBlock *BB = *I;
3872     if (BB->succ_size() != 1 || BB->size() == 0)
3873       continue;
3874 
3875     auto NextBB = std::next(I);
3876     MCInst *Last = BB->getLastNonPseudoInstr();
3877     // Fallthrough is a landing pad? Delete this edge (as long as we don't
3878     // have a direct jump to it)
3879     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3880         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3881       BB->removeAllSuccessors();
3882       continue;
3883     }
3884 
3885     // Look for suspicious calls at the end of BB where gcc may optimize it and
3886     // remove the jump to the epilogue when it knows the call won't return.
3887     if (!Last || !BC.MIB->isCall(*Last))
3888       continue;
3889 
3890     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3891     if (!CalleeSymbol)
3892       continue;
3893 
3894     StringRef CalleeName = CalleeSymbol->getName();
3895     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3896         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3897         CalleeName != "abort@PLT")
3898       continue;
3899 
3900     BB->removeAllSuccessors();
3901   }
3902 }
3903 
3904 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3905                                           uint64_t SymbolSize) const {
3906   // If this symbol is in a different section from the one where the
3907   // function symbol is, don't consider it as valid.
3908   if (!getOriginSection()->containsAddress(
3909           cantFail(Symbol.getAddress(), "cannot get symbol address")))
3910     return false;
3911 
3912   // Some symbols are tolerated inside function bodies, others are not.
3913   // The real function boundaries may not be known at this point.
3914   if (BC.isMarker(Symbol))
3915     return true;
3916 
3917   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3918   // function.
3919   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3920     return true;
3921 
3922   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3923     return false;
3924 
3925   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3926     return false;
3927 
3928   return true;
3929 }
3930 
3931 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3932   if (getKnownExecutionCount() == 0 || Count == 0)
3933     return;
3934 
3935   if (ExecutionCount < Count)
3936     Count = ExecutionCount;
3937 
3938   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
3939   if (AdjustmentRatio < 0.0)
3940     AdjustmentRatio = 0.0;
3941 
3942   for (BinaryBasicBlock &BB : blocks())
3943     BB.adjustExecutionCount(AdjustmentRatio);
3944 
3945   ExecutionCount -= Count;
3946 }
3947 
3948 BinaryFunction::~BinaryFunction() {
3949   for (BinaryBasicBlock *BB : BasicBlocks)
3950     delete BB;
3951   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
3952     delete BB;
3953 }
3954 
3955 void BinaryFunction::calculateLoopInfo() {
3956   // Discover loops.
3957   BinaryDominatorTree DomTree;
3958   DomTree.recalculate(*this);
3959   BLI.reset(new BinaryLoopInfo());
3960   BLI->analyze(DomTree);
3961 
3962   // Traverse discovered loops and add depth and profile information.
3963   std::stack<BinaryLoop *> St;
3964   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
3965     St.push(*I);
3966     ++BLI->OuterLoops;
3967   }
3968 
3969   while (!St.empty()) {
3970     BinaryLoop *L = St.top();
3971     St.pop();
3972     ++BLI->TotalLoops;
3973     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
3974 
3975     // Add nested loops in the stack.
3976     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3977       St.push(*I);
3978 
3979     // Skip if no valid profile is found.
3980     if (!hasValidProfile()) {
3981       L->EntryCount = COUNT_NO_PROFILE;
3982       L->ExitCount = COUNT_NO_PROFILE;
3983       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
3984       continue;
3985     }
3986 
3987     // Compute back edge count.
3988     SmallVector<BinaryBasicBlock *, 1> Latches;
3989     L->getLoopLatches(Latches);
3990 
3991     for (BinaryBasicBlock *Latch : Latches) {
3992       auto BI = Latch->branch_info_begin();
3993       for (BinaryBasicBlock *Succ : Latch->successors()) {
3994         if (Succ == L->getHeader()) {
3995           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
3996                  "profile data not found");
3997           L->TotalBackEdgeCount += BI->Count;
3998         }
3999         ++BI;
4000       }
4001     }
4002 
4003     // Compute entry count.
4004     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4005 
4006     // Compute exit count.
4007     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4008     L->getExitEdges(ExitEdges);
4009     for (BinaryLoop::Edge &Exit : ExitEdges) {
4010       const BinaryBasicBlock *Exiting = Exit.first;
4011       const BinaryBasicBlock *ExitTarget = Exit.second;
4012       auto BI = Exiting->branch_info_begin();
4013       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4014         if (Succ == ExitTarget) {
4015           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4016                  "profile data not found");
4017           L->ExitCount += BI->Count;
4018         }
4019         ++BI;
4020       }
4021     }
4022   }
4023 }
4024 
4025 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4026   if (!isEmitted()) {
4027     assert(!isInjected() && "injected function should be emitted");
4028     setOutputAddress(getAddress());
4029     setOutputSize(getSize());
4030     return;
4031   }
4032 
4033   const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4034   if (BC.HasRelocations || isInjected()) {
4035     const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4036     const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4037     setOutputAddress(BaseAddress + StartOffset);
4038     setOutputSize(EndOffset - StartOffset);
4039     if (hasConstantIsland()) {
4040       const uint64_t DataOffset =
4041           Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4042       setOutputDataAddress(BaseAddress + DataOffset);
4043       for (auto It : Islands->Offsets) {
4044         const uint64_t OldOffset = It.first;
4045         BinaryData *BD = BC.getBinaryDataAtAddress(getAddress() + OldOffset);
4046         if (!BD)
4047           continue;
4048 
4049         MCSymbol *Symbol = It.second;
4050         const uint64_t NewOffset = Layout.getSymbolOffset(*Symbol);
4051         BD->setOutputLocation(*getCodeSection(), NewOffset);
4052       }
4053     }
4054     if (isSplit()) {
4055       for (FunctionFragment &FF : getLayout().getSplitFragments()) {
4056         ErrorOr<BinarySection &> ColdSection =
4057             getCodeSection(FF.getFragmentNum());
4058         // If fragment is empty, cold section might not exist
4059         if (FF.empty() && ColdSection.getError())
4060           continue;
4061         const uint64_t ColdBaseAddress = ColdSection->getOutputAddress();
4062 
4063         const MCSymbol *ColdStartSymbol = getSymbol(FF.getFragmentNum());
4064         // If fragment is empty, symbol might have not been emitted
4065         if (FF.empty() && (!ColdStartSymbol || !ColdStartSymbol->isDefined()) &&
4066             !hasConstantIsland())
4067           continue;
4068         assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4069                "split function should have defined cold symbol");
4070         const MCSymbol *ColdEndSymbol =
4071             getFunctionEndLabel(FF.getFragmentNum());
4072         assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4073                "split function should have defined cold end symbol");
4074         const uint64_t ColdStartOffset =
4075             Layout.getSymbolOffset(*ColdStartSymbol);
4076         const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4077         FF.setAddress(ColdBaseAddress + ColdStartOffset);
4078         FF.setImageSize(ColdEndOffset - ColdStartOffset);
4079         if (hasConstantIsland()) {
4080           const uint64_t DataOffset =
4081               Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4082           setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4083         }
4084       }
4085     }
4086   } else {
4087     setOutputAddress(getAddress());
4088     setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4089   }
4090 
4091   // Update basic block output ranges for the debug info, if we have
4092   // secondary entry points in the symbol table to update or if writing BAT.
4093   if (!opts::UpdateDebugSections && !isMultiEntry() &&
4094       !requiresAddressTranslation())
4095     return;
4096 
4097   // Output ranges should match the input if the body hasn't changed.
4098   if (!isSimple() && !BC.HasRelocations)
4099     return;
4100 
4101   // AArch64 may have functions that only contains a constant island (no code).
4102   if (getLayout().block_empty())
4103     return;
4104 
4105   for (FunctionFragment &FF : getLayout().fragments()) {
4106     if (FF.empty())
4107       continue;
4108 
4109     const uint64_t FragmentBaseAddress =
4110         getCodeSection(isSimple() ? FF.getFragmentNum() : FragmentNum::main())
4111             ->getOutputAddress();
4112 
4113     BinaryBasicBlock *PrevBB = nullptr;
4114     for (BinaryBasicBlock *const BB : FF) {
4115       assert(BB->getLabel()->isDefined() && "symbol should be defined");
4116       if (!BC.HasRelocations) {
4117         if (BB->isSplit())
4118           assert(FragmentBaseAddress == FF.getAddress());
4119         else
4120           assert(FragmentBaseAddress == getOutputAddress());
4121       }
4122 
4123       const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4124       const uint64_t BBAddress = FragmentBaseAddress + BBOffset;
4125       BB->setOutputStartAddress(BBAddress);
4126 
4127       if (PrevBB)
4128         PrevBB->setOutputEndAddress(BBAddress);
4129       PrevBB = BB;
4130 
4131       BB->updateOutputValues(Layout);
4132     }
4133 
4134     PrevBB->setOutputEndAddress(PrevBB->isSplit()
4135                                     ? FF.getAddress() + FF.getImageSize()
4136                                     : getOutputAddress() + getOutputSize());
4137   }
4138 }
4139 
4140 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4141   DebugAddressRangesVector OutputRanges;
4142 
4143   if (isFolded())
4144     return OutputRanges;
4145 
4146   if (IsFragment)
4147     return OutputRanges;
4148 
4149   OutputRanges.emplace_back(getOutputAddress(),
4150                             getOutputAddress() + getOutputSize());
4151   if (isSplit()) {
4152     assert(isEmitted() && "split function should be emitted");
4153     for (const FunctionFragment &FF : getLayout().getSplitFragments())
4154       OutputRanges.emplace_back(FF.getAddress(),
4155                                 FF.getAddress() + FF.getImageSize());
4156   }
4157 
4158   if (isSimple())
4159     return OutputRanges;
4160 
4161   for (BinaryFunction *Frag : Fragments) {
4162     assert(!Frag->isSimple() &&
4163            "fragment of non-simple function should also be non-simple");
4164     OutputRanges.emplace_back(Frag->getOutputAddress(),
4165                               Frag->getOutputAddress() + Frag->getOutputSize());
4166   }
4167 
4168   return OutputRanges;
4169 }
4170 
4171 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4172   if (isFolded())
4173     return 0;
4174 
4175   // If the function hasn't changed return the same address.
4176   if (!isEmitted())
4177     return Address;
4178 
4179   if (Address < getAddress())
4180     return 0;
4181 
4182   // Check if the address is associated with an instruction that is tracked
4183   // by address translation.
4184   auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4185   if (KV != InputOffsetToAddressMap.end())
4186     return KV->second;
4187 
4188   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4189   //        intact. Instead we can use pseudo instructions and/or annotations.
4190   const uint64_t Offset = Address - getAddress();
4191   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4192   if (!BB) {
4193     // Special case for address immediately past the end of the function.
4194     if (Offset == getSize())
4195       return getOutputAddress() + getOutputSize();
4196 
4197     return 0;
4198   }
4199 
4200   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4201                   BB->getOutputAddressRange().second);
4202 }
4203 
4204 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4205     const DWARFAddressRangesVector &InputRanges) const {
4206   DebugAddressRangesVector OutputRanges;
4207 
4208   if (isFolded())
4209     return OutputRanges;
4210 
4211   // If the function hasn't changed return the same ranges.
4212   if (!isEmitted()) {
4213     OutputRanges.resize(InputRanges.size());
4214     llvm::transform(InputRanges, OutputRanges.begin(),
4215                     [](const DWARFAddressRange &Range) {
4216                       return DebugAddressRange(Range.LowPC, Range.HighPC);
4217                     });
4218     return OutputRanges;
4219   }
4220 
4221   // Even though we will merge ranges in a post-processing pass, we attempt to
4222   // merge them in a main processing loop as it improves the processing time.
4223   uint64_t PrevEndAddress = 0;
4224   for (const DWARFAddressRange &Range : InputRanges) {
4225     if (!containsAddress(Range.LowPC)) {
4226       LLVM_DEBUG(
4227           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4228                  << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4229                  << Twine::utohexstr(Range.HighPC) << "]\n");
4230       PrevEndAddress = 0;
4231       continue;
4232     }
4233     uint64_t InputOffset = Range.LowPC - getAddress();
4234     const uint64_t InputEndOffset =
4235         std::min(Range.HighPC - getAddress(), getSize());
4236 
4237     auto BBI = llvm::upper_bound(BasicBlockOffsets,
4238                                  BasicBlockOffset(InputOffset, nullptr),
4239                                  CompareBasicBlockOffsets());
4240     --BBI;
4241     do {
4242       const BinaryBasicBlock *BB = BBI->second;
4243       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4244         LLVM_DEBUG(
4245             dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4246                    << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4247                    << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4248         PrevEndAddress = 0;
4249         break;
4250       }
4251 
4252       // Skip the range if the block was deleted.
4253       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4254         const uint64_t StartAddress =
4255             OutputStart + InputOffset - BB->getOffset();
4256         uint64_t EndAddress = BB->getOutputAddressRange().second;
4257         if (InputEndOffset < BB->getEndOffset())
4258           EndAddress = StartAddress + InputEndOffset - InputOffset;
4259 
4260         if (StartAddress == PrevEndAddress) {
4261           OutputRanges.back().HighPC =
4262               std::max(OutputRanges.back().HighPC, EndAddress);
4263         } else {
4264           OutputRanges.emplace_back(StartAddress,
4265                                     std::max(StartAddress, EndAddress));
4266         }
4267         PrevEndAddress = OutputRanges.back().HighPC;
4268       }
4269 
4270       InputOffset = BB->getEndOffset();
4271       ++BBI;
4272     } while (InputOffset < InputEndOffset);
4273   }
4274 
4275   // Post-processing pass to sort and merge ranges.
4276   llvm::sort(OutputRanges);
4277   DebugAddressRangesVector MergedRanges;
4278   PrevEndAddress = 0;
4279   for (const DebugAddressRange &Range : OutputRanges) {
4280     if (Range.LowPC <= PrevEndAddress) {
4281       MergedRanges.back().HighPC =
4282           std::max(MergedRanges.back().HighPC, Range.HighPC);
4283     } else {
4284       MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4285     }
4286     PrevEndAddress = MergedRanges.back().HighPC;
4287   }
4288 
4289   return MergedRanges;
4290 }
4291 
4292 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4293   if (CurrentState == State::Disassembled) {
4294     auto II = Instructions.find(Offset);
4295     return (II == Instructions.end()) ? nullptr : &II->second;
4296   } else if (CurrentState == State::CFG) {
4297     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4298     if (!BB)
4299       return nullptr;
4300 
4301     for (MCInst &Inst : *BB) {
4302       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4303       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4304         return &Inst;
4305     }
4306 
4307     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4308       const uint32_t Size =
4309           BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4310       if (BB->getEndOffset() - Offset == Size)
4311         return LastInstr;
4312     }
4313 
4314     return nullptr;
4315   } else {
4316     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4317   }
4318 }
4319 
4320 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4321     const DebugLocationsVector &InputLL) const {
4322   DebugLocationsVector OutputLL;
4323 
4324   if (isFolded())
4325     return OutputLL;
4326 
4327   // If the function hasn't changed - there's nothing to update.
4328   if (!isEmitted())
4329     return InputLL;
4330 
4331   uint64_t PrevEndAddress = 0;
4332   SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4333   for (const DebugLocationEntry &Entry : InputLL) {
4334     const uint64_t Start = Entry.LowPC;
4335     const uint64_t End = Entry.HighPC;
4336     if (!containsAddress(Start)) {
4337       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4338                            "for "
4339                         << *this << " : [0x" << Twine::utohexstr(Start)
4340                         << ", 0x" << Twine::utohexstr(End) << "]\n");
4341       continue;
4342     }
4343     uint64_t InputOffset = Start - getAddress();
4344     const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4345     auto BBI = llvm::upper_bound(BasicBlockOffsets,
4346                                  BasicBlockOffset(InputOffset, nullptr),
4347                                  CompareBasicBlockOffsets());
4348     --BBI;
4349     do {
4350       const BinaryBasicBlock *BB = BBI->second;
4351       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4352         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4353                              "for "
4354                           << *this << " : [0x" << Twine::utohexstr(Start)
4355                           << ", 0x" << Twine::utohexstr(End) << "]\n");
4356         PrevEndAddress = 0;
4357         break;
4358       }
4359 
4360       // Skip the range if the block was deleted.
4361       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4362         const uint64_t StartAddress =
4363             OutputStart + InputOffset - BB->getOffset();
4364         uint64_t EndAddress = BB->getOutputAddressRange().second;
4365         if (InputEndOffset < BB->getEndOffset())
4366           EndAddress = StartAddress + InputEndOffset - InputOffset;
4367 
4368         if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4369           OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4370         } else {
4371           OutputLL.emplace_back(DebugLocationEntry{
4372               StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4373         }
4374         PrevEndAddress = OutputLL.back().HighPC;
4375         PrevExpr = &OutputLL.back().Expr;
4376       }
4377 
4378       ++BBI;
4379       InputOffset = BB->getEndOffset();
4380     } while (InputOffset < InputEndOffset);
4381   }
4382 
4383   // Sort and merge adjacent entries with identical location.
4384   llvm::stable_sort(
4385       OutputLL, [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4386         return A.LowPC < B.LowPC;
4387       });
4388   DebugLocationsVector MergedLL;
4389   PrevEndAddress = 0;
4390   PrevExpr = nullptr;
4391   for (const DebugLocationEntry &Entry : OutputLL) {
4392     if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4393       MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4394     } else {
4395       const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4396       const uint64_t End = std::max(Begin, Entry.HighPC);
4397       MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4398     }
4399     PrevEndAddress = MergedLL.back().HighPC;
4400     PrevExpr = &MergedLL.back().Expr;
4401   }
4402 
4403   return MergedLL;
4404 }
4405 
4406 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4407   if (!opts::shouldPrint(*this))
4408     return;
4409 
4410   OS << "Loop Info for Function \"" << *this << "\"";
4411   if (hasValidProfile())
4412     OS << " (count: " << getExecutionCount() << ")";
4413   OS << "\n";
4414 
4415   std::stack<BinaryLoop *> St;
4416   for (BinaryLoop *L : *BLI)
4417     St.push(L);
4418   while (!St.empty()) {
4419     BinaryLoop *L = St.top();
4420     St.pop();
4421 
4422     for (BinaryLoop *Inner : *L)
4423       St.push(Inner);
4424 
4425     if (!hasValidProfile())
4426       continue;
4427 
4428     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4429        << " loop header: " << L->getHeader()->getName();
4430     OS << "\n";
4431     OS << "Loop basic blocks: ";
4432     ListSeparator LS;
4433     for (BinaryBasicBlock *BB : L->blocks())
4434       OS << LS << BB->getName();
4435     OS << "\n";
4436     if (hasValidProfile()) {
4437       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4438       OS << "Loop entry count: " << L->EntryCount << "\n";
4439       OS << "Loop exit count: " << L->ExitCount << "\n";
4440       if (L->EntryCount > 0) {
4441         OS << "Average iters per entry: "
4442            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4443            << "\n";
4444       }
4445     }
4446     OS << "----\n";
4447   }
4448 
4449   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4450   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4451   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4452 }
4453 
4454 bool BinaryFunction::isAArch64Veneer() const {
4455   if (empty() || hasIslandsInfo())
4456     return false;
4457 
4458   BinaryBasicBlock &BB = **BasicBlocks.begin();
4459   for (MCInst &Inst : BB)
4460     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4461       return false;
4462 
4463   for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) {
4464     for (MCInst &Inst : **I)
4465       if (!BC.MIB->isNoop(Inst))
4466         return false;
4467   }
4468 
4469   return true;
4470 }
4471 
4472 void BinaryFunction::addRelocation(uint64_t Address, MCSymbol *Symbol,
4473                                    uint64_t RelType, uint64_t Addend,
4474                                    uint64_t Value) {
4475   assert(Address >= getAddress() && Address < getAddress() + getMaxSize() &&
4476          "address is outside of the function");
4477   uint64_t Offset = Address - getAddress();
4478   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addRelocation in "
4479                     << formatv("{0}@{1:x} against {2}\n", *this, Offset,
4480                                Symbol->getName()));
4481   bool IsCI = BC.isAArch64() && isInConstantIsland(Address);
4482   std::map<uint64_t, Relocation> &Rels =
4483       IsCI ? Islands->Relocations : Relocations;
4484   if (BC.MIB->shouldRecordCodeRelocation(RelType))
4485     Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
4486 }
4487 
4488 } // namespace bolt
4489 } // namespace llvm
4490