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