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