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