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