xref: /llvm-project/bolt/lib/Core/BinaryFunction.cpp (revision 5c4d306a10abc8c607ebfa50d73f008010b902f3)
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()) {
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 (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     if (JT.Entries.empty()) {
1619       bool HasOneParent = (JT.Parents.size() == 1);
1620       for (unsigned I = 0; I < JT.EntriesAsAddress.size(); ++I) {
1621         uint64_t EntryAddress = JT.EntriesAsAddress[I];
1622         // builtin_unreachable does not belong to any function
1623         // Need to handle separately
1624         bool IsBuiltIn = false;
1625         for (BinaryFunction *Parent : JT.Parents) {
1626           if (EntryAddress == Parent->getAddress() + Parent->getSize()) {
1627             IsBuiltIn = true;
1628             // Specify second parameter as true to accept builtin_unreachable
1629             MCSymbol *Label = getOrCreateLocalLabel(EntryAddress, true);
1630             JT.Entries.push_back(Label);
1631             break;
1632           }
1633         }
1634         if (IsBuiltIn)
1635           continue;
1636         // Create local label for targets cannot be reached by other fragments
1637         // Otherwise, secondary entry point to target function
1638         BinaryFunction *TargetBF =
1639             BC.getBinaryFunctionContainingAddress(EntryAddress);
1640         if (TargetBF->getAddress() != EntryAddress) {
1641           MCSymbol *Label =
1642               (HasOneParent && TargetBF == this)
1643                   ? getOrCreateLocalLabel(JT.EntriesAsAddress[I], true)
1644                   : TargetBF->addEntryPointAtOffset(EntryAddress -
1645                                                     TargetBF->getAddress());
1646           JT.Entries.push_back(Label);
1647         }
1648       }
1649     }
1650 
1651     const uint64_t BDSize =
1652         BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1653     if (!BDSize) {
1654       BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1655     } else {
1656       assert(BDSize >= JT.getSize() &&
1657              "jump table cannot be larger than the containing object");
1658     }
1659   }
1660 
1661   // Add TakenBranches from JumpTables.
1662   //
1663   // We want to do it after initial processing since we don't know jump tables'
1664   // boundaries until we process them all.
1665   for (auto &JTSite : JTSites) {
1666     const uint64_t JTSiteOffset = JTSite.first;
1667     const uint64_t JTAddress = JTSite.second;
1668     const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1669     assert(JT && "cannot find jump table for address");
1670 
1671     uint64_t EntryOffset = JTAddress - JT->getAddress();
1672     while (EntryOffset < JT->getSize()) {
1673       uint64_t EntryAddress = JT->EntriesAsAddress[EntryOffset / JT->EntrySize];
1674       uint64_t TargetOffset = EntryAddress - getAddress();
1675       if (TargetOffset < getSize()) {
1676         TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1677 
1678         if (opts::StrictMode)
1679           registerReferencedOffset(TargetOffset);
1680       }
1681 
1682       EntryOffset += JT->EntrySize;
1683 
1684       // A label at the next entry means the end of this jump table.
1685       if (JT->Labels.count(EntryOffset))
1686         break;
1687     }
1688   }
1689   clearList(JTSites);
1690 
1691   // Conservatively populate all possible destinations for unknown indirect
1692   // branches.
1693   if (opts::StrictMode && hasInternalReference()) {
1694     for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1695       for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1696         // Ignore __builtin_unreachable().
1697         if (PossibleDestination == getSize())
1698           continue;
1699         TakenBranches.emplace_back(Offset, PossibleDestination);
1700       }
1701     }
1702   }
1703 
1704   // Remove duplicates branches. We can get a bunch of them from jump tables.
1705   // Without doing jump table value profiling we don't have use for extra
1706   // (duplicate) branches.
1707   llvm::sort(TakenBranches);
1708   auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
1709   TakenBranches.erase(NewEnd, TakenBranches.end());
1710 }
1711 
1712 bool BinaryFunction::validateExternallyReferencedOffsets() {
1713   SmallPtrSet<MCSymbol *, 4> JTTargets;
1714   for (const JumpTable *JT : llvm::make_second_range(JumpTables))
1715     JTTargets.insert(JT->Entries.begin(), JT->Entries.end());
1716 
1717   bool HasUnclaimedReference = false;
1718   for (uint64_t Destination : ExternallyReferencedOffsets) {
1719     // Ignore __builtin_unreachable().
1720     if (Destination == getSize())
1721       continue;
1722     // Ignore constant islands
1723     if (isInConstantIsland(Destination + getAddress()))
1724       continue;
1725 
1726     if (BinaryBasicBlock *BB = getBasicBlockAtOffset(Destination)) {
1727       // Check if the externally referenced offset is a recognized jump table
1728       // target.
1729       if (JTTargets.contains(BB->getLabel()))
1730         continue;
1731 
1732       if (opts::Verbosity >= 1) {
1733         errs() << "BOLT-WARNING: unclaimed data to code reference (possibly "
1734                << "an unrecognized jump table entry) to " << BB->getName()
1735                << " in " << *this << "\n";
1736       }
1737       auto L = BC.scopeLock();
1738       addEntryPoint(*BB);
1739     } else {
1740       errs() << "BOLT-WARNING: unknown data to code reference to offset "
1741              << Twine::utohexstr(Destination) << " in " << *this << "\n";
1742       setIgnored();
1743     }
1744     HasUnclaimedReference = true;
1745   }
1746   return !HasUnclaimedReference;
1747 }
1748 
1749 bool BinaryFunction::postProcessIndirectBranches(
1750     MCPlusBuilder::AllocatorIdTy AllocId) {
1751   auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
1752     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding unknown control flow in " << *this
1753                       << " for " << BB.getName() << "\n");
1754     HasUnknownControlFlow = true;
1755     BB.removeAllSuccessors();
1756     for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1757       if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1758         BB.addSuccessor(SuccBB);
1759   };
1760 
1761   uint64_t NumIndirectJumps = 0;
1762   MCInst *LastIndirectJump = nullptr;
1763   BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1764   uint64_t LastJT = 0;
1765   uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1766   for (BinaryBasicBlock &BB : blocks()) {
1767     for (MCInst &Instr : BB) {
1768       if (!BC.MIB->isIndirectBranch(Instr))
1769         continue;
1770 
1771       // If there's an indirect branch in a single-block function -
1772       // it must be a tail call.
1773       if (BasicBlocks.size() == 1) {
1774         BC.MIB->convertJmpToTailCall(Instr);
1775         return true;
1776       }
1777 
1778       ++NumIndirectJumps;
1779 
1780       if (opts::StrictMode && !hasInternalReference()) {
1781         BC.MIB->convertJmpToTailCall(Instr);
1782         break;
1783       }
1784 
1785       // Validate the tail call or jump table assumptions now that we know
1786       // basic block boundaries.
1787       if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1788         const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1789         MCInst *MemLocInstr;
1790         unsigned BaseRegNum, IndexRegNum;
1791         int64_t DispValue;
1792         const MCExpr *DispExpr;
1793         MCInst *PCRelBaseInstr;
1794         IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
1795             Instr, BB.begin(), BB.end(), PtrSize, MemLocInstr, BaseRegNum,
1796             IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
1797         if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1798           continue;
1799 
1800         if (!opts::StrictMode)
1801           return false;
1802 
1803         if (BC.MIB->isTailCall(Instr)) {
1804           BC.MIB->convertTailCallToJmp(Instr);
1805         } else {
1806           LastIndirectJump = &Instr;
1807           LastIndirectJumpBB = &BB;
1808           LastJT = BC.MIB->getJumpTable(Instr);
1809           LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1810           BC.MIB->unsetJumpTable(Instr);
1811 
1812           JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1813           if (JT->Type == JumpTable::JTT_NORMAL) {
1814             // Invalidating the jump table may also invalidate other jump table
1815             // boundaries. Until we have/need a support for this, mark the
1816             // function as non-simple.
1817             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1818                               << JT->getName() << " in " << *this << '\n');
1819             return false;
1820           }
1821         }
1822 
1823         addUnknownControlFlow(BB);
1824         continue;
1825       }
1826 
1827       // If this block contains an epilogue code and has an indirect branch,
1828       // then most likely it's a tail call. Otherwise, we cannot tell for sure
1829       // what it is and conservatively reject the function's CFG.
1830       bool IsEpilogue = llvm::any_of(BB, [&](const MCInst &Instr) {
1831         return BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr);
1832       });
1833       if (IsEpilogue) {
1834         BC.MIB->convertJmpToTailCall(Instr);
1835         BB.removeAllSuccessors();
1836         continue;
1837       }
1838 
1839       if (opts::Verbosity >= 2) {
1840         outs() << "BOLT-INFO: rejected potential indirect tail call in "
1841                << "function " << *this << " in basic block " << BB.getName()
1842                << ".\n";
1843         LLVM_DEBUG(BC.printInstructions(dbgs(), BB.begin(), BB.end(),
1844                                         BB.getOffset(), this, true));
1845       }
1846 
1847       if (!opts::StrictMode)
1848         return false;
1849 
1850       addUnknownControlFlow(BB);
1851     }
1852   }
1853 
1854   if (HasInternalLabelReference)
1855     return false;
1856 
1857   // If there's only one jump table, and one indirect jump, and no other
1858   // references, then we should be able to derive the jump table even if we
1859   // fail to match the pattern.
1860   if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
1861       JumpTables.size() == 1 && LastIndirectJump &&
1862       !BC.getJumpTableContainingAddress(LastJT)->IsSplit) {
1863     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: unsetting unknown control flow in "
1864                       << *this << '\n');
1865     BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1866     HasUnknownControlFlow = false;
1867 
1868     LastIndirectJumpBB->updateJumpTableSuccessors();
1869   }
1870 
1871   if (HasFixedIndirectBranch)
1872     return false;
1873 
1874   // Validate that all data references to function offsets are claimed by
1875   // recognized jump tables. Register externally referenced blocks as entry
1876   // points.
1877   if (!opts::StrictMode && hasInternalReference()) {
1878     if (!validateExternallyReferencedOffsets())
1879       return false;
1880   }
1881 
1882   if (HasUnknownControlFlow && !BC.HasRelocations)
1883     return false;
1884 
1885   return true;
1886 }
1887 
1888 void BinaryFunction::recomputeLandingPads() {
1889   updateBBIndices(0);
1890 
1891   for (BinaryBasicBlock *BB : BasicBlocks) {
1892     BB->LandingPads.clear();
1893     BB->Throwers.clear();
1894   }
1895 
1896   for (BinaryBasicBlock *BB : BasicBlocks) {
1897     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1898     for (MCInst &Instr : *BB) {
1899       if (!BC.MIB->isInvoke(Instr))
1900         continue;
1901 
1902       const std::optional<MCPlus::MCLandingPad> EHInfo =
1903           BC.MIB->getEHInfo(Instr);
1904       if (!EHInfo || !EHInfo->first)
1905         continue;
1906 
1907       BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1908       if (!BBLandingPads.count(LPBlock)) {
1909         BBLandingPads.insert(LPBlock);
1910         BB->LandingPads.emplace_back(LPBlock);
1911         LPBlock->Throwers.emplace_back(BB);
1912       }
1913     }
1914   }
1915 }
1916 
1917 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1918   auto &MIB = BC.MIB;
1919 
1920   if (!isSimple()) {
1921     assert(!BC.HasRelocations &&
1922            "cannot process file with non-simple function in relocs mode");
1923     return false;
1924   }
1925 
1926   if (CurrentState != State::Disassembled)
1927     return false;
1928 
1929   assert(BasicBlocks.empty() && "basic block list should be empty");
1930   assert((Labels.find(getFirstInstructionOffset()) != Labels.end()) &&
1931          "first instruction should always have a label");
1932 
1933   // Create basic blocks in the original layout order:
1934   //
1935   //  * Every instruction with associated label marks
1936   //    the beginning of a basic block.
1937   //  * Conditional instruction marks the end of a basic block,
1938   //    except when the following instruction is an
1939   //    unconditional branch, and the unconditional branch is not
1940   //    a destination of another branch. In the latter case, the
1941   //    basic block will consist of a single unconditional branch
1942   //    (missed "double-jump" optimization).
1943   //
1944   // Created basic blocks are sorted in layout order since they are
1945   // created in the same order as instructions, and instructions are
1946   // sorted by offsets.
1947   BinaryBasicBlock *InsertBB = nullptr;
1948   BinaryBasicBlock *PrevBB = nullptr;
1949   bool IsLastInstrNop = false;
1950   // Offset of the last non-nop instruction.
1951   uint64_t LastInstrOffset = 0;
1952 
1953   auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1954                                    BinaryBasicBlock *InsertBB) {
1955     for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1956               FE = OffsetToCFI.upper_bound(CFIOffset);
1957          FI != FE; ++FI) {
1958       addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1959     }
1960   };
1961 
1962   // For profiling purposes we need to save the offset of the last instruction
1963   // in the basic block.
1964   // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1965   //       older profiles ignored nops.
1966   auto updateOffset = [&](uint64_t Offset) {
1967     assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
1968     MCInst *LastNonNop = nullptr;
1969     for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
1970                                             E = PrevBB->rend();
1971          RII != E; ++RII) {
1972       if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
1973         LastNonNop = &*RII;
1974         break;
1975       }
1976     }
1977     if (LastNonNop && !MIB->getOffset(*LastNonNop))
1978       MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId);
1979   };
1980 
1981   for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
1982     const uint32_t Offset = I->first;
1983     MCInst &Instr = I->second;
1984 
1985     auto LI = Labels.find(Offset);
1986     if (LI != Labels.end()) {
1987       // Always create new BB at branch destination.
1988       PrevBB = InsertBB ? InsertBB : PrevBB;
1989       InsertBB = addBasicBlockAt(LI->first, LI->second);
1990       if (opts::PreserveBlocksAlignment && IsLastInstrNop)
1991         InsertBB->setDerivedAlignment();
1992 
1993       if (PrevBB)
1994         updateOffset(LastInstrOffset);
1995     }
1996 
1997     const uint64_t InstrInputAddr = I->first + Address;
1998     bool IsSDTMarker =
1999         MIB->isNoop(Instr) && BC.SDTMarkers.count(InstrInputAddr);
2000     bool IsLKMarker = BC.LKMarkers.count(InstrInputAddr);
2001     // Mark all nops with Offset for profile tracking purposes.
2002     if (MIB->isNoop(Instr) || IsLKMarker) {
2003       if (!MIB->getOffset(Instr))
2004         MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId);
2005       if (IsSDTMarker || IsLKMarker)
2006         HasSDTMarker = true;
2007       else
2008         // Annotate ordinary nops, so we can safely delete them if required.
2009         MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2010     }
2011 
2012     if (!InsertBB) {
2013       // It must be a fallthrough or unreachable code. Create a new block unless
2014       // we see an unconditional branch following a conditional one. The latter
2015       // should not be a conditional tail call.
2016       assert(PrevBB && "no previous basic block for a fall through");
2017       MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2018       assert(PrevInstr && "no previous instruction for a fall through");
2019       if (MIB->isUnconditionalBranch(Instr) &&
2020           !MIB->isIndirectBranch(*PrevInstr) &&
2021           !MIB->isUnconditionalBranch(*PrevInstr) &&
2022           !MIB->getConditionalTailCall(*PrevInstr) &&
2023           !MIB->isReturn(*PrevInstr)) {
2024         // Temporarily restore inserter basic block.
2025         InsertBB = PrevBB;
2026       } else {
2027         MCSymbol *Label;
2028         {
2029           auto L = BC.scopeLock();
2030           Label = BC.Ctx->createNamedTempSymbol("FT");
2031         }
2032         InsertBB = addBasicBlockAt(Offset, Label);
2033         if (opts::PreserveBlocksAlignment && IsLastInstrNop)
2034           InsertBB->setDerivedAlignment();
2035         updateOffset(LastInstrOffset);
2036       }
2037     }
2038     if (Offset == getFirstInstructionOffset()) {
2039       // Add associated CFI pseudos in the first offset
2040       addCFIPlaceholders(Offset, InsertBB);
2041     }
2042 
2043     const bool IsBlockEnd = MIB->isTerminator(Instr);
2044     IsLastInstrNop = MIB->isNoop(Instr);
2045     if (!IsLastInstrNop)
2046       LastInstrOffset = Offset;
2047     InsertBB->addInstruction(std::move(Instr));
2048 
2049     // Add associated CFI instrs. We always add the CFI instruction that is
2050     // located immediately after this instruction, since the next CFI
2051     // instruction reflects the change in state caused by this instruction.
2052     auto NextInstr = std::next(I);
2053     uint64_t CFIOffset;
2054     if (NextInstr != E)
2055       CFIOffset = NextInstr->first;
2056     else
2057       CFIOffset = getSize();
2058 
2059     // Note: this potentially invalidates instruction pointers/iterators.
2060     addCFIPlaceholders(CFIOffset, InsertBB);
2061 
2062     if (IsBlockEnd) {
2063       PrevBB = InsertBB;
2064       InsertBB = nullptr;
2065     }
2066   }
2067 
2068   if (BasicBlocks.empty()) {
2069     setSimple(false);
2070     return false;
2071   }
2072 
2073   // Intermediate dump.
2074   LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2075 
2076   // TODO: handle properly calls to no-return functions,
2077   // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2078   // blocks.
2079 
2080   for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2081     LLVM_DEBUG(dbgs() << "registering branch [0x"
2082                       << Twine::utohexstr(Branch.first) << "] -> [0x"
2083                       << Twine::utohexstr(Branch.second) << "]\n");
2084     BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2085     BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2086     if (!FromBB || !ToBB) {
2087       if (!FromBB)
2088         errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2089       if (!ToBB)
2090         errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2091       BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2092                            *this);
2093     }
2094 
2095     FromBB->addSuccessor(ToBB);
2096   }
2097 
2098   // Add fall-through branches.
2099   PrevBB = nullptr;
2100   bool IsPrevFT = false; // Is previous block a fall-through.
2101   for (BinaryBasicBlock *BB : BasicBlocks) {
2102     if (IsPrevFT)
2103       PrevBB->addSuccessor(BB);
2104 
2105     if (BB->empty()) {
2106       IsPrevFT = true;
2107       PrevBB = BB;
2108       continue;
2109     }
2110 
2111     MCInst *LastInstr = BB->getLastNonPseudoInstr();
2112     assert(LastInstr &&
2113            "should have non-pseudo instruction in non-empty block");
2114 
2115     if (BB->succ_size() == 0) {
2116       // Since there's no existing successors, we know the last instruction is
2117       // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2118       // fall-through.
2119       //
2120       // Conditional tail call is a special case since we don't add a taken
2121       // branch successor for it.
2122       IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2123                  MIB->getConditionalTailCall(*LastInstr);
2124     } else if (BB->succ_size() == 1) {
2125       IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2126     } else {
2127       IsPrevFT = false;
2128     }
2129 
2130     PrevBB = BB;
2131   }
2132 
2133   // Assign landing pads and throwers info.
2134   recomputeLandingPads();
2135 
2136   // Assign CFI information to each BB entry.
2137   annotateCFIState();
2138 
2139   // Annotate invoke instructions with GNU_args_size data.
2140   propagateGnuArgsSizeInfo(AllocatorId);
2141 
2142   // Set the basic block layout to the original order and set end offsets.
2143   PrevBB = nullptr;
2144   for (BinaryBasicBlock *BB : BasicBlocks) {
2145     Layout.addBasicBlock(BB);
2146     if (PrevBB)
2147       PrevBB->setEndOffset(BB->getOffset());
2148     PrevBB = BB;
2149   }
2150   PrevBB->setEndOffset(getSize());
2151 
2152   Layout.updateLayoutIndices();
2153 
2154   normalizeCFIState();
2155 
2156   // Clean-up memory taken by intermediate structures.
2157   //
2158   // NB: don't clear Labels list as we may need them if we mark the function
2159   //     as non-simple later in the process of discovering extra entry points.
2160   clearList(Instructions);
2161   clearList(OffsetToCFI);
2162   clearList(TakenBranches);
2163 
2164   // Update the state.
2165   CurrentState = State::CFG;
2166 
2167   // Make any necessary adjustments for indirect branches.
2168   if (!postProcessIndirectBranches(AllocatorId)) {
2169     if (opts::Verbosity) {
2170       errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2171              << *this << '\n';
2172     }
2173     // In relocation mode we want to keep processing the function but avoid
2174     // optimizing it.
2175     setSimple(false);
2176   }
2177 
2178   clearList(ExternallyReferencedOffsets);
2179   clearList(UnknownIndirectBranchOffsets);
2180 
2181   return true;
2182 }
2183 
2184 void BinaryFunction::postProcessCFG() {
2185   if (isSimple() && !BasicBlocks.empty()) {
2186     // Convert conditional tail call branches to conditional branches that jump
2187     // to a tail call.
2188     removeConditionalTailCalls();
2189 
2190     postProcessProfile();
2191 
2192     // Eliminate inconsistencies between branch instructions and CFG.
2193     postProcessBranches();
2194   }
2195 
2196   calculateMacroOpFusionStats();
2197 
2198   // The final cleanup of intermediate structures.
2199   clearList(IgnoredBranches);
2200 
2201   // Remove "Offset" annotations, unless we need an address-translation table
2202   // later. This has no cost, since annotations are allocated by a bumpptr
2203   // allocator and won't be released anyway until late in the pipeline.
2204   if (!requiresAddressTranslation() && !opts::Instrument) {
2205     for (BinaryBasicBlock &BB : blocks())
2206       for (MCInst &Inst : BB)
2207         BC.MIB->clearOffset(Inst);
2208   }
2209 
2210   assert((!isSimple() || validateCFG()) &&
2211          "invalid CFG detected after post-processing");
2212 }
2213 
2214 void BinaryFunction::calculateMacroOpFusionStats() {
2215   if (!getBinaryContext().isX86())
2216     return;
2217   for (const BinaryBasicBlock &BB : blocks()) {
2218     auto II = BB.getMacroOpFusionPair();
2219     if (II == BB.end())
2220       continue;
2221 
2222     // Check offset of the second instruction.
2223     // FIXME: arch-specific.
2224     const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2225     if (!Offset || (getAddress() + Offset) % 64)
2226       continue;
2227 
2228     LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2229                       << Twine::utohexstr(getAddress() + Offset)
2230                       << " in function " << *this << "; executed "
2231                       << BB.getKnownExecutionCount() << " times.\n");
2232     ++BC.MissedMacroFusionPairs;
2233     BC.MissedMacroFusionExecCount += BB.getKnownExecutionCount();
2234   }
2235 }
2236 
2237 void BinaryFunction::removeTagsFromProfile() {
2238   for (BinaryBasicBlock *BB : BasicBlocks) {
2239     if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2240       BB->ExecutionCount = 0;
2241     for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2242       if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2243           BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2244         continue;
2245       BI.Count = 0;
2246       BI.MispredictedCount = 0;
2247     }
2248   }
2249 }
2250 
2251 void BinaryFunction::removeConditionalTailCalls() {
2252   // Blocks to be appended at the end.
2253   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2254 
2255   for (auto BBI = begin(); BBI != end(); ++BBI) {
2256     BinaryBasicBlock &BB = *BBI;
2257     MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2258     if (!CTCInstr)
2259       continue;
2260 
2261     std::optional<uint64_t> TargetAddressOrNone =
2262         BC.MIB->getConditionalTailCall(*CTCInstr);
2263     if (!TargetAddressOrNone)
2264       continue;
2265 
2266     // Gather all necessary information about CTC instruction before
2267     // annotations are destroyed.
2268     const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2269     uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2270     uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2271     if (hasValidProfile()) {
2272       CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2273           *CTCInstr, "CTCTakenCount");
2274       CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2275           *CTCInstr, "CTCMispredCount");
2276     }
2277 
2278     // Assert that the tail call does not throw.
2279     assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2280            "found tail call with associated landing pad");
2281 
2282     // Create a basic block with an unconditional tail call instruction using
2283     // the same destination.
2284     const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2285     assert(CTCTargetLabel && "symbol expected for conditional tail call");
2286     MCInst TailCallInstr;
2287     BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2288     // Link new BBs to the original input offset of the BB where the CTC
2289     // is, so we can map samples recorded in new BBs back to the original BB
2290     // seem in the input binary (if using BAT)
2291     std::unique_ptr<BinaryBasicBlock> TailCallBB =
2292         createBasicBlock(BC.Ctx->createNamedTempSymbol("TC"));
2293     TailCallBB->setOffset(BB.getInputOffset());
2294     TailCallBB->addInstruction(TailCallInstr);
2295     TailCallBB->setCFIState(CFIStateBeforeCTC);
2296 
2297     // Add CFG edge with profile info from BB to TailCallBB.
2298     BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2299 
2300     // Add execution count for the block.
2301     TailCallBB->setExecutionCount(CTCTakenCount);
2302 
2303     BC.MIB->convertTailCallToJmp(*CTCInstr);
2304 
2305     BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2306                                 BC.Ctx.get());
2307 
2308     // Add basic block to the list that will be added to the end.
2309     NewBlocks.emplace_back(std::move(TailCallBB));
2310 
2311     // Swap edges as the TailCallBB corresponds to the taken branch.
2312     BB.swapConditionalSuccessors();
2313 
2314     // This branch is no longer a conditional tail call.
2315     BC.MIB->unsetConditionalTailCall(*CTCInstr);
2316   }
2317 
2318   insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2319                     /* UpdateLayout */ true,
2320                     /* UpdateCFIState */ false);
2321 }
2322 
2323 uint64_t BinaryFunction::getFunctionScore() const {
2324   if (FunctionScore != -1)
2325     return FunctionScore;
2326 
2327   if (!isSimple() || !hasValidProfile()) {
2328     FunctionScore = 0;
2329     return FunctionScore;
2330   }
2331 
2332   uint64_t TotalScore = 0ULL;
2333   for (const BinaryBasicBlock &BB : blocks()) {
2334     uint64_t BBExecCount = BB.getExecutionCount();
2335     if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2336       continue;
2337     TotalScore += BBExecCount * BB.getNumNonPseudos();
2338   }
2339   FunctionScore = TotalScore;
2340   return FunctionScore;
2341 }
2342 
2343 void BinaryFunction::annotateCFIState() {
2344   assert(CurrentState == State::Disassembled && "unexpected function state");
2345   assert(!BasicBlocks.empty() && "basic block list should not be empty");
2346 
2347   // This is an index of the last processed CFI in FDE CFI program.
2348   uint32_t State = 0;
2349 
2350   // This is an index of RememberState CFI reflecting effective state right
2351   // after execution of RestoreState CFI.
2352   //
2353   // It differs from State iff the CFI at (State-1)
2354   // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2355   //
2356   // This allows us to generate shorter replay sequences when producing new
2357   // CFI programs.
2358   uint32_t EffectiveState = 0;
2359 
2360   // For tracking RememberState/RestoreState sequences.
2361   std::stack<uint32_t> StateStack;
2362 
2363   for (BinaryBasicBlock *BB : BasicBlocks) {
2364     BB->setCFIState(EffectiveState);
2365 
2366     for (const MCInst &Instr : *BB) {
2367       const MCCFIInstruction *CFI = getCFIFor(Instr);
2368       if (!CFI)
2369         continue;
2370 
2371       ++State;
2372 
2373       switch (CFI->getOperation()) {
2374       case MCCFIInstruction::OpRememberState:
2375         StateStack.push(EffectiveState);
2376         EffectiveState = State;
2377         break;
2378       case MCCFIInstruction::OpRestoreState:
2379         assert(!StateStack.empty() && "corrupt CFI stack");
2380         EffectiveState = StateStack.top();
2381         StateStack.pop();
2382         break;
2383       case MCCFIInstruction::OpGnuArgsSize:
2384         // OpGnuArgsSize CFIs do not affect the CFI state.
2385         break;
2386       default:
2387         // Any other CFI updates the state.
2388         EffectiveState = State;
2389         break;
2390       }
2391     }
2392   }
2393 
2394   assert(StateStack.empty() && "corrupt CFI stack");
2395 }
2396 
2397 namespace {
2398 
2399 /// Our full interpretation of a DWARF CFI machine state at a given point
2400 struct CFISnapshot {
2401   /// CFA register number and offset defining the canonical frame at this
2402   /// point, or the number of a rule (CFI state) that computes it with a
2403   /// DWARF expression. This number will be negative if it refers to a CFI
2404   /// located in the CIE instead of the FDE.
2405   uint32_t CFAReg;
2406   int32_t CFAOffset;
2407   int32_t CFARule;
2408   /// Mapping of rules (CFI states) that define the location of each
2409   /// register. If absent, no rule defining the location of such register
2410   /// was ever read. This number will be negative if it refers to a CFI
2411   /// located in the CIE instead of the FDE.
2412   DenseMap<int32_t, int32_t> RegRule;
2413 
2414   /// References to CIE, FDE and expanded instructions after a restore state
2415   const BinaryFunction::CFIInstrMapType &CIE;
2416   const BinaryFunction::CFIInstrMapType &FDE;
2417   const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2418 
2419   /// Current FDE CFI number representing the state where the snapshot is at
2420   int32_t CurState;
2421 
2422   /// Used when we don't have information about which state/rule to apply
2423   /// to recover the location of either the CFA or a specific register
2424   constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2425 
2426 private:
2427   /// Update our snapshot by executing a single CFI
2428   void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2429     switch (Instr.getOperation()) {
2430     case MCCFIInstruction::OpSameValue:
2431     case MCCFIInstruction::OpRelOffset:
2432     case MCCFIInstruction::OpOffset:
2433     case MCCFIInstruction::OpRestore:
2434     case MCCFIInstruction::OpUndefined:
2435     case MCCFIInstruction::OpRegister:
2436       RegRule[Instr.getRegister()] = RuleNumber;
2437       break;
2438     case MCCFIInstruction::OpDefCfaRegister:
2439       CFAReg = Instr.getRegister();
2440       CFARule = UNKNOWN;
2441       break;
2442     case MCCFIInstruction::OpDefCfaOffset:
2443       CFAOffset = Instr.getOffset();
2444       CFARule = UNKNOWN;
2445       break;
2446     case MCCFIInstruction::OpDefCfa:
2447       CFAReg = Instr.getRegister();
2448       CFAOffset = Instr.getOffset();
2449       CFARule = UNKNOWN;
2450       break;
2451     case MCCFIInstruction::OpEscape: {
2452       std::optional<uint8_t> Reg =
2453           readDWARFExpressionTargetReg(Instr.getValues());
2454       // Handle DW_CFA_def_cfa_expression
2455       if (!Reg) {
2456         CFARule = RuleNumber;
2457         break;
2458       }
2459       RegRule[*Reg] = RuleNumber;
2460       break;
2461     }
2462     case MCCFIInstruction::OpAdjustCfaOffset:
2463     case MCCFIInstruction::OpWindowSave:
2464     case MCCFIInstruction::OpNegateRAState:
2465     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2466       llvm_unreachable("unsupported CFI opcode");
2467       break;
2468     case MCCFIInstruction::OpRememberState:
2469     case MCCFIInstruction::OpRestoreState:
2470     case MCCFIInstruction::OpGnuArgsSize:
2471       // do not affect CFI state
2472       break;
2473     }
2474   }
2475 
2476 public:
2477   /// Advance state reading FDE CFI instructions up to State number
2478   void advanceTo(int32_t State) {
2479     for (int32_t I = CurState, E = State; I != E; ++I) {
2480       const MCCFIInstruction &Instr = FDE[I];
2481       if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2482         update(Instr, I);
2483         continue;
2484       }
2485       // If restore state instruction, fetch the equivalent CFIs that have
2486       // the same effect of this restore. This is used to ensure remember-
2487       // restore pairs are completely removed.
2488       auto Iter = FrameRestoreEquivalents.find(I);
2489       if (Iter == FrameRestoreEquivalents.end())
2490         continue;
2491       for (int32_t RuleNumber : Iter->second)
2492         update(FDE[RuleNumber], RuleNumber);
2493     }
2494 
2495     assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2496             CFARule != UNKNOWN) &&
2497            "CIE did not define default CFA?");
2498 
2499     CurState = State;
2500   }
2501 
2502   /// Interpret all CIE and FDE instructions up until CFI State number and
2503   /// populate this snapshot
2504   CFISnapshot(
2505       const BinaryFunction::CFIInstrMapType &CIE,
2506       const BinaryFunction::CFIInstrMapType &FDE,
2507       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2508       int32_t State)
2509       : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2510     CFAReg = UNKNOWN;
2511     CFAOffset = UNKNOWN;
2512     CFARule = UNKNOWN;
2513     CurState = 0;
2514 
2515     for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2516       const MCCFIInstruction &Instr = CIE[I];
2517       update(Instr, -I);
2518     }
2519 
2520     advanceTo(State);
2521   }
2522 };
2523 
2524 /// A CFI snapshot with the capability of checking if incremental additions to
2525 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2526 /// back-to-back that are doing the same state change, or to avoid emitting a
2527 /// CFI at all when the state at that point would not be modified after that CFI
2528 struct CFISnapshotDiff : public CFISnapshot {
2529   bool RestoredCFAReg{false};
2530   bool RestoredCFAOffset{false};
2531   DenseMap<int32_t, bool> RestoredRegs;
2532 
2533   CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2534 
2535   CFISnapshotDiff(
2536       const BinaryFunction::CFIInstrMapType &CIE,
2537       const BinaryFunction::CFIInstrMapType &FDE,
2538       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2539       int32_t State)
2540       : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2541 
2542   /// Return true if applying Instr to this state is redundant and can be
2543   /// dismissed.
2544   bool isRedundant(const MCCFIInstruction &Instr) {
2545     switch (Instr.getOperation()) {
2546     case MCCFIInstruction::OpSameValue:
2547     case MCCFIInstruction::OpRelOffset:
2548     case MCCFIInstruction::OpOffset:
2549     case MCCFIInstruction::OpRestore:
2550     case MCCFIInstruction::OpUndefined:
2551     case MCCFIInstruction::OpRegister:
2552     case MCCFIInstruction::OpEscape: {
2553       uint32_t Reg;
2554       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2555         Reg = Instr.getRegister();
2556       } else {
2557         std::optional<uint8_t> R =
2558             readDWARFExpressionTargetReg(Instr.getValues());
2559         // Handle DW_CFA_def_cfa_expression
2560         if (!R) {
2561           if (RestoredCFAReg && RestoredCFAOffset)
2562             return true;
2563           RestoredCFAReg = true;
2564           RestoredCFAOffset = true;
2565           return false;
2566         }
2567         Reg = *R;
2568       }
2569       if (RestoredRegs[Reg])
2570         return true;
2571       RestoredRegs[Reg] = true;
2572       const int32_t CurRegRule = RegRule.contains(Reg) ? RegRule[Reg] : UNKNOWN;
2573       if (CurRegRule == UNKNOWN) {
2574         if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2575             Instr.getOperation() == MCCFIInstruction::OpSameValue)
2576           return true;
2577         return false;
2578       }
2579       const MCCFIInstruction &LastDef =
2580           CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2581       return LastDef == Instr;
2582     }
2583     case MCCFIInstruction::OpDefCfaRegister:
2584       if (RestoredCFAReg)
2585         return true;
2586       RestoredCFAReg = true;
2587       return CFAReg == Instr.getRegister();
2588     case MCCFIInstruction::OpDefCfaOffset:
2589       if (RestoredCFAOffset)
2590         return true;
2591       RestoredCFAOffset = true;
2592       return CFAOffset == Instr.getOffset();
2593     case MCCFIInstruction::OpDefCfa:
2594       if (RestoredCFAReg && RestoredCFAOffset)
2595         return true;
2596       RestoredCFAReg = true;
2597       RestoredCFAOffset = true;
2598       return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2599     case MCCFIInstruction::OpAdjustCfaOffset:
2600     case MCCFIInstruction::OpWindowSave:
2601     case MCCFIInstruction::OpNegateRAState:
2602     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2603       llvm_unreachable("unsupported CFI opcode");
2604       return false;
2605     case MCCFIInstruction::OpRememberState:
2606     case MCCFIInstruction::OpRestoreState:
2607     case MCCFIInstruction::OpGnuArgsSize:
2608       // do not affect CFI state
2609       return true;
2610     }
2611     return false;
2612   }
2613 };
2614 
2615 } // end anonymous namespace
2616 
2617 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2618                                      BinaryBasicBlock *InBB,
2619                                      BinaryBasicBlock::iterator InsertIt) {
2620   if (FromState == ToState)
2621     return true;
2622   assert(FromState < ToState && "can only replay CFIs forward");
2623 
2624   CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2625                           FrameRestoreEquivalents, FromState);
2626 
2627   std::vector<uint32_t> NewCFIs;
2628   for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2629     MCCFIInstruction *Instr = &FrameInstructions[CurState];
2630     if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2631       auto Iter = FrameRestoreEquivalents.find(CurState);
2632       assert(Iter != FrameRestoreEquivalents.end());
2633       NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2634       // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2635       // so we might as well fall-through here.
2636     }
2637     NewCFIs.push_back(CurState);
2638   }
2639 
2640   // Replay instructions while avoiding duplicates
2641   for (int32_t State : llvm::reverse(NewCFIs)) {
2642     if (CFIDiff.isRedundant(FrameInstructions[State]))
2643       continue;
2644     InsertIt = addCFIPseudo(InBB, InsertIt, State);
2645   }
2646 
2647   return true;
2648 }
2649 
2650 SmallVector<int32_t, 4>
2651 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2652                                BinaryBasicBlock *InBB,
2653                                BinaryBasicBlock::iterator &InsertIt) {
2654   SmallVector<int32_t, 4> NewStates;
2655 
2656   CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2657                          FrameRestoreEquivalents, ToState);
2658   CFISnapshotDiff FromCFITable(ToCFITable);
2659   FromCFITable.advanceTo(FromState);
2660 
2661   auto undoStateDefCfa = [&]() {
2662     if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2663       FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2664           nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2665       if (FromCFITable.isRedundant(FrameInstructions.back())) {
2666         FrameInstructions.pop_back();
2667         return;
2668       }
2669       NewStates.push_back(FrameInstructions.size() - 1);
2670       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2671       ++InsertIt;
2672     } else if (ToCFITable.CFARule < 0) {
2673       if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2674         return;
2675       NewStates.push_back(FrameInstructions.size());
2676       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2677       ++InsertIt;
2678       FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2679     } else if (!FromCFITable.isRedundant(
2680                    FrameInstructions[ToCFITable.CFARule])) {
2681       NewStates.push_back(ToCFITable.CFARule);
2682       InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2683       ++InsertIt;
2684     }
2685   };
2686 
2687   auto undoState = [&](const MCCFIInstruction &Instr) {
2688     switch (Instr.getOperation()) {
2689     case MCCFIInstruction::OpRememberState:
2690     case MCCFIInstruction::OpRestoreState:
2691       break;
2692     case MCCFIInstruction::OpSameValue:
2693     case MCCFIInstruction::OpRelOffset:
2694     case MCCFIInstruction::OpOffset:
2695     case MCCFIInstruction::OpRestore:
2696     case MCCFIInstruction::OpUndefined:
2697     case MCCFIInstruction::OpEscape:
2698     case MCCFIInstruction::OpRegister: {
2699       uint32_t Reg;
2700       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2701         Reg = Instr.getRegister();
2702       } else {
2703         std::optional<uint8_t> R =
2704             readDWARFExpressionTargetReg(Instr.getValues());
2705         // Handle DW_CFA_def_cfa_expression
2706         if (!R) {
2707           undoStateDefCfa();
2708           return;
2709         }
2710         Reg = *R;
2711       }
2712 
2713       if (!ToCFITable.RegRule.contains(Reg)) {
2714         FrameInstructions.emplace_back(
2715             MCCFIInstruction::createRestore(nullptr, Reg));
2716         if (FromCFITable.isRedundant(FrameInstructions.back())) {
2717           FrameInstructions.pop_back();
2718           break;
2719         }
2720         NewStates.push_back(FrameInstructions.size() - 1);
2721         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2722         ++InsertIt;
2723         break;
2724       }
2725       const int32_t Rule = ToCFITable.RegRule[Reg];
2726       if (Rule < 0) {
2727         if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2728           break;
2729         NewStates.push_back(FrameInstructions.size());
2730         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2731         ++InsertIt;
2732         FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2733         break;
2734       }
2735       if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2736         break;
2737       NewStates.push_back(Rule);
2738       InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2739       ++InsertIt;
2740       break;
2741     }
2742     case MCCFIInstruction::OpDefCfaRegister:
2743     case MCCFIInstruction::OpDefCfaOffset:
2744     case MCCFIInstruction::OpDefCfa:
2745       undoStateDefCfa();
2746       break;
2747     case MCCFIInstruction::OpAdjustCfaOffset:
2748     case MCCFIInstruction::OpWindowSave:
2749     case MCCFIInstruction::OpNegateRAState:
2750     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2751       llvm_unreachable("unsupported CFI opcode");
2752       break;
2753     case MCCFIInstruction::OpGnuArgsSize:
2754       // do not affect CFI state
2755       break;
2756     }
2757   };
2758 
2759   // Undo all modifications from ToState to FromState
2760   for (int32_t I = ToState, E = FromState; I != E; ++I) {
2761     const MCCFIInstruction &Instr = FrameInstructions[I];
2762     if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2763       undoState(Instr);
2764       continue;
2765     }
2766     auto Iter = FrameRestoreEquivalents.find(I);
2767     if (Iter == FrameRestoreEquivalents.end())
2768       continue;
2769     for (int32_t State : Iter->second)
2770       undoState(FrameInstructions[State]);
2771   }
2772 
2773   return NewStates;
2774 }
2775 
2776 void BinaryFunction::normalizeCFIState() {
2777   // Reordering blocks with remember-restore state instructions can be specially
2778   // tricky. When rewriting the CFI, we omit remember-restore state instructions
2779   // entirely. For restore state, we build a map expanding each restore to the
2780   // equivalent unwindCFIState sequence required at that point to achieve the
2781   // same effect of the restore. All remember state are then just ignored.
2782   std::stack<int32_t> Stack;
2783   for (BinaryBasicBlock *CurBB : Layout.blocks()) {
2784     for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2785       if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2786         if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2787           Stack.push(II->getOperand(0).getImm());
2788           continue;
2789         }
2790         if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2791           const int32_t RememberState = Stack.top();
2792           const int32_t CurState = II->getOperand(0).getImm();
2793           FrameRestoreEquivalents[CurState] =
2794               unwindCFIState(CurState, RememberState, CurBB, II);
2795           Stack.pop();
2796         }
2797       }
2798     }
2799   }
2800 }
2801 
2802 bool BinaryFunction::finalizeCFIState() {
2803   LLVM_DEBUG(
2804       dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2805   LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2806                     << ": ");
2807 
2808   const char *Sep = "";
2809   (void)Sep;
2810   for (FunctionFragment &FF : Layout.fragments()) {
2811     // Hot-cold border: at start of each region (with a different FDE) we need
2812     // to reset the CFI state.
2813     int32_t State = 0;
2814 
2815     for (BinaryBasicBlock *BB : FF) {
2816       const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2817 
2818       // We need to recover the correct state if it doesn't match expected
2819       // state at BB entry point.
2820       if (BB->getCFIState() < State) {
2821         // In this case, State is currently higher than what this BB expect it
2822         // to be. To solve this, we need to insert CFI instructions to undo
2823         // the effect of all CFI from BB's state to current State.
2824         auto InsertIt = BB->begin();
2825         unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2826       } else if (BB->getCFIState() > State) {
2827         // If BB's CFI state is greater than State, it means we are behind in
2828         // the state. Just emit all instructions to reach this state at the
2829         // beginning of this BB. If this sequence of instructions involve
2830         // remember state or restore state, bail out.
2831         if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2832           return false;
2833       }
2834 
2835       State = CFIStateAtExit;
2836       LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2837     }
2838   }
2839   LLVM_DEBUG(dbgs() << "\n");
2840 
2841   for (BinaryBasicBlock &BB : blocks()) {
2842     for (auto II = BB.begin(); II != BB.end();) {
2843       const MCCFIInstruction *CFI = getCFIFor(*II);
2844       if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2845                   CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2846         II = BB.eraseInstruction(II);
2847       } else {
2848         ++II;
2849       }
2850     }
2851   }
2852 
2853   return true;
2854 }
2855 
2856 bool BinaryFunction::requiresAddressTranslation() const {
2857   return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2858 }
2859 
2860 uint64_t BinaryFunction::getInstructionCount() const {
2861   uint64_t Count = 0;
2862   for (const BinaryBasicBlock &BB : blocks())
2863     Count += BB.getNumNonPseudos();
2864   return Count;
2865 }
2866 
2867 void BinaryFunction::clearDisasmState() {
2868   clearList(Instructions);
2869   clearList(IgnoredBranches);
2870   clearList(TakenBranches);
2871 
2872   if (BC.HasRelocations) {
2873     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2874       BC.UndefinedSymbols.insert(LI.second);
2875     for (MCSymbol *const EndLabel : FunctionEndLabels)
2876       if (EndLabel)
2877         BC.UndefinedSymbols.insert(EndLabel);
2878   }
2879 }
2880 
2881 void BinaryFunction::setTrapOnEntry() {
2882   clearDisasmState();
2883 
2884   forEachEntryPoint([&](uint64_t Offset, const MCSymbol *Label) -> bool {
2885     MCInst TrapInstr;
2886     BC.MIB->createTrap(TrapInstr);
2887     addInstruction(Offset, std::move(TrapInstr));
2888     return true;
2889   });
2890 
2891   TrapsOnEntry = true;
2892 }
2893 
2894 void BinaryFunction::setIgnored() {
2895   if (opts::processAllFunctions()) {
2896     // We can accept ignored functions before they've been disassembled.
2897     // In that case, they would still get disassembled and emited, but not
2898     // optimized.
2899     assert(CurrentState == State::Empty &&
2900            "cannot ignore non-empty functions in current mode");
2901     IsIgnored = true;
2902     return;
2903   }
2904 
2905   clearDisasmState();
2906 
2907   // Clear CFG state too.
2908   if (hasCFG()) {
2909     releaseCFG();
2910 
2911     for (BinaryBasicBlock *BB : BasicBlocks)
2912       delete BB;
2913     clearList(BasicBlocks);
2914 
2915     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2916       delete BB;
2917     clearList(DeletedBasicBlocks);
2918 
2919     Layout.clear();
2920   }
2921 
2922   CurrentState = State::Empty;
2923 
2924   IsIgnored = true;
2925   IsSimple = false;
2926   LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2927 }
2928 
2929 void BinaryFunction::duplicateConstantIslands() {
2930   assert(Islands && "function expected to have constant islands");
2931 
2932   for (BinaryBasicBlock *BB : getLayout().blocks()) {
2933     if (!BB->isCold())
2934       continue;
2935 
2936     for (MCInst &Inst : *BB) {
2937       int OpNum = 0;
2938       for (MCOperand &Operand : Inst) {
2939         if (!Operand.isExpr()) {
2940           ++OpNum;
2941           continue;
2942         }
2943         const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2944         // Check if this is an island symbol
2945         if (!Islands->Symbols.count(Symbol) &&
2946             !Islands->ProxySymbols.count(Symbol))
2947           continue;
2948 
2949         // Create cold symbol, if missing
2950         auto ISym = Islands->ColdSymbols.find(Symbol);
2951         MCSymbol *ColdSymbol;
2952         if (ISym != Islands->ColdSymbols.end()) {
2953           ColdSymbol = ISym->second;
2954         } else {
2955           ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
2956           Islands->ColdSymbols[Symbol] = ColdSymbol;
2957           // Check if this is a proxy island symbol and update owner proxy map
2958           if (Islands->ProxySymbols.count(Symbol)) {
2959             BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
2960             auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
2961             Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
2962           }
2963         }
2964 
2965         // Update instruction reference
2966         Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
2967             Inst,
2968             MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
2969                                     *BC.Ctx),
2970             *BC.Ctx, 0));
2971         ++OpNum;
2972       }
2973     }
2974   }
2975 }
2976 
2977 #ifndef MAX_PATH
2978 #define MAX_PATH 255
2979 #endif
2980 
2981 static std::string constructFilename(std::string Filename,
2982                                      std::string Annotation,
2983                                      std::string Suffix) {
2984   std::replace(Filename.begin(), Filename.end(), '/', '-');
2985   if (!Annotation.empty())
2986     Annotation.insert(0, "-");
2987   if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
2988     assert(Suffix.size() + Annotation.size() <= MAX_PATH);
2989     if (opts::Verbosity >= 1) {
2990       errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
2991              << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
2992     }
2993     Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
2994   }
2995   Filename += Annotation;
2996   Filename += Suffix;
2997   return Filename;
2998 }
2999 
3000 static std::string formatEscapes(const std::string &Str) {
3001   std::string Result;
3002   for (unsigned I = 0; I < Str.size(); ++I) {
3003     char C = Str[I];
3004     switch (C) {
3005     case '\n':
3006       Result += "&#13;";
3007       break;
3008     case '"':
3009       break;
3010     default:
3011       Result += C;
3012       break;
3013     }
3014   }
3015   return Result;
3016 }
3017 
3018 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3019   OS << "digraph \"" << getPrintName() << "\" {\n"
3020      << "node [fontname=courier, shape=box, style=filled, colorscheme=brbg9]\n";
3021   uint64_t Offset = Address;
3022   for (BinaryBasicBlock *BB : BasicBlocks) {
3023     auto LayoutPos = find(Layout.blocks(), BB);
3024     unsigned LayoutIndex = LayoutPos - Layout.block_begin();
3025     const char *ColdStr = BB->isCold() ? " (cold)" : "";
3026     std::vector<std::string> Attrs;
3027     // Bold box for entry points
3028     if (isEntryPoint(*BB))
3029       Attrs.push_back("penwidth=2");
3030     if (BLI && BLI->getLoopFor(BB)) {
3031       // Distinguish innermost loops
3032       const BinaryLoop *Loop = BLI->getLoopFor(BB);
3033       if (Loop->isInnermost())
3034         Attrs.push_back("fillcolor=6");
3035       else // some outer loop
3036         Attrs.push_back("fillcolor=4");
3037     } else { // non-loopy code
3038       Attrs.push_back("fillcolor=5");
3039     }
3040     ListSeparator LS;
3041     OS << "\"" << BB->getName() << "\" [";
3042     for (StringRef Attr : Attrs)
3043       OS << LS << Attr;
3044     OS << "]\n";
3045     OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u,CFI:%u)\\n",
3046                  BB->getName().data(), BB->getName().data(), ColdStr,
3047                  BB->getKnownExecutionCount(), BB->getOffset(), getIndex(BB),
3048                  LayoutIndex, BB->getCFIState());
3049 
3050     if (opts::DotToolTipCode) {
3051       std::string Str;
3052       raw_string_ostream CS(Str);
3053       Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this,
3054                                     /* PrintMCInst = */ false,
3055                                     /* PrintMemData = */ false,
3056                                     /* PrintRelocations = */ false,
3057                                     /* Endl = */ R"(\\l)");
3058       OS << formatEscapes(CS.str()) << '\n';
3059     }
3060     OS << "\"]\n";
3061 
3062     // analyzeBranch is just used to get the names of the branch
3063     // opcodes.
3064     const MCSymbol *TBB = nullptr;
3065     const MCSymbol *FBB = nullptr;
3066     MCInst *CondBranch = nullptr;
3067     MCInst *UncondBranch = nullptr;
3068     const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3069 
3070     const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3071     const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3072 
3073     auto BI = BB->branch_info_begin();
3074     for (BinaryBasicBlock *Succ : BB->successors()) {
3075       std::string Branch;
3076       if (Success) {
3077         if (Succ == BB->getConditionalSuccessor(true)) {
3078           Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3079                                     CondBranch->getOpcode()))
3080                               : "TB";
3081         } else if (Succ == BB->getConditionalSuccessor(false)) {
3082           Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3083                                       UncondBranch->getOpcode()))
3084                                 : "FB";
3085         } else {
3086           Branch = "FT";
3087         }
3088       }
3089       if (IsJumpTable)
3090         Branch = "JT";
3091       OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3092                    Succ->getName().data(), Branch.c_str());
3093 
3094       if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3095           BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3096         OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3097       } else if (ExecutionCount != COUNT_NO_PROFILE &&
3098                  BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3099         OS << "\\n(IC:" << BI->Count << ")";
3100       }
3101       OS << "\"]\n";
3102 
3103       ++BI;
3104     }
3105     for (BinaryBasicBlock *LP : BB->landing_pads()) {
3106       OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3107                    BB->getName().data(), LP->getName().data());
3108     }
3109   }
3110   OS << "}\n";
3111 }
3112 
3113 void BinaryFunction::viewGraph() const {
3114   SmallString<MAX_PATH> Filename;
3115   if (std::error_code EC =
3116           sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3117     errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3118            << " bolt-cfg-XXXXX.dot temporary file.\n";
3119     return;
3120   }
3121   dumpGraphToFile(std::string(Filename));
3122   if (DisplayGraph(Filename))
3123     errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3124   if (std::error_code EC = sys::fs::remove(Filename)) {
3125     errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3126            << Filename << "\n";
3127   }
3128 }
3129 
3130 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3131   if (!opts::shouldPrint(*this))
3132     return;
3133 
3134   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3135   if (opts::Verbosity >= 1)
3136     outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n";
3137   dumpGraphToFile(Filename);
3138 }
3139 
3140 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3141   std::error_code EC;
3142   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3143   if (EC) {
3144     if (opts::Verbosity >= 1) {
3145       errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3146              << Filename << " for output.\n";
3147     }
3148     return;
3149   }
3150   dumpGraph(of);
3151 }
3152 
3153 bool BinaryFunction::validateCFG() const {
3154   bool Valid = true;
3155   for (BinaryBasicBlock *BB : BasicBlocks)
3156     Valid &= BB->validateSuccessorInvariants();
3157 
3158   if (!Valid)
3159     return Valid;
3160 
3161   // Make sure all blocks in CFG are valid.
3162   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3163     if (!BB->isValid()) {
3164       errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3165              << " detected in:\n";
3166       this->dump();
3167       return false;
3168     }
3169     return true;
3170   };
3171   for (const BinaryBasicBlock *BB : BasicBlocks) {
3172     if (!validateBlock(BB, "block"))
3173       return false;
3174     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3175       if (!validateBlock(PredBB, "predecessor"))
3176         return false;
3177     for (const BinaryBasicBlock *SuccBB : BB->successors())
3178       if (!validateBlock(SuccBB, "successor"))
3179         return false;
3180     for (const BinaryBasicBlock *LP : BB->landing_pads())
3181       if (!validateBlock(LP, "landing pad"))
3182         return false;
3183     for (const BinaryBasicBlock *Thrower : BB->throwers())
3184       if (!validateBlock(Thrower, "thrower"))
3185         return false;
3186   }
3187 
3188   for (const BinaryBasicBlock *BB : BasicBlocks) {
3189     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3190     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3191       if (BBLandingPads.count(LP)) {
3192         errs() << "BOLT-ERROR: duplicate landing pad detected in"
3193                << BB->getName() << " in function " << *this << '\n';
3194         return false;
3195       }
3196       BBLandingPads.insert(LP);
3197     }
3198 
3199     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3200     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3201       if (BBThrowers.count(Thrower)) {
3202         errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3203                << " in function " << *this << '\n';
3204         return false;
3205       }
3206       BBThrowers.insert(Thrower);
3207     }
3208 
3209     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3210       if (!llvm::is_contained(LPBlock->throwers(), BB)) {
3211         errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3212                << ": " << BB->getName() << " is in LandingPads but not in "
3213                << LPBlock->getName() << " Throwers\n";
3214         return false;
3215       }
3216     }
3217     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3218       if (!llvm::is_contained(Thrower->landing_pads(), BB)) {
3219         errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3220                << ": " << BB->getName() << " is in Throwers list but not in "
3221                << Thrower->getName() << " LandingPads\n";
3222         return false;
3223       }
3224     }
3225   }
3226 
3227   return Valid;
3228 }
3229 
3230 void BinaryFunction::fixBranches() {
3231   auto &MIB = BC.MIB;
3232   MCContext *Ctx = BC.Ctx.get();
3233 
3234   for (BinaryBasicBlock *BB : BasicBlocks) {
3235     const MCSymbol *TBB = nullptr;
3236     const MCSymbol *FBB = nullptr;
3237     MCInst *CondBranch = nullptr;
3238     MCInst *UncondBranch = nullptr;
3239     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3240       continue;
3241 
3242     // We will create unconditional branch with correct destination if needed.
3243     if (UncondBranch)
3244       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3245 
3246     // Basic block that follows the current one in the final layout.
3247     const BinaryBasicBlock *NextBB =
3248         Layout.getBasicBlockAfter(BB, /*IgnoreSplits=*/false);
3249 
3250     if (BB->succ_size() == 1) {
3251       // __builtin_unreachable() could create a conditional branch that
3252       // falls-through into the next function - hence the block will have only
3253       // one valid successor. Since behaviour is undefined - we replace
3254       // the conditional branch with an unconditional if required.
3255       if (CondBranch)
3256         BB->eraseInstruction(BB->findInstruction(CondBranch));
3257       if (BB->getSuccessor() == NextBB)
3258         continue;
3259       BB->addBranchInstruction(BB->getSuccessor());
3260     } else if (BB->succ_size() == 2) {
3261       assert(CondBranch && "conditional branch expected");
3262       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3263       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3264       // Check whether we support reversing this branch direction
3265       const bool IsSupported = !MIB->isUnsupportedBranch(*CondBranch);
3266       if (NextBB && NextBB == TSuccessor && IsSupported) {
3267         std::swap(TSuccessor, FSuccessor);
3268         {
3269           auto L = BC.scopeLock();
3270           MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3271         }
3272         BB->swapConditionalSuccessors();
3273       } else {
3274         auto L = BC.scopeLock();
3275         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3276       }
3277       if (TSuccessor == FSuccessor)
3278         BB->removeDuplicateConditionalSuccessor(CondBranch);
3279       if (!NextBB ||
3280           ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3281         // If one of the branches is guaranteed to be "long" while the other
3282         // could be "short", then prioritize short for "taken". This will
3283         // generate a sequence 1 byte shorter on x86.
3284         if (IsSupported && BC.isX86() &&
3285             TSuccessor->getFragmentNum() != FSuccessor->getFragmentNum() &&
3286             BB->getFragmentNum() != TSuccessor->getFragmentNum()) {
3287           std::swap(TSuccessor, FSuccessor);
3288           {
3289             auto L = BC.scopeLock();
3290             MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3291                                         Ctx);
3292           }
3293           BB->swapConditionalSuccessors();
3294         }
3295         BB->addBranchInstruction(FSuccessor);
3296       }
3297     }
3298     // Cases where the number of successors is 0 (block ends with a
3299     // terminator) or more than 2 (switch table) don't require branch
3300     // instruction adjustments.
3301   }
3302   assert((!isSimple() || validateCFG()) &&
3303          "Invalid CFG detected after fixing branches");
3304 }
3305 
3306 void BinaryFunction::propagateGnuArgsSizeInfo(
3307     MCPlusBuilder::AllocatorIdTy AllocId) {
3308   assert(CurrentState == State::Disassembled && "unexpected function state");
3309 
3310   if (!hasEHRanges() || !usesGnuArgsSize())
3311     return;
3312 
3313   // The current value of DW_CFA_GNU_args_size affects all following
3314   // invoke instructions until the next CFI overrides it.
3315   // It is important to iterate basic blocks in the original order when
3316   // assigning the value.
3317   uint64_t CurrentGnuArgsSize = 0;
3318   for (BinaryBasicBlock *BB : BasicBlocks) {
3319     for (auto II = BB->begin(); II != BB->end();) {
3320       MCInst &Instr = *II;
3321       if (BC.MIB->isCFI(Instr)) {
3322         const MCCFIInstruction *CFI = getCFIFor(Instr);
3323         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3324           CurrentGnuArgsSize = CFI->getOffset();
3325           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3326           // during the final code emission. The information is embedded
3327           // inside call instructions.
3328           II = BB->erasePseudoInstruction(II);
3329           continue;
3330         }
3331       } else if (BC.MIB->isInvoke(Instr)) {
3332         // Add the value of GNU_args_size as an extra operand to invokes.
3333         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3334       }
3335       ++II;
3336     }
3337   }
3338 }
3339 
3340 void BinaryFunction::postProcessBranches() {
3341   if (!isSimple())
3342     return;
3343   for (BinaryBasicBlock &BB : blocks()) {
3344     auto LastInstrRI = BB.getLastNonPseudo();
3345     if (BB.succ_size() == 1) {
3346       if (LastInstrRI != BB.rend() &&
3347           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3348         // __builtin_unreachable() could create a conditional branch that
3349         // falls-through into the next function - hence the block will have only
3350         // one valid successor. Such behaviour is undefined and thus we remove
3351         // the conditional branch while leaving a valid successor.
3352         BB.eraseInstruction(std::prev(LastInstrRI.base()));
3353         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3354                           << BB.getName() << " in function " << *this << '\n');
3355       }
3356     } else if (BB.succ_size() == 0) {
3357       // Ignore unreachable basic blocks.
3358       if (BB.pred_size() == 0 || BB.isLandingPad())
3359         continue;
3360 
3361       // If it's the basic block that does not end up with a terminator - we
3362       // insert a return instruction unless it's a call instruction.
3363       if (LastInstrRI == BB.rend()) {
3364         LLVM_DEBUG(
3365             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3366                    << BB.getName() << " in function " << *this << '\n');
3367         continue;
3368       }
3369       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3370           !BC.MIB->isCall(*LastInstrRI)) {
3371         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3372                           << BB.getName() << " in function " << *this << '\n');
3373         MCInst ReturnInstr;
3374         BC.MIB->createReturn(ReturnInstr);
3375         BB.addInstruction(ReturnInstr);
3376       }
3377     }
3378   }
3379   assert(validateCFG() && "invalid CFG");
3380 }
3381 
3382 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3383   assert(Offset && "cannot add primary entry point");
3384   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3385 
3386   const uint64_t EntryPointAddress = getAddress() + Offset;
3387   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3388 
3389   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3390   if (EntrySymbol)
3391     return EntrySymbol;
3392 
3393   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3394     EntrySymbol = EntryBD->getSymbol();
3395   } else {
3396     EntrySymbol = BC.getOrCreateGlobalSymbol(
3397         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3398   }
3399   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3400 
3401   BC.setSymbolToFunctionMap(EntrySymbol, this);
3402 
3403   return EntrySymbol;
3404 }
3405 
3406 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3407   assert(CurrentState == State::CFG &&
3408          "basic block can be added as an entry only in a function with CFG");
3409 
3410   if (&BB == BasicBlocks.front())
3411     return getSymbol();
3412 
3413   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3414   if (EntrySymbol)
3415     return EntrySymbol;
3416 
3417   EntrySymbol =
3418       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3419 
3420   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3421 
3422   BC.setSymbolToFunctionMap(EntrySymbol, this);
3423 
3424   return EntrySymbol;
3425 }
3426 
3427 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3428   if (EntryID == 0)
3429     return getSymbol();
3430 
3431   if (!isMultiEntry())
3432     return nullptr;
3433 
3434   uint64_t NumEntries = 0;
3435   if (hasCFG()) {
3436     for (BinaryBasicBlock *BB : BasicBlocks) {
3437       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3438       if (!EntrySymbol)
3439         continue;
3440       if (NumEntries == EntryID)
3441         return EntrySymbol;
3442       ++NumEntries;
3443     }
3444   } else {
3445     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3446       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3447       if (!EntrySymbol)
3448         continue;
3449       if (NumEntries == EntryID)
3450         return EntrySymbol;
3451       ++NumEntries;
3452     }
3453   }
3454 
3455   return nullptr;
3456 }
3457 
3458 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3459   if (!isMultiEntry())
3460     return 0;
3461 
3462   for (const MCSymbol *FunctionSymbol : getSymbols())
3463     if (FunctionSymbol == Symbol)
3464       return 0;
3465 
3466   // Check all secondary entries available as either basic blocks or lables.
3467   uint64_t NumEntries = 0;
3468   for (const BinaryBasicBlock *BB : BasicBlocks) {
3469     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3470     if (!EntrySymbol)
3471       continue;
3472     if (EntrySymbol == Symbol)
3473       return NumEntries;
3474     ++NumEntries;
3475   }
3476   NumEntries = 0;
3477   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3478     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3479     if (!EntrySymbol)
3480       continue;
3481     if (EntrySymbol == Symbol)
3482       return NumEntries;
3483     ++NumEntries;
3484   }
3485 
3486   llvm_unreachable("symbol not found");
3487 }
3488 
3489 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3490   bool Status = Callback(0, getSymbol());
3491   if (!isMultiEntry())
3492     return Status;
3493 
3494   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3495     if (!Status)
3496       break;
3497 
3498     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3499     if (!EntrySymbol)
3500       continue;
3501 
3502     Status = Callback(KV.first, EntrySymbol);
3503   }
3504 
3505   return Status;
3506 }
3507 
3508 BinaryFunction::BasicBlockListType BinaryFunction::dfs() const {
3509   BasicBlockListType DFS;
3510   unsigned Index = 0;
3511   std::stack<BinaryBasicBlock *> Stack;
3512 
3513   // Push entry points to the stack in reverse order.
3514   //
3515   // NB: we rely on the original order of entries to match.
3516   SmallVector<BinaryBasicBlock *> EntryPoints;
3517   llvm::copy_if(BasicBlocks, std::back_inserter(EntryPoints),
3518           [&](const BinaryBasicBlock *const BB) { return isEntryPoint(*BB); });
3519   // Sort entry points by their offset to make sure we got them in the right
3520   // order.
3521   llvm::stable_sort(EntryPoints, [](const BinaryBasicBlock *const A,
3522                               const BinaryBasicBlock *const B) {
3523     return A->getOffset() < B->getOffset();
3524   });
3525   for (BinaryBasicBlock *const BB : reverse(EntryPoints))
3526     Stack.push(BB);
3527 
3528   for (BinaryBasicBlock &BB : blocks())
3529     BB.setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3530 
3531   while (!Stack.empty()) {
3532     BinaryBasicBlock *BB = Stack.top();
3533     Stack.pop();
3534 
3535     if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3536       continue;
3537 
3538     BB->setLayoutIndex(Index++);
3539     DFS.push_back(BB);
3540 
3541     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3542       Stack.push(SuccBB);
3543     }
3544 
3545     const MCSymbol *TBB = nullptr;
3546     const MCSymbol *FBB = nullptr;
3547     MCInst *CondBranch = nullptr;
3548     MCInst *UncondBranch = nullptr;
3549     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3550         BB->succ_size() == 2) {
3551       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3552               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3553         Stack.push(BB->getConditionalSuccessor(true));
3554         Stack.push(BB->getConditionalSuccessor(false));
3555       } else {
3556         Stack.push(BB->getConditionalSuccessor(false));
3557         Stack.push(BB->getConditionalSuccessor(true));
3558       }
3559     } else {
3560       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3561         Stack.push(SuccBB);
3562       }
3563     }
3564   }
3565 
3566   return DFS;
3567 }
3568 
3569 size_t BinaryFunction::computeHash(bool UseDFS,
3570                                    OperandHashFuncTy OperandHashFunc) const {
3571   if (size() == 0)
3572     return 0;
3573 
3574   assert(hasCFG() && "function is expected to have CFG");
3575 
3576   SmallVector<const BinaryBasicBlock *, 0> Order;
3577   if (UseDFS)
3578     llvm::copy(dfs(), std::back_inserter(Order));
3579   else
3580     llvm::copy(Layout.blocks(), std::back_inserter(Order));
3581 
3582   // The hash is computed by creating a string of all instruction opcodes and
3583   // possibly their operands and then hashing that string with std::hash.
3584   std::string HashString;
3585   for (const BinaryBasicBlock *BB : Order)
3586     HashString.append(hashBlock(BC, *BB, OperandHashFunc));
3587 
3588   return Hash = std::hash<std::string>{}(HashString);
3589 }
3590 
3591 void BinaryFunction::insertBasicBlocks(
3592     BinaryBasicBlock *Start,
3593     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3594     const bool UpdateLayout, const bool UpdateCFIState,
3595     const bool RecomputeLandingPads) {
3596   const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3597   const size_t NumNewBlocks = NewBBs.size();
3598 
3599   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3600                      nullptr);
3601 
3602   int64_t I = StartIndex + 1;
3603   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3604     assert(!BasicBlocks[I]);
3605     BasicBlocks[I++] = BB.release();
3606   }
3607 
3608   if (RecomputeLandingPads)
3609     recomputeLandingPads();
3610   else
3611     updateBBIndices(0);
3612 
3613   if (UpdateLayout)
3614     updateLayout(Start, NumNewBlocks);
3615 
3616   if (UpdateCFIState)
3617     updateCFIState(Start, NumNewBlocks);
3618 }
3619 
3620 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3621     BinaryFunction::iterator StartBB,
3622     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3623     const bool UpdateLayout, const bool UpdateCFIState,
3624     const bool RecomputeLandingPads) {
3625   const unsigned StartIndex = getIndex(&*StartBB);
3626   const size_t NumNewBlocks = NewBBs.size();
3627 
3628   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3629                      nullptr);
3630   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3631 
3632   unsigned I = StartIndex + 1;
3633   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3634     assert(!BasicBlocks[I]);
3635     BasicBlocks[I++] = BB.release();
3636   }
3637 
3638   if (RecomputeLandingPads)
3639     recomputeLandingPads();
3640   else
3641     updateBBIndices(0);
3642 
3643   if (UpdateLayout)
3644     updateLayout(*std::prev(RetIter), NumNewBlocks);
3645 
3646   if (UpdateCFIState)
3647     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3648 
3649   return RetIter;
3650 }
3651 
3652 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3653   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3654     BasicBlocks[I]->Index = I;
3655 }
3656 
3657 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3658                                     const unsigned NumNewBlocks) {
3659   const int32_t CFIState = Start->getCFIStateAtExit();
3660   const unsigned StartIndex = getIndex(Start) + 1;
3661   for (unsigned I = 0; I < NumNewBlocks; ++I)
3662     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3663 }
3664 
3665 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3666                                   const unsigned NumNewBlocks) {
3667   BasicBlockListType::iterator Begin;
3668   BasicBlockListType::iterator End;
3669 
3670   // If start not provided copy new blocks from the beginning of BasicBlocks
3671   if (!Start) {
3672     Begin = BasicBlocks.begin();
3673     End = BasicBlocks.begin() + NumNewBlocks;
3674   } else {
3675     unsigned StartIndex = getIndex(Start);
3676     Begin = std::next(BasicBlocks.begin(), StartIndex + 1);
3677     End = std::next(BasicBlocks.begin(), StartIndex + NumNewBlocks + 1);
3678   }
3679 
3680   // Insert new blocks in the layout immediately after Start.
3681   Layout.insertBasicBlocks(Start, {Begin, End});
3682   Layout.updateLayoutIndices();
3683 }
3684 
3685 bool BinaryFunction::checkForAmbiguousJumpTables() {
3686   SmallSet<uint64_t, 4> JumpTables;
3687   for (BinaryBasicBlock *&BB : BasicBlocks) {
3688     for (MCInst &Inst : *BB) {
3689       if (!BC.MIB->isIndirectBranch(Inst))
3690         continue;
3691       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3692       if (!JTAddress)
3693         continue;
3694       // This address can be inside another jump table, but we only consider
3695       // it ambiguous when the same start address is used, not the same JT
3696       // object.
3697       if (!JumpTables.count(JTAddress)) {
3698         JumpTables.insert(JTAddress);
3699         continue;
3700       }
3701       return true;
3702     }
3703   }
3704   return false;
3705 }
3706 
3707 void BinaryFunction::disambiguateJumpTables(
3708     MCPlusBuilder::AllocatorIdTy AllocId) {
3709   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3710   SmallPtrSet<JumpTable *, 4> JumpTables;
3711   for (BinaryBasicBlock *&BB : BasicBlocks) {
3712     for (MCInst &Inst : *BB) {
3713       if (!BC.MIB->isIndirectBranch(Inst))
3714         continue;
3715       JumpTable *JT = getJumpTable(Inst);
3716       if (!JT)
3717         continue;
3718       auto Iter = JumpTables.find(JT);
3719       if (Iter == JumpTables.end()) {
3720         JumpTables.insert(JT);
3721         continue;
3722       }
3723       // This instruction is an indirect jump using a jump table, but it is
3724       // using the same jump table of another jump. Try all our tricks to
3725       // extract the jump table symbol and make it point to a new, duplicated JT
3726       MCPhysReg BaseReg1;
3727       uint64_t Scale;
3728       const MCSymbol *Target;
3729       // In case we match if our first matcher, first instruction is the one to
3730       // patch
3731       MCInst *JTLoadInst = &Inst;
3732       // Try a standard indirect jump matcher, scale 8
3733       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3734           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3735                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3736                               /*Offset=*/BC.MIB->matchSymbol(Target));
3737       if (!IndJmpMatcher->match(
3738               *BC.MRI, *BC.MIB,
3739               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3740           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3741         MCPhysReg BaseReg2;
3742         uint64_t Offset;
3743         // Standard JT matching failed. Trying now:
3744         //     movq  "jt.2397/1"(,%rax,8), %rax
3745         //     jmpq  *%rax
3746         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3747             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3748                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3749                               /*Offset=*/BC.MIB->matchSymbol(Target));
3750         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3751         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3752             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3753         if (!IndJmpMatcher2->match(
3754                 *BC.MRI, *BC.MIB,
3755                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3756             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3757           // JT matching failed. Trying now:
3758           // PIC-style matcher, scale 4
3759           //    addq    %rdx, %rsi
3760           //    addq    %rdx, %rdi
3761           //    leaq    DATAat0x402450(%rip), %r11
3762           //    movslq  (%r11,%rdx,4), %rcx
3763           //    addq    %r11, %rcx
3764           //    jmpq    *%rcx # JUMPTABLE @0x402450
3765           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3766               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3767                   BC.MIB->matchReg(BaseReg1),
3768                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3769                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3770                                     BC.MIB->matchImm(Offset))));
3771           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3772               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3773           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3774           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3775               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3776                                                    BC.MIB->matchAnyOperand()));
3777           if (!PICIndJmpMatcher->match(
3778                   *BC.MRI, *BC.MIB,
3779                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3780               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3781               !PICBaseAddrMatcher->match(
3782                   *BC.MRI, *BC.MIB,
3783                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3784             llvm_unreachable("Failed to extract jump table base");
3785             continue;
3786           }
3787           // Matched PIC, identify the instruction with the reference to the JT
3788           JTLoadInst = LEAMatcher->CurInst;
3789         } else {
3790           // Matched non-PIC
3791           JTLoadInst = LoadMatcher->CurInst;
3792         }
3793       }
3794 
3795       uint64_t NewJumpTableID = 0;
3796       const MCSymbol *NewJTLabel;
3797       std::tie(NewJumpTableID, NewJTLabel) =
3798           BC.duplicateJumpTable(*this, JT, Target);
3799       {
3800         auto L = BC.scopeLock();
3801         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3802       }
3803       // We use a unique ID with the high bit set as address for this "injected"
3804       // jump table (not originally in the input binary).
3805       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3806     }
3807   }
3808 }
3809 
3810 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3811                                              BinaryBasicBlock *OldDest,
3812                                              BinaryBasicBlock *NewDest) {
3813   MCInst *Instr = BB->getLastNonPseudoInstr();
3814   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3815     return false;
3816   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3817   assert(JTAddress && "Invalid jump table address");
3818   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3819   assert(JT && "No jump table structure for this indirect branch");
3820   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3821                                         NewDest->getLabel());
3822   (void)Patched;
3823   assert(Patched && "Invalid entry to be replaced in jump table");
3824   return true;
3825 }
3826 
3827 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3828                                             BinaryBasicBlock *To) {
3829   // Create intermediate BB
3830   MCSymbol *Tmp;
3831   {
3832     auto L = BC.scopeLock();
3833     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3834   }
3835   // Link new BBs to the original input offset of the From BB, so we can map
3836   // samples recorded in new BBs back to the original BB seem in the input
3837   // binary (if using BAT)
3838   std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp);
3839   NewBB->setOffset(From->getInputOffset());
3840   BinaryBasicBlock *NewBBPtr = NewBB.get();
3841 
3842   // Update "From" BB
3843   auto I = From->succ_begin();
3844   auto BI = From->branch_info_begin();
3845   for (; I != From->succ_end(); ++I) {
3846     if (*I == To)
3847       break;
3848     ++BI;
3849   }
3850   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3851   uint64_t OrigCount = BI->Count;
3852   uint64_t OrigMispreds = BI->MispredictedCount;
3853   replaceJumpTableEntryIn(From, To, NewBBPtr);
3854   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3855 
3856   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3857   NewBB->setExecutionCount(OrigCount);
3858   NewBB->setIsCold(From->isCold());
3859 
3860   // Update CFI and BB layout with new intermediate BB
3861   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3862   NewBBs.emplace_back(std::move(NewBB));
3863   insertBasicBlocks(From, std::move(NewBBs), true, true,
3864                     /*RecomputeLandingPads=*/false);
3865   return NewBBPtr;
3866 }
3867 
3868 void BinaryFunction::deleteConservativeEdges() {
3869   // Our goal is to aggressively remove edges from the CFG that we believe are
3870   // wrong. This is used for instrumentation, where it is safe to remove
3871   // fallthrough edges because we won't reorder blocks.
3872   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3873     BinaryBasicBlock *BB = *I;
3874     if (BB->succ_size() != 1 || BB->size() == 0)
3875       continue;
3876 
3877     auto NextBB = std::next(I);
3878     MCInst *Last = BB->getLastNonPseudoInstr();
3879     // Fallthrough is a landing pad? Delete this edge (as long as we don't
3880     // have a direct jump to it)
3881     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3882         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3883       BB->removeAllSuccessors();
3884       continue;
3885     }
3886 
3887     // Look for suspicious calls at the end of BB where gcc may optimize it and
3888     // remove the jump to the epilogue when it knows the call won't return.
3889     if (!Last || !BC.MIB->isCall(*Last))
3890       continue;
3891 
3892     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3893     if (!CalleeSymbol)
3894       continue;
3895 
3896     StringRef CalleeName = CalleeSymbol->getName();
3897     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3898         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3899         CalleeName != "abort@PLT")
3900       continue;
3901 
3902     BB->removeAllSuccessors();
3903   }
3904 }
3905 
3906 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3907                                           uint64_t SymbolSize) const {
3908   // If this symbol is in a different section from the one where the
3909   // function symbol is, don't consider it as valid.
3910   if (!getOriginSection()->containsAddress(
3911           cantFail(Symbol.getAddress(), "cannot get symbol address")))
3912     return false;
3913 
3914   // Some symbols are tolerated inside function bodies, others are not.
3915   // The real function boundaries may not be known at this point.
3916   if (BC.isMarker(Symbol))
3917     return true;
3918 
3919   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3920   // function.
3921   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3922     return true;
3923 
3924   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3925     return false;
3926 
3927   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3928     return false;
3929 
3930   return true;
3931 }
3932 
3933 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3934   if (getKnownExecutionCount() == 0 || Count == 0)
3935     return;
3936 
3937   if (ExecutionCount < Count)
3938     Count = ExecutionCount;
3939 
3940   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
3941   if (AdjustmentRatio < 0.0)
3942     AdjustmentRatio = 0.0;
3943 
3944   for (BinaryBasicBlock &BB : blocks())
3945     BB.adjustExecutionCount(AdjustmentRatio);
3946 
3947   ExecutionCount -= Count;
3948 }
3949 
3950 BinaryFunction::~BinaryFunction() {
3951   for (BinaryBasicBlock *BB : BasicBlocks)
3952     delete BB;
3953   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
3954     delete BB;
3955 }
3956 
3957 void BinaryFunction::calculateLoopInfo() {
3958   // Discover loops.
3959   BinaryDominatorTree DomTree;
3960   DomTree.recalculate(*this);
3961   BLI.reset(new BinaryLoopInfo());
3962   BLI->analyze(DomTree);
3963 
3964   // Traverse discovered loops and add depth and profile information.
3965   std::stack<BinaryLoop *> St;
3966   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
3967     St.push(*I);
3968     ++BLI->OuterLoops;
3969   }
3970 
3971   while (!St.empty()) {
3972     BinaryLoop *L = St.top();
3973     St.pop();
3974     ++BLI->TotalLoops;
3975     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
3976 
3977     // Add nested loops in the stack.
3978     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3979       St.push(*I);
3980 
3981     // Skip if no valid profile is found.
3982     if (!hasValidProfile()) {
3983       L->EntryCount = COUNT_NO_PROFILE;
3984       L->ExitCount = COUNT_NO_PROFILE;
3985       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
3986       continue;
3987     }
3988 
3989     // Compute back edge count.
3990     SmallVector<BinaryBasicBlock *, 1> Latches;
3991     L->getLoopLatches(Latches);
3992 
3993     for (BinaryBasicBlock *Latch : Latches) {
3994       auto BI = Latch->branch_info_begin();
3995       for (BinaryBasicBlock *Succ : Latch->successors()) {
3996         if (Succ == L->getHeader()) {
3997           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
3998                  "profile data not found");
3999           L->TotalBackEdgeCount += BI->Count;
4000         }
4001         ++BI;
4002       }
4003     }
4004 
4005     // Compute entry count.
4006     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4007 
4008     // Compute exit count.
4009     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4010     L->getExitEdges(ExitEdges);
4011     for (BinaryLoop::Edge &Exit : ExitEdges) {
4012       const BinaryBasicBlock *Exiting = Exit.first;
4013       const BinaryBasicBlock *ExitTarget = Exit.second;
4014       auto BI = Exiting->branch_info_begin();
4015       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4016         if (Succ == ExitTarget) {
4017           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4018                  "profile data not found");
4019           L->ExitCount += BI->Count;
4020         }
4021         ++BI;
4022       }
4023     }
4024   }
4025 }
4026 
4027 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4028   if (!isEmitted()) {
4029     assert(!isInjected() && "injected function should be emitted");
4030     setOutputAddress(getAddress());
4031     setOutputSize(getSize());
4032     return;
4033   }
4034 
4035   const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4036   if (BC.HasRelocations || isInjected()) {
4037     const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4038     const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4039     setOutputAddress(BaseAddress + StartOffset);
4040     setOutputSize(EndOffset - StartOffset);
4041     if (hasConstantIsland()) {
4042       const uint64_t DataOffset =
4043           Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4044       setOutputDataAddress(BaseAddress + DataOffset);
4045       for (auto It : Islands->Offsets) {
4046         const uint64_t OldOffset = It.first;
4047         BinaryData *BD = BC.getBinaryDataAtAddress(getAddress() + OldOffset);
4048         if (!BD)
4049           continue;
4050 
4051         MCSymbol *Symbol = It.second;
4052         const uint64_t NewOffset = Layout.getSymbolOffset(*Symbol);
4053         BD->setOutputLocation(*getCodeSection(), NewOffset);
4054       }
4055     }
4056     if (isSplit()) {
4057       for (FunctionFragment &FF : getLayout().getSplitFragments()) {
4058         ErrorOr<BinarySection &> ColdSection =
4059             getCodeSection(FF.getFragmentNum());
4060         // If fragment is empty, cold section might not exist
4061         if (FF.empty() && ColdSection.getError())
4062           continue;
4063         const uint64_t ColdBaseAddress = ColdSection->getOutputAddress();
4064 
4065         const MCSymbol *ColdStartSymbol = getSymbol(FF.getFragmentNum());
4066         // If fragment is empty, symbol might have not been emitted
4067         if (FF.empty() && (!ColdStartSymbol || !ColdStartSymbol->isDefined()) &&
4068             !hasConstantIsland())
4069           continue;
4070         assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4071                "split function should have defined cold symbol");
4072         const MCSymbol *ColdEndSymbol =
4073             getFunctionEndLabel(FF.getFragmentNum());
4074         assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4075                "split function should have defined cold end symbol");
4076         const uint64_t ColdStartOffset =
4077             Layout.getSymbolOffset(*ColdStartSymbol);
4078         const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4079         FF.setAddress(ColdBaseAddress + ColdStartOffset);
4080         FF.setImageSize(ColdEndOffset - ColdStartOffset);
4081         if (hasConstantIsland()) {
4082           const uint64_t DataOffset =
4083               Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4084           setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4085         }
4086       }
4087     }
4088   } else {
4089     setOutputAddress(getAddress());
4090     setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4091   }
4092 
4093   // Update basic block output ranges for the debug info, if we have
4094   // secondary entry points in the symbol table to update or if writing BAT.
4095   if (!opts::UpdateDebugSections && !isMultiEntry() &&
4096       !requiresAddressTranslation())
4097     return;
4098 
4099   // Output ranges should match the input if the body hasn't changed.
4100   if (!isSimple() && !BC.HasRelocations)
4101     return;
4102 
4103   // AArch64 may have functions that only contains a constant island (no code).
4104   if (getLayout().block_empty())
4105     return;
4106 
4107   for (FunctionFragment &FF : getLayout().fragments()) {
4108     if (FF.empty())
4109       continue;
4110 
4111     const uint64_t FragmentBaseAddress =
4112         getCodeSection(isSimple() ? FF.getFragmentNum() : FragmentNum::main())
4113             ->getOutputAddress();
4114 
4115     BinaryBasicBlock *PrevBB = nullptr;
4116     for (BinaryBasicBlock *const BB : FF) {
4117       assert(BB->getLabel()->isDefined() && "symbol should be defined");
4118       if (!BC.HasRelocations) {
4119         if (BB->isSplit())
4120           assert(FragmentBaseAddress == FF.getAddress());
4121         else
4122           assert(FragmentBaseAddress == getOutputAddress());
4123       }
4124 
4125       const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4126       const uint64_t BBAddress = FragmentBaseAddress + BBOffset;
4127       BB->setOutputStartAddress(BBAddress);
4128 
4129       if (PrevBB)
4130         PrevBB->setOutputEndAddress(BBAddress);
4131       PrevBB = BB;
4132 
4133       BB->updateOutputValues(Layout);
4134     }
4135 
4136     PrevBB->setOutputEndAddress(PrevBB->isSplit()
4137                                     ? FF.getAddress() + FF.getImageSize()
4138                                     : getOutputAddress() + getOutputSize());
4139   }
4140 }
4141 
4142 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4143   DebugAddressRangesVector OutputRanges;
4144 
4145   if (isFolded())
4146     return OutputRanges;
4147 
4148   if (IsFragment)
4149     return OutputRanges;
4150 
4151   OutputRanges.emplace_back(getOutputAddress(),
4152                             getOutputAddress() + getOutputSize());
4153   if (isSplit()) {
4154     assert(isEmitted() && "split function should be emitted");
4155     for (const FunctionFragment &FF : getLayout().getSplitFragments())
4156       OutputRanges.emplace_back(FF.getAddress(),
4157                                 FF.getAddress() + FF.getImageSize());
4158   }
4159 
4160   if (isSimple())
4161     return OutputRanges;
4162 
4163   for (BinaryFunction *Frag : Fragments) {
4164     assert(!Frag->isSimple() &&
4165            "fragment of non-simple function should also be non-simple");
4166     OutputRanges.emplace_back(Frag->getOutputAddress(),
4167                               Frag->getOutputAddress() + Frag->getOutputSize());
4168   }
4169 
4170   return OutputRanges;
4171 }
4172 
4173 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4174   if (isFolded())
4175     return 0;
4176 
4177   // If the function hasn't changed return the same address.
4178   if (!isEmitted())
4179     return Address;
4180 
4181   if (Address < getAddress())
4182     return 0;
4183 
4184   // Check if the address is associated with an instruction that is tracked
4185   // by address translation.
4186   auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4187   if (KV != InputOffsetToAddressMap.end())
4188     return KV->second;
4189 
4190   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4191   //        intact. Instead we can use pseudo instructions and/or annotations.
4192   const uint64_t Offset = Address - getAddress();
4193   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4194   if (!BB) {
4195     // Special case for address immediately past the end of the function.
4196     if (Offset == getSize())
4197       return getOutputAddress() + getOutputSize();
4198 
4199     return 0;
4200   }
4201 
4202   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4203                   BB->getOutputAddressRange().second);
4204 }
4205 
4206 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4207     const DWARFAddressRangesVector &InputRanges) const {
4208   DebugAddressRangesVector OutputRanges;
4209 
4210   if (isFolded())
4211     return OutputRanges;
4212 
4213   // If the function hasn't changed return the same ranges.
4214   if (!isEmitted()) {
4215     OutputRanges.resize(InputRanges.size());
4216     llvm::transform(InputRanges, OutputRanges.begin(),
4217                     [](const DWARFAddressRange &Range) {
4218                       return DebugAddressRange(Range.LowPC, Range.HighPC);
4219                     });
4220     return OutputRanges;
4221   }
4222 
4223   // Even though we will merge ranges in a post-processing pass, we attempt to
4224   // merge them in a main processing loop as it improves the processing time.
4225   uint64_t PrevEndAddress = 0;
4226   for (const DWARFAddressRange &Range : InputRanges) {
4227     if (!containsAddress(Range.LowPC)) {
4228       LLVM_DEBUG(
4229           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4230                  << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4231                  << Twine::utohexstr(Range.HighPC) << "]\n");
4232       PrevEndAddress = 0;
4233       continue;
4234     }
4235     uint64_t InputOffset = Range.LowPC - getAddress();
4236     const uint64_t InputEndOffset =
4237         std::min(Range.HighPC - getAddress(), getSize());
4238 
4239     auto BBI = llvm::upper_bound(BasicBlockOffsets,
4240                                  BasicBlockOffset(InputOffset, nullptr),
4241                                  CompareBasicBlockOffsets());
4242     --BBI;
4243     do {
4244       const BinaryBasicBlock *BB = BBI->second;
4245       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4246         LLVM_DEBUG(
4247             dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4248                    << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4249                    << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4250         PrevEndAddress = 0;
4251         break;
4252       }
4253 
4254       // Skip the range if the block was deleted.
4255       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4256         const uint64_t StartAddress =
4257             OutputStart + InputOffset - BB->getOffset();
4258         uint64_t EndAddress = BB->getOutputAddressRange().second;
4259         if (InputEndOffset < BB->getEndOffset())
4260           EndAddress = StartAddress + InputEndOffset - InputOffset;
4261 
4262         if (StartAddress == PrevEndAddress) {
4263           OutputRanges.back().HighPC =
4264               std::max(OutputRanges.back().HighPC, EndAddress);
4265         } else {
4266           OutputRanges.emplace_back(StartAddress,
4267                                     std::max(StartAddress, EndAddress));
4268         }
4269         PrevEndAddress = OutputRanges.back().HighPC;
4270       }
4271 
4272       InputOffset = BB->getEndOffset();
4273       ++BBI;
4274     } while (InputOffset < InputEndOffset);
4275   }
4276 
4277   // Post-processing pass to sort and merge ranges.
4278   llvm::sort(OutputRanges);
4279   DebugAddressRangesVector MergedRanges;
4280   PrevEndAddress = 0;
4281   for (const DebugAddressRange &Range : OutputRanges) {
4282     if (Range.LowPC <= PrevEndAddress) {
4283       MergedRanges.back().HighPC =
4284           std::max(MergedRanges.back().HighPC, Range.HighPC);
4285     } else {
4286       MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4287     }
4288     PrevEndAddress = MergedRanges.back().HighPC;
4289   }
4290 
4291   return MergedRanges;
4292 }
4293 
4294 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4295   if (CurrentState == State::Disassembled) {
4296     auto II = Instructions.find(Offset);
4297     return (II == Instructions.end()) ? nullptr : &II->second;
4298   } else if (CurrentState == State::CFG) {
4299     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4300     if (!BB)
4301       return nullptr;
4302 
4303     for (MCInst &Inst : *BB) {
4304       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4305       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4306         return &Inst;
4307     }
4308 
4309     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4310       const uint32_t Size =
4311           BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4312       if (BB->getEndOffset() - Offset == Size)
4313         return LastInstr;
4314     }
4315 
4316     return nullptr;
4317   } else {
4318     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4319   }
4320 }
4321 
4322 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4323     const DebugLocationsVector &InputLL) const {
4324   DebugLocationsVector OutputLL;
4325 
4326   if (isFolded())
4327     return OutputLL;
4328 
4329   // If the function hasn't changed - there's nothing to update.
4330   if (!isEmitted())
4331     return InputLL;
4332 
4333   uint64_t PrevEndAddress = 0;
4334   SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4335   for (const DebugLocationEntry &Entry : InputLL) {
4336     const uint64_t Start = Entry.LowPC;
4337     const uint64_t End = Entry.HighPC;
4338     if (!containsAddress(Start)) {
4339       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4340                            "for "
4341                         << *this << " : [0x" << Twine::utohexstr(Start)
4342                         << ", 0x" << Twine::utohexstr(End) << "]\n");
4343       continue;
4344     }
4345     uint64_t InputOffset = Start - getAddress();
4346     const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4347     auto BBI = llvm::upper_bound(BasicBlockOffsets,
4348                                  BasicBlockOffset(InputOffset, nullptr),
4349                                  CompareBasicBlockOffsets());
4350     --BBI;
4351     do {
4352       const BinaryBasicBlock *BB = BBI->second;
4353       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4354         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4355                              "for "
4356                           << *this << " : [0x" << Twine::utohexstr(Start)
4357                           << ", 0x" << Twine::utohexstr(End) << "]\n");
4358         PrevEndAddress = 0;
4359         break;
4360       }
4361 
4362       // Skip the range if the block was deleted.
4363       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4364         const uint64_t StartAddress =
4365             OutputStart + InputOffset - BB->getOffset();
4366         uint64_t EndAddress = BB->getOutputAddressRange().second;
4367         if (InputEndOffset < BB->getEndOffset())
4368           EndAddress = StartAddress + InputEndOffset - InputOffset;
4369 
4370         if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4371           OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4372         } else {
4373           OutputLL.emplace_back(DebugLocationEntry{
4374               StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4375         }
4376         PrevEndAddress = OutputLL.back().HighPC;
4377         PrevExpr = &OutputLL.back().Expr;
4378       }
4379 
4380       ++BBI;
4381       InputOffset = BB->getEndOffset();
4382     } while (InputOffset < InputEndOffset);
4383   }
4384 
4385   // Sort and merge adjacent entries with identical location.
4386   llvm::stable_sort(
4387       OutputLL, [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4388         return A.LowPC < B.LowPC;
4389       });
4390   DebugLocationsVector MergedLL;
4391   PrevEndAddress = 0;
4392   PrevExpr = nullptr;
4393   for (const DebugLocationEntry &Entry : OutputLL) {
4394     if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4395       MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4396     } else {
4397       const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4398       const uint64_t End = std::max(Begin, Entry.HighPC);
4399       MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4400     }
4401     PrevEndAddress = MergedLL.back().HighPC;
4402     PrevExpr = &MergedLL.back().Expr;
4403   }
4404 
4405   return MergedLL;
4406 }
4407 
4408 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4409   if (!opts::shouldPrint(*this))
4410     return;
4411 
4412   OS << "Loop Info for Function \"" << *this << "\"";
4413   if (hasValidProfile())
4414     OS << " (count: " << getExecutionCount() << ")";
4415   OS << "\n";
4416 
4417   std::stack<BinaryLoop *> St;
4418   for (BinaryLoop *L : *BLI)
4419     St.push(L);
4420   while (!St.empty()) {
4421     BinaryLoop *L = St.top();
4422     St.pop();
4423 
4424     for (BinaryLoop *Inner : *L)
4425       St.push(Inner);
4426 
4427     if (!hasValidProfile())
4428       continue;
4429 
4430     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4431        << " loop header: " << L->getHeader()->getName();
4432     OS << "\n";
4433     OS << "Loop basic blocks: ";
4434     ListSeparator LS;
4435     for (BinaryBasicBlock *BB : L->blocks())
4436       OS << LS << BB->getName();
4437     OS << "\n";
4438     if (hasValidProfile()) {
4439       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4440       OS << "Loop entry count: " << L->EntryCount << "\n";
4441       OS << "Loop exit count: " << L->ExitCount << "\n";
4442       if (L->EntryCount > 0) {
4443         OS << "Average iters per entry: "
4444            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4445            << "\n";
4446       }
4447     }
4448     OS << "----\n";
4449   }
4450 
4451   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4452   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4453   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4454 }
4455 
4456 bool BinaryFunction::isAArch64Veneer() const {
4457   if (empty() || hasIslandsInfo())
4458     return false;
4459 
4460   BinaryBasicBlock &BB = **BasicBlocks.begin();
4461   for (MCInst &Inst : BB)
4462     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4463       return false;
4464 
4465   for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) {
4466     for (MCInst &Inst : **I)
4467       if (!BC.MIB->isNoop(Inst))
4468         return false;
4469   }
4470 
4471   return true;
4472 }
4473 
4474 void BinaryFunction::addRelocation(uint64_t Address, MCSymbol *Symbol,
4475                                    uint64_t RelType, uint64_t Addend,
4476                                    uint64_t Value) {
4477   assert(Address >= getAddress() && Address < getAddress() + getMaxSize() &&
4478          "address is outside of the function");
4479   uint64_t Offset = Address - getAddress();
4480   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addRelocation in "
4481                     << formatv("{0}@{1:x} against {2}\n", *this, Offset,
4482                                Symbol->getName()));
4483   bool IsCI = BC.isAArch64() && isInConstantIsland(Address);
4484   std::map<uint64_t, Relocation> &Rels =
4485       IsCI ? Islands->Relocations : Relocations;
4486   if (BC.MIB->shouldRecordCodeRelocation(RelType))
4487     Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
4488 }
4489 
4490 } // namespace bolt
4491 } // namespace llvm
4492