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