xref: /llvm-project/bolt/lib/Core/BinaryFunction.cpp (revision 8cb7a873ab8568acfbfd6c27a927d924cc994017)
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/MCRegisterInfo.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     if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) {
1269       uint64_t TargetAddress = 0;
1270       if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1271                               TargetAddress)) {
1272         // Check if the target is within the same function. Otherwise it's
1273         // a call, possibly a tail call.
1274         //
1275         // If the target *is* the function address it could be either a branch
1276         // or a recursive call.
1277         bool IsCall = MIB->isCall(Instruction);
1278         const bool IsCondBranch = MIB->isConditionalBranch(Instruction);
1279         MCSymbol *TargetSymbol = nullptr;
1280 
1281         if (BC.MIB->isUnsupportedBranch(Instruction.getOpcode())) {
1282           setIgnored();
1283           if (BinaryFunction *TargetFunc =
1284                   BC.getBinaryFunctionContainingAddress(TargetAddress))
1285             TargetFunc->setIgnored();
1286         }
1287 
1288         if (IsCall && containsAddress(TargetAddress)) {
1289           if (TargetAddress == getAddress()) {
1290             // Recursive call.
1291             TargetSymbol = getSymbol();
1292           } else {
1293             if (BC.isX86()) {
1294               // Dangerous old-style x86 PIC code. We may need to freeze this
1295               // function, so preserve the function as is for now.
1296               PreserveNops = true;
1297             } else {
1298               errs() << "BOLT-WARNING: internal call detected at 0x"
1299                      << Twine::utohexstr(AbsoluteInstrAddr) << " in function "
1300                      << *this << ". Skipping.\n";
1301               IsSimple = false;
1302             }
1303           }
1304         }
1305 
1306         if (!TargetSymbol) {
1307           // Create either local label or external symbol.
1308           if (containsAddress(TargetAddress)) {
1309             TargetSymbol = getOrCreateLocalLabel(TargetAddress);
1310           } else {
1311             if (TargetAddress == getAddress() + getSize() &&
1312                 TargetAddress < getAddress() + getMaxSize()) {
1313               // Result of __builtin_unreachable().
1314               LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x"
1315                                 << Twine::utohexstr(AbsoluteInstrAddr)
1316                                 << " in function " << *this
1317                                 << " : replacing with nop.\n");
1318               BC.MIB->createNoop(Instruction);
1319               if (IsCondBranch) {
1320                 // Register branch offset for profile validation.
1321                 IgnoredBranches.emplace_back(Offset, Offset + Size);
1322               }
1323               goto add_instruction;
1324             }
1325             // May update Instruction and IsCall
1326             TargetSymbol = handleExternalReference(Instruction, Size, Offset,
1327                                                    TargetAddress, IsCall);
1328           }
1329         }
1330 
1331         if (!IsCall) {
1332           // Add taken branch info.
1333           TakenBranches.emplace_back(Offset, TargetAddress - getAddress());
1334         }
1335         BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx);
1336 
1337         // Mark CTC.
1338         if (IsCondBranch && IsCall)
1339           MIB->setConditionalTailCall(Instruction, TargetAddress);
1340       } else {
1341         // Could not evaluate branch. Should be an indirect call or an
1342         // indirect branch. Bail out on the latter case.
1343         if (MIB->isIndirectBranch(Instruction))
1344           handleIndirectBranch(Instruction, Size, Offset);
1345         // Indirect call. We only need to fix it if the operand is RIP-relative.
1346         if (IsSimple && MIB->hasPCRelOperand(Instruction))
1347           handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1348 
1349         if (BC.isAArch64())
1350           handleAArch64IndirectCall(Instruction, Offset);
1351       }
1352     } else {
1353       // Check if there's a relocation associated with this instruction.
1354       bool UsedReloc = false;
1355       for (auto Itr = Relocations.lower_bound(Offset),
1356                 ItrE = Relocations.lower_bound(Offset + Size);
1357            Itr != ItrE; ++Itr) {
1358         const Relocation &Relocation = Itr->second;
1359         uint64_t SymbolValue = Relocation.Value - Relocation.Addend;
1360         if (Relocation.isPCRelative())
1361           SymbolValue += getAddress() + Relocation.Offset;
1362 
1363         // Process reference to the symbol.
1364         if (BC.isX86())
1365           BC.handleAddressRef(SymbolValue, *this, Relocation.isPCRelative());
1366 
1367         if (BC.isAArch64() || !Relocation.isPCRelative()) {
1368           int64_t Value = Relocation.Value;
1369           const bool Result = BC.MIB->replaceImmWithSymbolRef(
1370               Instruction, Relocation.Symbol, Relocation.Addend, Ctx.get(),
1371               Value, Relocation.Type);
1372           (void)Result;
1373           assert(Result && "cannot replace immediate with relocation");
1374 
1375           if (BC.isX86()) {
1376             // Make sure we replaced the correct immediate (instruction
1377             // can have multiple immediate operands).
1378             assert(
1379                 truncateToSize(static_cast<uint64_t>(Value),
1380                                Relocation::getSizeForType(Relocation.Type)) ==
1381                     truncateToSize(Relocation.Value, Relocation::getSizeForType(
1382                                                          Relocation.Type)) &&
1383                 "immediate value mismatch in function");
1384           } else if (BC.isAArch64()) {
1385             // For aarch, if we replaced an immediate with a symbol from a
1386             // relocation, we mark it so we do not try to further process a
1387             // pc-relative operand. All we need is the symbol.
1388             UsedReloc = true;
1389           }
1390         } else {
1391           // Check if the relocation matches memop's Disp.
1392           uint64_t TargetAddress;
1393           if (!BC.MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1394                                                 AbsoluteInstrAddr, Size)) {
1395             errs() << "BOLT-ERROR: PC-relative operand can't be evaluated\n";
1396             exit(1);
1397           }
1398           assert(TargetAddress == Relocation.Value + AbsoluteInstrAddr + Size &&
1399                  "Immediate value mismatch detected.");
1400 
1401           const MCExpr *Expr = MCSymbolRefExpr::create(
1402               Relocation.Symbol, MCSymbolRefExpr::VK_None, *BC.Ctx);
1403           // Real addend for pc-relative targets is adjusted with a delta
1404           // from relocation placement to the next instruction.
1405           const uint64_t TargetAddend =
1406               Relocation.Addend + Offset + Size - Relocation.Offset;
1407           if (TargetAddend) {
1408             const MCConstantExpr *Offset =
1409                 MCConstantExpr::create(TargetAddend, *BC.Ctx);
1410             Expr = MCBinaryExpr::createAdd(Expr, Offset, *BC.Ctx);
1411           }
1412           BC.MIB->replaceMemOperandDisp(
1413               Instruction, MCOperand::createExpr(BC.MIB->getTargetExprFor(
1414                                Instruction, Expr, *BC.Ctx, 0)));
1415           UsedReloc = true;
1416         }
1417       }
1418 
1419       if (MIB->hasPCRelOperand(Instruction) && !UsedReloc)
1420         handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1421     }
1422 
1423 add_instruction:
1424     if (getDWARFLineTable()) {
1425       Instruction.setLoc(findDebugLineInformationForInstructionAt(
1426           AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable()));
1427     }
1428 
1429     // Record offset of the instruction for profile matching.
1430     if (BC.keepOffsetForInstruction(Instruction))
1431       MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
1432 
1433     if (BC.MIB->isNoop(Instruction)) {
1434       // NOTE: disassembly loses the correct size information for noops.
1435       //       E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
1436       //       5 bytes. Preserve the size info using annotations.
1437       MIB->addAnnotation(Instruction, "Size", static_cast<uint32_t>(Size));
1438     }
1439 
1440     addInstruction(Offset, std::move(Instruction));
1441   }
1442 
1443   clearList(Relocations);
1444 
1445   if (!IsSimple) {
1446     clearList(Instructions);
1447     return false;
1448   }
1449 
1450   updateState(State::Disassembled);
1451 
1452   return true;
1453 }
1454 
1455 bool BinaryFunction::scanExternalRefs() {
1456   bool Success = true;
1457   bool DisassemblyFailed = false;
1458 
1459   // Ignore pseudo functions.
1460   if (isPseudo())
1461     return Success;
1462 
1463   if (opts::NoScan) {
1464     clearList(Relocations);
1465     clearList(ExternallyReferencedOffsets);
1466 
1467     return false;
1468   }
1469 
1470   // List of external references for this function.
1471   std::vector<Relocation> FunctionRelocations;
1472 
1473   static BinaryContext::IndependentCodeEmitter Emitter =
1474       BC.createIndependentMCCodeEmitter();
1475 
1476   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1477   assert(ErrorOrFunctionData && "function data is not available");
1478   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1479   assert(FunctionData.size() == getMaxSize() &&
1480          "function size does not match raw data size");
1481 
1482   uint64_t Size = 0; // instruction size
1483   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1484     // Check for data inside code and ignore it
1485     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1486       Size = DataInCodeSize;
1487       continue;
1488     }
1489 
1490     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1491     MCInst Instruction;
1492     if (!BC.DisAsm->getInstruction(Instruction, Size,
1493                                    FunctionData.slice(Offset),
1494                                    AbsoluteInstrAddr, nulls())) {
1495       if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) {
1496         errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1497                << Twine::utohexstr(Offset) << " (address 0x"
1498                << Twine::utohexstr(AbsoluteInstrAddr) << ") in function "
1499                << *this << '\n';
1500       }
1501       Success = false;
1502       DisassemblyFailed = true;
1503       break;
1504     }
1505 
1506     // Return true if we can skip handling the Target function reference.
1507     auto ignoreFunctionRef = [&](const BinaryFunction &Target) {
1508       if (&Target == this)
1509         return true;
1510 
1511       // Note that later we may decide not to emit Target function. In that
1512       // case, we conservatively create references that will be ignored or
1513       // resolved to the same function.
1514       if (!BC.shouldEmit(Target))
1515         return true;
1516 
1517       return false;
1518     };
1519 
1520     // Return true if we can ignore reference to the symbol.
1521     auto ignoreReference = [&](const MCSymbol *TargetSymbol) {
1522       if (!TargetSymbol)
1523         return true;
1524 
1525       if (BC.forceSymbolRelocations(TargetSymbol->getName()))
1526         return false;
1527 
1528       BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol);
1529       if (!TargetFunction)
1530         return true;
1531 
1532       return ignoreFunctionRef(*TargetFunction);
1533     };
1534 
1535     // Detect if the instruction references an address.
1536     // Without relocations, we can only trust PC-relative address modes.
1537     uint64_t TargetAddress = 0;
1538     bool IsPCRel = false;
1539     bool IsBranch = false;
1540     if (BC.MIB->hasPCRelOperand(Instruction)) {
1541       if (BC.MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1542                                            AbsoluteInstrAddr, Size)) {
1543         IsPCRel = true;
1544       }
1545     } else if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) {
1546       if (BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1547                                  TargetAddress)) {
1548         IsBranch = true;
1549       }
1550     }
1551 
1552     MCSymbol *TargetSymbol = nullptr;
1553 
1554     // Create an entry point at reference address if needed.
1555     BinaryFunction *TargetFunction =
1556         BC.getBinaryFunctionContainingAddress(TargetAddress);
1557     if (TargetFunction && !ignoreFunctionRef(*TargetFunction)) {
1558       const uint64_t FunctionOffset =
1559           TargetAddress - TargetFunction->getAddress();
1560       TargetSymbol = FunctionOffset
1561                          ? TargetFunction->addEntryPointAtOffset(FunctionOffset)
1562                          : TargetFunction->getSymbol();
1563     }
1564 
1565     // Can't find more references and not creating relocations.
1566     if (!BC.HasRelocations)
1567       continue;
1568 
1569     // Create a relocation against the TargetSymbol as the symbol might get
1570     // moved.
1571     if (TargetSymbol) {
1572       if (IsBranch) {
1573         BC.MIB->replaceBranchTarget(Instruction, TargetSymbol,
1574                                     Emitter.LocalCtx.get());
1575       } else if (IsPCRel) {
1576         const MCExpr *Expr = MCSymbolRefExpr::create(
1577             TargetSymbol, MCSymbolRefExpr::VK_None, *Emitter.LocalCtx.get());
1578         BC.MIB->replaceMemOperandDisp(
1579             Instruction, MCOperand::createExpr(BC.MIB->getTargetExprFor(
1580                              Instruction, Expr, *Emitter.LocalCtx.get(), 0)));
1581       }
1582     }
1583 
1584     // Create more relocations based on input file relocations.
1585     bool HasRel = false;
1586     for (auto Itr = Relocations.lower_bound(Offset),
1587               ItrE = Relocations.lower_bound(Offset + Size);
1588          Itr != ItrE; ++Itr) {
1589       Relocation &Relocation = Itr->second;
1590       if (Relocation.isPCRelative() && BC.isX86())
1591         continue;
1592       if (ignoreReference(Relocation.Symbol))
1593         continue;
1594 
1595       int64_t Value = Relocation.Value;
1596       const bool Result = BC.MIB->replaceImmWithSymbolRef(
1597           Instruction, Relocation.Symbol, Relocation.Addend,
1598           Emitter.LocalCtx.get(), Value, Relocation.Type);
1599       (void)Result;
1600       assert(Result && "cannot replace immediate with relocation");
1601 
1602       HasRel = true;
1603     }
1604 
1605     if (!TargetSymbol && !HasRel)
1606       continue;
1607 
1608     // Emit the instruction using temp emitter and generate relocations.
1609     SmallString<256> Code;
1610     SmallVector<MCFixup, 4> Fixups;
1611     raw_svector_ostream VecOS(Code);
1612     Emitter.MCE->encodeInstruction(Instruction, VecOS, Fixups, *BC.STI);
1613 
1614     // Create relocation for every fixup.
1615     for (const MCFixup &Fixup : Fixups) {
1616       Optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB);
1617       if (!Rel) {
1618         Success = false;
1619         continue;
1620       }
1621 
1622       if (Relocation::getSizeForType(Rel->Type) < 4) {
1623         // If the instruction uses a short form, then we might not be able
1624         // to handle the rewrite without relaxation, and hence cannot reliably
1625         // create an external reference relocation.
1626         Success = false;
1627         continue;
1628       }
1629       Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset;
1630       FunctionRelocations.push_back(*Rel);
1631     }
1632 
1633     if (!Success)
1634       break;
1635   }
1636 
1637   // Add relocations unless disassembly failed for this function.
1638   if (!DisassemblyFailed)
1639     for (Relocation &Rel : FunctionRelocations)
1640       getOriginSection()->addPendingRelocation(Rel);
1641 
1642   // Inform BinaryContext that this function symbols will not be defined and
1643   // relocations should not be created against them.
1644   if (BC.HasRelocations) {
1645     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
1646       BC.UndefinedSymbols.insert(LI.second);
1647     if (FunctionEndLabel)
1648       BC.UndefinedSymbols.insert(FunctionEndLabel);
1649   }
1650 
1651   clearList(Relocations);
1652   clearList(ExternallyReferencedOffsets);
1653 
1654   if (Success && BC.HasRelocations)
1655     HasExternalRefRelocations = true;
1656 
1657   if (opts::Verbosity >= 1 && !Success)
1658     outs() << "BOLT-INFO: failed to scan refs for  " << *this << '\n';
1659 
1660   return Success;
1661 }
1662 
1663 void BinaryFunction::postProcessEntryPoints() {
1664   if (!isSimple())
1665     return;
1666 
1667   for (auto &KV : Labels) {
1668     MCSymbol *Label = KV.second;
1669     if (!getSecondaryEntryPointSymbol(Label))
1670       continue;
1671 
1672     // In non-relocation mode there's potentially an external undetectable
1673     // reference to the entry point and hence we cannot move this entry
1674     // point. Optimizing without moving could be difficult.
1675     if (!BC.HasRelocations)
1676       setSimple(false);
1677 
1678     const uint32_t Offset = KV.first;
1679 
1680     // If we are at Offset 0 and there is no instruction associated with it,
1681     // this means this is an empty function. Just ignore. If we find an
1682     // instruction at this offset, this entry point is valid.
1683     if (!Offset || getInstructionAtOffset(Offset))
1684       continue;
1685 
1686     // On AArch64 there are legitimate reasons to have references past the
1687     // end of the function, e.g. jump tables.
1688     if (BC.isAArch64() && Offset == getSize())
1689       continue;
1690 
1691     errs() << "BOLT-WARNING: reference in the middle of instruction "
1692               "detected in function "
1693            << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n';
1694     if (BC.HasRelocations)
1695       setIgnored();
1696     setSimple(false);
1697     return;
1698   }
1699 }
1700 
1701 void BinaryFunction::postProcessJumpTables() {
1702   // Create labels for all entries.
1703   for (auto &JTI : JumpTables) {
1704     JumpTable &JT = *JTI.second;
1705     if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) {
1706       opts::JumpTables = JTS_MOVE;
1707       outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was "
1708                 "detected in function "
1709              << *this << '\n';
1710     }
1711     for (unsigned I = 0; I < JT.OffsetEntries.size(); ++I) {
1712       MCSymbol *Label =
1713           getOrCreateLocalLabel(getAddress() + JT.OffsetEntries[I],
1714                                 /*CreatePastEnd*/ true);
1715       JT.Entries.push_back(Label);
1716     }
1717 
1718     const uint64_t BDSize =
1719         BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1720     if (!BDSize) {
1721       BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1722     } else {
1723       assert(BDSize >= JT.getSize() &&
1724              "jump table cannot be larger than the containing object");
1725     }
1726   }
1727 
1728   // Add TakenBranches from JumpTables.
1729   //
1730   // We want to do it after initial processing since we don't know jump tables'
1731   // boundaries until we process them all.
1732   for (auto &JTSite : JTSites) {
1733     const uint64_t JTSiteOffset = JTSite.first;
1734     const uint64_t JTAddress = JTSite.second;
1735     const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1736     assert(JT && "cannot find jump table for address");
1737 
1738     uint64_t EntryOffset = JTAddress - JT->getAddress();
1739     while (EntryOffset < JT->getSize()) {
1740       uint64_t TargetOffset = JT->OffsetEntries[EntryOffset / JT->EntrySize];
1741       if (TargetOffset < getSize()) {
1742         TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1743 
1744         if (opts::StrictMode)
1745           registerReferencedOffset(TargetOffset);
1746       }
1747 
1748       EntryOffset += JT->EntrySize;
1749 
1750       // A label at the next entry means the end of this jump table.
1751       if (JT->Labels.count(EntryOffset))
1752         break;
1753     }
1754   }
1755   clearList(JTSites);
1756 
1757   // Free memory used by jump table offsets.
1758   for (auto &JTI : JumpTables) {
1759     JumpTable &JT = *JTI.second;
1760     clearList(JT.OffsetEntries);
1761   }
1762 
1763   // Conservatively populate all possible destinations for unknown indirect
1764   // branches.
1765   if (opts::StrictMode && hasInternalReference()) {
1766     for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1767       for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1768         // Ignore __builtin_unreachable().
1769         if (PossibleDestination == getSize())
1770           continue;
1771         TakenBranches.emplace_back(Offset, PossibleDestination);
1772       }
1773     }
1774   }
1775 
1776   // Remove duplicates branches. We can get a bunch of them from jump tables.
1777   // Without doing jump table value profiling we don't have use for extra
1778   // (duplicate) branches.
1779   std::sort(TakenBranches.begin(), TakenBranches.end());
1780   auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
1781   TakenBranches.erase(NewEnd, TakenBranches.end());
1782 }
1783 
1784 bool BinaryFunction::postProcessIndirectBranches(
1785     MCPlusBuilder::AllocatorIdTy AllocId) {
1786   auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
1787     HasUnknownControlFlow = true;
1788     BB.removeAllSuccessors();
1789     for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1790       if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1791         BB.addSuccessor(SuccBB);
1792   };
1793 
1794   uint64_t NumIndirectJumps = 0;
1795   MCInst *LastIndirectJump = nullptr;
1796   BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1797   uint64_t LastJT = 0;
1798   uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1799   for (BinaryBasicBlock *BB : layout()) {
1800     for (MCInst &Instr : *BB) {
1801       if (!BC.MIB->isIndirectBranch(Instr))
1802         continue;
1803 
1804       // If there's an indirect branch in a single-block function -
1805       // it must be a tail call.
1806       if (layout_size() == 1) {
1807         BC.MIB->convertJmpToTailCall(Instr);
1808         return true;
1809       }
1810 
1811       ++NumIndirectJumps;
1812 
1813       if (opts::StrictMode && !hasInternalReference()) {
1814         BC.MIB->convertJmpToTailCall(Instr);
1815         break;
1816       }
1817 
1818       // Validate the tail call or jump table assumptions now that we know
1819       // basic block boundaries.
1820       if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1821         const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1822         MCInst *MemLocInstr;
1823         unsigned BaseRegNum, IndexRegNum;
1824         int64_t DispValue;
1825         const MCExpr *DispExpr;
1826         MCInst *PCRelBaseInstr;
1827         IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
1828             Instr, BB->begin(), BB->end(), PtrSize, MemLocInstr, BaseRegNum,
1829             IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
1830         if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1831           continue;
1832 
1833         if (!opts::StrictMode)
1834           return false;
1835 
1836         if (BC.MIB->isTailCall(Instr)) {
1837           BC.MIB->convertTailCallToJmp(Instr);
1838         } else {
1839           LastIndirectJump = &Instr;
1840           LastIndirectJumpBB = BB;
1841           LastJT = BC.MIB->getJumpTable(Instr);
1842           LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1843           BC.MIB->unsetJumpTable(Instr);
1844 
1845           JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1846           if (JT->Type == JumpTable::JTT_NORMAL) {
1847             // Invalidating the jump table may also invalidate other jump table
1848             // boundaries. Until we have/need a support for this, mark the
1849             // function as non-simple.
1850             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1851                               << JT->getName() << " in " << *this << '\n');
1852             return false;
1853           }
1854         }
1855 
1856         addUnknownControlFlow(*BB);
1857         continue;
1858       }
1859 
1860       // If this block contains an epilogue code and has an indirect branch,
1861       // then most likely it's a tail call. Otherwise, we cannot tell for sure
1862       // what it is and conservatively reject the function's CFG.
1863       bool IsEpilogue = false;
1864       for (const MCInst &Instr : *BB) {
1865         if (BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr)) {
1866           IsEpilogue = true;
1867           break;
1868         }
1869       }
1870       if (IsEpilogue) {
1871         BC.MIB->convertJmpToTailCall(Instr);
1872         BB->removeAllSuccessors();
1873         continue;
1874       }
1875 
1876       if (opts::Verbosity >= 2) {
1877         outs() << "BOLT-INFO: rejected potential indirect tail call in "
1878                << "function " << *this << " in basic block " << BB->getName()
1879                << ".\n";
1880         LLVM_DEBUG(BC.printInstructions(dbgs(), BB->begin(), BB->end(),
1881                                         BB->getOffset(), this, true));
1882       }
1883 
1884       if (!opts::StrictMode)
1885         return false;
1886 
1887       addUnknownControlFlow(*BB);
1888     }
1889   }
1890 
1891   if (HasInternalLabelReference)
1892     return false;
1893 
1894   // If there's only one jump table, and one indirect jump, and no other
1895   // references, then we should be able to derive the jump table even if we
1896   // fail to match the pattern.
1897   if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
1898       JumpTables.size() == 1 && LastIndirectJump) {
1899     BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1900     HasUnknownControlFlow = false;
1901 
1902     LastIndirectJumpBB->updateJumpTableSuccessors();
1903   }
1904 
1905   if (HasFixedIndirectBranch)
1906     return false;
1907 
1908   if (HasUnknownControlFlow && !BC.HasRelocations)
1909     return false;
1910 
1911   return true;
1912 }
1913 
1914 void BinaryFunction::recomputeLandingPads() {
1915   updateBBIndices(0);
1916 
1917   for (BinaryBasicBlock *BB : BasicBlocks) {
1918     BB->LandingPads.clear();
1919     BB->Throwers.clear();
1920   }
1921 
1922   for (BinaryBasicBlock *BB : BasicBlocks) {
1923     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1924     for (MCInst &Instr : *BB) {
1925       if (!BC.MIB->isInvoke(Instr))
1926         continue;
1927 
1928       const Optional<MCPlus::MCLandingPad> EHInfo = BC.MIB->getEHInfo(Instr);
1929       if (!EHInfo || !EHInfo->first)
1930         continue;
1931 
1932       BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1933       if (!BBLandingPads.count(LPBlock)) {
1934         BBLandingPads.insert(LPBlock);
1935         BB->LandingPads.emplace_back(LPBlock);
1936         LPBlock->Throwers.emplace_back(BB);
1937       }
1938     }
1939   }
1940 }
1941 
1942 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1943   auto &MIB = BC.MIB;
1944 
1945   if (!isSimple()) {
1946     assert(!BC.HasRelocations &&
1947            "cannot process file with non-simple function in relocs mode");
1948     return false;
1949   }
1950 
1951   if (CurrentState != State::Disassembled)
1952     return false;
1953 
1954   assert(BasicBlocks.empty() && "basic block list should be empty");
1955   assert((Labels.find(0) != Labels.end()) &&
1956          "first instruction should always have a label");
1957 
1958   // Create basic blocks in the original layout order:
1959   //
1960   //  * Every instruction with associated label marks
1961   //    the beginning of a basic block.
1962   //  * Conditional instruction marks the end of a basic block,
1963   //    except when the following instruction is an
1964   //    unconditional branch, and the unconditional branch is not
1965   //    a destination of another branch. In the latter case, the
1966   //    basic block will consist of a single unconditional branch
1967   //    (missed "double-jump" optimization).
1968   //
1969   // Created basic blocks are sorted in layout order since they are
1970   // created in the same order as instructions, and instructions are
1971   // sorted by offsets.
1972   BinaryBasicBlock *InsertBB = nullptr;
1973   BinaryBasicBlock *PrevBB = nullptr;
1974   bool IsLastInstrNop = false;
1975   // Offset of the last non-nop instruction.
1976   uint64_t LastInstrOffset = 0;
1977 
1978   auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1979                                    BinaryBasicBlock *InsertBB) {
1980     for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1981               FE = OffsetToCFI.upper_bound(CFIOffset);
1982          FI != FE; ++FI) {
1983       addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1984     }
1985   };
1986 
1987   // For profiling purposes we need to save the offset of the last instruction
1988   // in the basic block.
1989   // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1990   //       older profiles ignored nops.
1991   auto updateOffset = [&](uint64_t Offset) {
1992     assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
1993     MCInst *LastNonNop = nullptr;
1994     for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
1995                                             E = PrevBB->rend();
1996          RII != E; ++RII) {
1997       if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
1998         LastNonNop = &*RII;
1999         break;
2000       }
2001     }
2002     if (LastNonNop && !MIB->getOffset(*LastNonNop))
2003       MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId);
2004   };
2005 
2006   for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
2007     const uint32_t Offset = I->first;
2008     MCInst &Instr = I->second;
2009 
2010     auto LI = Labels.find(Offset);
2011     if (LI != Labels.end()) {
2012       // Always create new BB at branch destination.
2013       PrevBB = InsertBB ? InsertBB : PrevBB;
2014       InsertBB = addBasicBlock(LI->first, LI->second,
2015                                opts::PreserveBlocksAlignment && IsLastInstrNop);
2016       if (PrevBB)
2017         updateOffset(LastInstrOffset);
2018     }
2019 
2020     const uint64_t InstrInputAddr = I->first + Address;
2021     bool IsSDTMarker =
2022         MIB->isNoop(Instr) && BC.SDTMarkers.count(InstrInputAddr);
2023     bool IsLKMarker = BC.LKMarkers.count(InstrInputAddr);
2024     // Mark all nops with Offset for profile tracking purposes.
2025     if (MIB->isNoop(Instr) || IsLKMarker) {
2026       if (!MIB->getOffset(Instr))
2027         MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId);
2028       if (IsSDTMarker || IsLKMarker)
2029         HasSDTMarker = true;
2030       else
2031         // Annotate ordinary nops, so we can safely delete them if required.
2032         MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2033     }
2034 
2035     if (!InsertBB) {
2036       // It must be a fallthrough or unreachable code. Create a new block unless
2037       // we see an unconditional branch following a conditional one. The latter
2038       // should not be a conditional tail call.
2039       assert(PrevBB && "no previous basic block for a fall through");
2040       MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2041       assert(PrevInstr && "no previous instruction for a fall through");
2042       if (MIB->isUnconditionalBranch(Instr) &&
2043           !MIB->isUnconditionalBranch(*PrevInstr) &&
2044           !MIB->getConditionalTailCall(*PrevInstr) &&
2045           !MIB->isReturn(*PrevInstr)) {
2046         // Temporarily restore inserter basic block.
2047         InsertBB = PrevBB;
2048       } else {
2049         MCSymbol *Label;
2050         {
2051           auto L = BC.scopeLock();
2052           Label = BC.Ctx->createNamedTempSymbol("FT");
2053         }
2054         InsertBB = addBasicBlock(
2055             Offset, Label, opts::PreserveBlocksAlignment && IsLastInstrNop);
2056         updateOffset(LastInstrOffset);
2057       }
2058     }
2059     if (Offset == 0) {
2060       // Add associated CFI pseudos in the first offset (0)
2061       addCFIPlaceholders(0, InsertBB);
2062     }
2063 
2064     const bool IsBlockEnd = MIB->isTerminator(Instr);
2065     IsLastInstrNop = MIB->isNoop(Instr);
2066     if (!IsLastInstrNop)
2067       LastInstrOffset = Offset;
2068     InsertBB->addInstruction(std::move(Instr));
2069 
2070     // Add associated CFI instrs. We always add the CFI instruction that is
2071     // located immediately after this instruction, since the next CFI
2072     // instruction reflects the change in state caused by this instruction.
2073     auto NextInstr = std::next(I);
2074     uint64_t CFIOffset;
2075     if (NextInstr != E)
2076       CFIOffset = NextInstr->first;
2077     else
2078       CFIOffset = getSize();
2079 
2080     // Note: this potentially invalidates instruction pointers/iterators.
2081     addCFIPlaceholders(CFIOffset, InsertBB);
2082 
2083     if (IsBlockEnd) {
2084       PrevBB = InsertBB;
2085       InsertBB = nullptr;
2086     }
2087   }
2088 
2089   if (BasicBlocks.empty()) {
2090     setSimple(false);
2091     return false;
2092   }
2093 
2094   // Intermediate dump.
2095   LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2096 
2097   // TODO: handle properly calls to no-return functions,
2098   // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2099   // blocks.
2100 
2101   for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2102     LLVM_DEBUG(dbgs() << "registering branch [0x"
2103                       << Twine::utohexstr(Branch.first) << "] -> [0x"
2104                       << Twine::utohexstr(Branch.second) << "]\n");
2105     BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2106     BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2107     if (!FromBB || !ToBB) {
2108       if (!FromBB)
2109         errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2110       if (!ToBB)
2111         errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2112       BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2113                            *this);
2114     }
2115 
2116     FromBB->addSuccessor(ToBB);
2117   }
2118 
2119   // Add fall-through branches.
2120   PrevBB = nullptr;
2121   bool IsPrevFT = false; // Is previous block a fall-through.
2122   for (BinaryBasicBlock *BB : BasicBlocks) {
2123     if (IsPrevFT)
2124       PrevBB->addSuccessor(BB);
2125 
2126     if (BB->empty()) {
2127       IsPrevFT = true;
2128       PrevBB = BB;
2129       continue;
2130     }
2131 
2132     MCInst *LastInstr = BB->getLastNonPseudoInstr();
2133     assert(LastInstr &&
2134            "should have non-pseudo instruction in non-empty block");
2135 
2136     if (BB->succ_size() == 0) {
2137       // Since there's no existing successors, we know the last instruction is
2138       // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2139       // fall-through.
2140       //
2141       // Conditional tail call is a special case since we don't add a taken
2142       // branch successor for it.
2143       IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2144                  MIB->getConditionalTailCall(*LastInstr);
2145     } else if (BB->succ_size() == 1) {
2146       IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2147     } else {
2148       IsPrevFT = false;
2149     }
2150 
2151     PrevBB = BB;
2152   }
2153 
2154   // Assign landing pads and throwers info.
2155   recomputeLandingPads();
2156 
2157   // Assign CFI information to each BB entry.
2158   annotateCFIState();
2159 
2160   // Annotate invoke instructions with GNU_args_size data.
2161   propagateGnuArgsSizeInfo(AllocatorId);
2162 
2163   // Set the basic block layout to the original order and set end offsets.
2164   PrevBB = nullptr;
2165   for (BinaryBasicBlock *BB : BasicBlocks) {
2166     BasicBlocksLayout.emplace_back(BB);
2167     if (PrevBB)
2168       PrevBB->setEndOffset(BB->getOffset());
2169     PrevBB = BB;
2170   }
2171   PrevBB->setEndOffset(getSize());
2172 
2173   updateLayoutIndices();
2174 
2175   normalizeCFIState();
2176 
2177   // Clean-up memory taken by intermediate structures.
2178   //
2179   // NB: don't clear Labels list as we may need them if we mark the function
2180   //     as non-simple later in the process of discovering extra entry points.
2181   clearList(Instructions);
2182   clearList(OffsetToCFI);
2183   clearList(TakenBranches);
2184 
2185   // Update the state.
2186   CurrentState = State::CFG;
2187 
2188   // Make any necessary adjustments for indirect branches.
2189   if (!postProcessIndirectBranches(AllocatorId)) {
2190     if (opts::Verbosity) {
2191       errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2192              << *this << '\n';
2193     }
2194     // In relocation mode we want to keep processing the function but avoid
2195     // optimizing it.
2196     setSimple(false);
2197   }
2198 
2199   clearList(ExternallyReferencedOffsets);
2200   clearList(UnknownIndirectBranchOffsets);
2201 
2202   return true;
2203 }
2204 
2205 void BinaryFunction::postProcessCFG() {
2206   if (isSimple() && !BasicBlocks.empty()) {
2207     // Convert conditional tail call branches to conditional branches that jump
2208     // to a tail call.
2209     removeConditionalTailCalls();
2210 
2211     postProcessProfile();
2212 
2213     // Eliminate inconsistencies between branch instructions and CFG.
2214     postProcessBranches();
2215   }
2216 
2217   calculateMacroOpFusionStats();
2218 
2219   // The final cleanup of intermediate structures.
2220   clearList(IgnoredBranches);
2221 
2222   // Remove "Offset" annotations, unless we need an address-translation table
2223   // later. This has no cost, since annotations are allocated by a bumpptr
2224   // allocator and won't be released anyway until late in the pipeline.
2225   if (!requiresAddressTranslation() && !opts::Instrument) {
2226     for (BinaryBasicBlock *BB : layout())
2227       for (MCInst &Inst : *BB)
2228         BC.MIB->clearOffset(Inst);
2229   }
2230 
2231   assert((!isSimple() || validateCFG()) &&
2232          "invalid CFG detected after post-processing");
2233 }
2234 
2235 void BinaryFunction::calculateMacroOpFusionStats() {
2236   if (!getBinaryContext().isX86())
2237     return;
2238   for (BinaryBasicBlock *BB : layout()) {
2239     auto II = BB->getMacroOpFusionPair();
2240     if (II == BB->end())
2241       continue;
2242 
2243     // Check offset of the second instruction.
2244     // FIXME: arch-specific.
2245     const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2246     if (!Offset || (getAddress() + Offset) % 64)
2247       continue;
2248 
2249     LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2250                       << Twine::utohexstr(getAddress() + Offset)
2251                       << " in function " << *this << "; executed "
2252                       << BB->getKnownExecutionCount() << " times.\n");
2253     ++BC.MissedMacroFusionPairs;
2254     BC.MissedMacroFusionExecCount += BB->getKnownExecutionCount();
2255   }
2256 }
2257 
2258 void BinaryFunction::removeTagsFromProfile() {
2259   for (BinaryBasicBlock *BB : BasicBlocks) {
2260     if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2261       BB->ExecutionCount = 0;
2262     for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2263       if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2264           BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2265         continue;
2266       BI.Count = 0;
2267       BI.MispredictedCount = 0;
2268     }
2269   }
2270 }
2271 
2272 void BinaryFunction::removeConditionalTailCalls() {
2273   // Blocks to be appended at the end.
2274   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2275 
2276   for (auto BBI = begin(); BBI != end(); ++BBI) {
2277     BinaryBasicBlock &BB = *BBI;
2278     MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2279     if (!CTCInstr)
2280       continue;
2281 
2282     Optional<uint64_t> TargetAddressOrNone =
2283         BC.MIB->getConditionalTailCall(*CTCInstr);
2284     if (!TargetAddressOrNone)
2285       continue;
2286 
2287     // Gather all necessary information about CTC instruction before
2288     // annotations are destroyed.
2289     const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2290     uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2291     uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2292     if (hasValidProfile()) {
2293       CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2294           *CTCInstr, "CTCTakenCount");
2295       CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2296           *CTCInstr, "CTCMispredCount");
2297     }
2298 
2299     // Assert that the tail call does not throw.
2300     assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2301            "found tail call with associated landing pad");
2302 
2303     // Create a basic block with an unconditional tail call instruction using
2304     // the same destination.
2305     const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2306     assert(CTCTargetLabel && "symbol expected for conditional tail call");
2307     MCInst TailCallInstr;
2308     BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2309     // Link new BBs to the original input offset of the BB where the CTC
2310     // is, so we can map samples recorded in new BBs back to the original BB
2311     // seem in the input binary (if using BAT)
2312     std::unique_ptr<BinaryBasicBlock> TailCallBB = createBasicBlock(
2313         BB.getInputOffset(), BC.Ctx->createNamedTempSymbol("TC"));
2314     TailCallBB->addInstruction(TailCallInstr);
2315     TailCallBB->setCFIState(CFIStateBeforeCTC);
2316 
2317     // Add CFG edge with profile info from BB to TailCallBB.
2318     BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2319 
2320     // Add execution count for the block.
2321     TailCallBB->setExecutionCount(CTCTakenCount);
2322 
2323     BC.MIB->convertTailCallToJmp(*CTCInstr);
2324 
2325     BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2326                                 BC.Ctx.get());
2327 
2328     // Add basic block to the list that will be added to the end.
2329     NewBlocks.emplace_back(std::move(TailCallBB));
2330 
2331     // Swap edges as the TailCallBB corresponds to the taken branch.
2332     BB.swapConditionalSuccessors();
2333 
2334     // This branch is no longer a conditional tail call.
2335     BC.MIB->unsetConditionalTailCall(*CTCInstr);
2336   }
2337 
2338   insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2339                     /* UpdateLayout */ true,
2340                     /* UpdateCFIState */ false);
2341 }
2342 
2343 uint64_t BinaryFunction::getFunctionScore() const {
2344   if (FunctionScore != -1)
2345     return FunctionScore;
2346 
2347   if (!isSimple() || !hasValidProfile()) {
2348     FunctionScore = 0;
2349     return FunctionScore;
2350   }
2351 
2352   uint64_t TotalScore = 0ULL;
2353   for (BinaryBasicBlock *BB : layout()) {
2354     uint64_t BBExecCount = BB->getExecutionCount();
2355     if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2356       continue;
2357     TotalScore += BBExecCount;
2358   }
2359   FunctionScore = TotalScore;
2360   return FunctionScore;
2361 }
2362 
2363 void BinaryFunction::annotateCFIState() {
2364   assert(CurrentState == State::Disassembled && "unexpected function state");
2365   assert(!BasicBlocks.empty() && "basic block list should not be empty");
2366 
2367   // This is an index of the last processed CFI in FDE CFI program.
2368   uint32_t State = 0;
2369 
2370   // This is an index of RememberState CFI reflecting effective state right
2371   // after execution of RestoreState CFI.
2372   //
2373   // It differs from State iff the CFI at (State-1)
2374   // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2375   //
2376   // This allows us to generate shorter replay sequences when producing new
2377   // CFI programs.
2378   uint32_t EffectiveState = 0;
2379 
2380   // For tracking RememberState/RestoreState sequences.
2381   std::stack<uint32_t> StateStack;
2382 
2383   for (BinaryBasicBlock *BB : BasicBlocks) {
2384     BB->setCFIState(EffectiveState);
2385 
2386     for (const MCInst &Instr : *BB) {
2387       const MCCFIInstruction *CFI = getCFIFor(Instr);
2388       if (!CFI)
2389         continue;
2390 
2391       ++State;
2392 
2393       switch (CFI->getOperation()) {
2394       case MCCFIInstruction::OpRememberState:
2395         StateStack.push(EffectiveState);
2396         EffectiveState = State;
2397         break;
2398       case MCCFIInstruction::OpRestoreState:
2399         assert(!StateStack.empty() && "corrupt CFI stack");
2400         EffectiveState = StateStack.top();
2401         StateStack.pop();
2402         break;
2403       case MCCFIInstruction::OpGnuArgsSize:
2404         // OpGnuArgsSize CFIs do not affect the CFI state.
2405         break;
2406       default:
2407         // Any other CFI updates the state.
2408         EffectiveState = State;
2409         break;
2410       }
2411     }
2412   }
2413 
2414   assert(StateStack.empty() && "corrupt CFI stack");
2415 }
2416 
2417 namespace {
2418 
2419 /// Our full interpretation of a DWARF CFI machine state at a given point
2420 struct CFISnapshot {
2421   /// CFA register number and offset defining the canonical frame at this
2422   /// point, or the number of a rule (CFI state) that computes it with a
2423   /// DWARF expression. This number will be negative if it refers to a CFI
2424   /// located in the CIE instead of the FDE.
2425   uint32_t CFAReg;
2426   int32_t CFAOffset;
2427   int32_t CFARule;
2428   /// Mapping of rules (CFI states) that define the location of each
2429   /// register. If absent, no rule defining the location of such register
2430   /// was ever read. This number will be negative if it refers to a CFI
2431   /// located in the CIE instead of the FDE.
2432   DenseMap<int32_t, int32_t> RegRule;
2433 
2434   /// References to CIE, FDE and expanded instructions after a restore state
2435   const BinaryFunction::CFIInstrMapType &CIE;
2436   const BinaryFunction::CFIInstrMapType &FDE;
2437   const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2438 
2439   /// Current FDE CFI number representing the state where the snapshot is at
2440   int32_t CurState;
2441 
2442   /// Used when we don't have information about which state/rule to apply
2443   /// to recover the location of either the CFA or a specific register
2444   constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2445 
2446 private:
2447   /// Update our snapshot by executing a single CFI
2448   void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2449     switch (Instr.getOperation()) {
2450     case MCCFIInstruction::OpSameValue:
2451     case MCCFIInstruction::OpRelOffset:
2452     case MCCFIInstruction::OpOffset:
2453     case MCCFIInstruction::OpRestore:
2454     case MCCFIInstruction::OpUndefined:
2455     case MCCFIInstruction::OpRegister:
2456       RegRule[Instr.getRegister()] = RuleNumber;
2457       break;
2458     case MCCFIInstruction::OpDefCfaRegister:
2459       CFAReg = Instr.getRegister();
2460       CFARule = UNKNOWN;
2461       break;
2462     case MCCFIInstruction::OpDefCfaOffset:
2463       CFAOffset = Instr.getOffset();
2464       CFARule = UNKNOWN;
2465       break;
2466     case MCCFIInstruction::OpDefCfa:
2467       CFAReg = Instr.getRegister();
2468       CFAOffset = Instr.getOffset();
2469       CFARule = UNKNOWN;
2470       break;
2471     case MCCFIInstruction::OpEscape: {
2472       Optional<uint8_t> Reg = readDWARFExpressionTargetReg(Instr.getValues());
2473       // Handle DW_CFA_def_cfa_expression
2474       if (!Reg) {
2475         CFARule = RuleNumber;
2476         break;
2477       }
2478       RegRule[*Reg] = RuleNumber;
2479       break;
2480     }
2481     case MCCFIInstruction::OpAdjustCfaOffset:
2482     case MCCFIInstruction::OpWindowSave:
2483     case MCCFIInstruction::OpNegateRAState:
2484     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2485       llvm_unreachable("unsupported CFI opcode");
2486       break;
2487     case MCCFIInstruction::OpRememberState:
2488     case MCCFIInstruction::OpRestoreState:
2489     case MCCFIInstruction::OpGnuArgsSize:
2490       // do not affect CFI state
2491       break;
2492     }
2493   }
2494 
2495 public:
2496   /// Advance state reading FDE CFI instructions up to State number
2497   void advanceTo(int32_t State) {
2498     for (int32_t I = CurState, E = State; I != E; ++I) {
2499       const MCCFIInstruction &Instr = FDE[I];
2500       if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2501         update(Instr, I);
2502         continue;
2503       }
2504       // If restore state instruction, fetch the equivalent CFIs that have
2505       // the same effect of this restore. This is used to ensure remember-
2506       // restore pairs are completely removed.
2507       auto Iter = FrameRestoreEquivalents.find(I);
2508       if (Iter == FrameRestoreEquivalents.end())
2509         continue;
2510       for (int32_t RuleNumber : Iter->second)
2511         update(FDE[RuleNumber], RuleNumber);
2512     }
2513 
2514     assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2515             CFARule != UNKNOWN) &&
2516            "CIE did not define default CFA?");
2517 
2518     CurState = State;
2519   }
2520 
2521   /// Interpret all CIE and FDE instructions up until CFI State number and
2522   /// populate this snapshot
2523   CFISnapshot(
2524       const BinaryFunction::CFIInstrMapType &CIE,
2525       const BinaryFunction::CFIInstrMapType &FDE,
2526       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2527       int32_t State)
2528       : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2529     CFAReg = UNKNOWN;
2530     CFAOffset = UNKNOWN;
2531     CFARule = UNKNOWN;
2532     CurState = 0;
2533 
2534     for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2535       const MCCFIInstruction &Instr = CIE[I];
2536       update(Instr, -I);
2537     }
2538 
2539     advanceTo(State);
2540   }
2541 };
2542 
2543 /// A CFI snapshot with the capability of checking if incremental additions to
2544 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2545 /// back-to-back that are doing the same state change, or to avoid emitting a
2546 /// CFI at all when the state at that point would not be modified after that CFI
2547 struct CFISnapshotDiff : public CFISnapshot {
2548   bool RestoredCFAReg{false};
2549   bool RestoredCFAOffset{false};
2550   DenseMap<int32_t, bool> RestoredRegs;
2551 
2552   CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2553 
2554   CFISnapshotDiff(
2555       const BinaryFunction::CFIInstrMapType &CIE,
2556       const BinaryFunction::CFIInstrMapType &FDE,
2557       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2558       int32_t State)
2559       : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2560 
2561   /// Return true if applying Instr to this state is redundant and can be
2562   /// dismissed.
2563   bool isRedundant(const MCCFIInstruction &Instr) {
2564     switch (Instr.getOperation()) {
2565     case MCCFIInstruction::OpSameValue:
2566     case MCCFIInstruction::OpRelOffset:
2567     case MCCFIInstruction::OpOffset:
2568     case MCCFIInstruction::OpRestore:
2569     case MCCFIInstruction::OpUndefined:
2570     case MCCFIInstruction::OpRegister:
2571     case MCCFIInstruction::OpEscape: {
2572       uint32_t Reg;
2573       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2574         Reg = Instr.getRegister();
2575       } else {
2576         Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2577         // Handle DW_CFA_def_cfa_expression
2578         if (!R) {
2579           if (RestoredCFAReg && RestoredCFAOffset)
2580             return true;
2581           RestoredCFAReg = true;
2582           RestoredCFAOffset = true;
2583           return false;
2584         }
2585         Reg = *R;
2586       }
2587       if (RestoredRegs[Reg])
2588         return true;
2589       RestoredRegs[Reg] = true;
2590       const int32_t CurRegRule =
2591           RegRule.find(Reg) != RegRule.end() ? RegRule[Reg] : UNKNOWN;
2592       if (CurRegRule == UNKNOWN) {
2593         if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2594             Instr.getOperation() == MCCFIInstruction::OpSameValue)
2595           return true;
2596         return false;
2597       }
2598       const MCCFIInstruction &LastDef =
2599           CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2600       return LastDef == Instr;
2601     }
2602     case MCCFIInstruction::OpDefCfaRegister:
2603       if (RestoredCFAReg)
2604         return true;
2605       RestoredCFAReg = true;
2606       return CFAReg == Instr.getRegister();
2607     case MCCFIInstruction::OpDefCfaOffset:
2608       if (RestoredCFAOffset)
2609         return true;
2610       RestoredCFAOffset = true;
2611       return CFAOffset == Instr.getOffset();
2612     case MCCFIInstruction::OpDefCfa:
2613       if (RestoredCFAReg && RestoredCFAOffset)
2614         return true;
2615       RestoredCFAReg = true;
2616       RestoredCFAOffset = true;
2617       return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2618     case MCCFIInstruction::OpAdjustCfaOffset:
2619     case MCCFIInstruction::OpWindowSave:
2620     case MCCFIInstruction::OpNegateRAState:
2621     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2622       llvm_unreachable("unsupported CFI opcode");
2623       return false;
2624     case MCCFIInstruction::OpRememberState:
2625     case MCCFIInstruction::OpRestoreState:
2626     case MCCFIInstruction::OpGnuArgsSize:
2627       // do not affect CFI state
2628       return true;
2629     }
2630     return false;
2631   }
2632 };
2633 
2634 } // end anonymous namespace
2635 
2636 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2637                                      BinaryBasicBlock *InBB,
2638                                      BinaryBasicBlock::iterator InsertIt) {
2639   if (FromState == ToState)
2640     return true;
2641   assert(FromState < ToState && "can only replay CFIs forward");
2642 
2643   CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2644                           FrameRestoreEquivalents, FromState);
2645 
2646   std::vector<uint32_t> NewCFIs;
2647   for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2648     MCCFIInstruction *Instr = &FrameInstructions[CurState];
2649     if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2650       auto Iter = FrameRestoreEquivalents.find(CurState);
2651       assert(Iter != FrameRestoreEquivalents.end());
2652       NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2653       // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2654       // so we might as well fall-through here.
2655     }
2656     NewCFIs.push_back(CurState);
2657     continue;
2658   }
2659 
2660   // Replay instructions while avoiding duplicates
2661   for (auto I = NewCFIs.rbegin(), E = NewCFIs.rend(); I != E; ++I) {
2662     if (CFIDiff.isRedundant(FrameInstructions[*I]))
2663       continue;
2664     InsertIt = addCFIPseudo(InBB, InsertIt, *I);
2665   }
2666 
2667   return true;
2668 }
2669 
2670 SmallVector<int32_t, 4>
2671 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2672                                BinaryBasicBlock *InBB,
2673                                BinaryBasicBlock::iterator &InsertIt) {
2674   SmallVector<int32_t, 4> NewStates;
2675 
2676   CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2677                          FrameRestoreEquivalents, ToState);
2678   CFISnapshotDiff FromCFITable(ToCFITable);
2679   FromCFITable.advanceTo(FromState);
2680 
2681   auto undoStateDefCfa = [&]() {
2682     if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2683       FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2684           nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2685       if (FromCFITable.isRedundant(FrameInstructions.back())) {
2686         FrameInstructions.pop_back();
2687         return;
2688       }
2689       NewStates.push_back(FrameInstructions.size() - 1);
2690       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2691       ++InsertIt;
2692     } else if (ToCFITable.CFARule < 0) {
2693       if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2694         return;
2695       NewStates.push_back(FrameInstructions.size());
2696       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2697       ++InsertIt;
2698       FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2699     } else if (!FromCFITable.isRedundant(
2700                    FrameInstructions[ToCFITable.CFARule])) {
2701       NewStates.push_back(ToCFITable.CFARule);
2702       InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2703       ++InsertIt;
2704     }
2705   };
2706 
2707   auto undoState = [&](const MCCFIInstruction &Instr) {
2708     switch (Instr.getOperation()) {
2709     case MCCFIInstruction::OpRememberState:
2710     case MCCFIInstruction::OpRestoreState:
2711       break;
2712     case MCCFIInstruction::OpSameValue:
2713     case MCCFIInstruction::OpRelOffset:
2714     case MCCFIInstruction::OpOffset:
2715     case MCCFIInstruction::OpRestore:
2716     case MCCFIInstruction::OpUndefined:
2717     case MCCFIInstruction::OpEscape:
2718     case MCCFIInstruction::OpRegister: {
2719       uint32_t Reg;
2720       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2721         Reg = Instr.getRegister();
2722       } else {
2723         Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2724         // Handle DW_CFA_def_cfa_expression
2725         if (!R) {
2726           undoStateDefCfa();
2727           return;
2728         }
2729         Reg = *R;
2730       }
2731 
2732       if (ToCFITable.RegRule.find(Reg) == ToCFITable.RegRule.end()) {
2733         FrameInstructions.emplace_back(
2734             MCCFIInstruction::createRestore(nullptr, Reg));
2735         if (FromCFITable.isRedundant(FrameInstructions.back())) {
2736           FrameInstructions.pop_back();
2737           break;
2738         }
2739         NewStates.push_back(FrameInstructions.size() - 1);
2740         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2741         ++InsertIt;
2742         break;
2743       }
2744       const int32_t Rule = ToCFITable.RegRule[Reg];
2745       if (Rule < 0) {
2746         if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2747           break;
2748         NewStates.push_back(FrameInstructions.size());
2749         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2750         ++InsertIt;
2751         FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2752         break;
2753       }
2754       if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2755         break;
2756       NewStates.push_back(Rule);
2757       InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2758       ++InsertIt;
2759       break;
2760     }
2761     case MCCFIInstruction::OpDefCfaRegister:
2762     case MCCFIInstruction::OpDefCfaOffset:
2763     case MCCFIInstruction::OpDefCfa:
2764       undoStateDefCfa();
2765       break;
2766     case MCCFIInstruction::OpAdjustCfaOffset:
2767     case MCCFIInstruction::OpWindowSave:
2768     case MCCFIInstruction::OpNegateRAState:
2769     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2770       llvm_unreachable("unsupported CFI opcode");
2771       break;
2772     case MCCFIInstruction::OpGnuArgsSize:
2773       // do not affect CFI state
2774       break;
2775     }
2776   };
2777 
2778   // Undo all modifications from ToState to FromState
2779   for (int32_t I = ToState, E = FromState; I != E; ++I) {
2780     const MCCFIInstruction &Instr = FrameInstructions[I];
2781     if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2782       undoState(Instr);
2783       continue;
2784     }
2785     auto Iter = FrameRestoreEquivalents.find(I);
2786     if (Iter == FrameRestoreEquivalents.end())
2787       continue;
2788     for (int32_t State : Iter->second)
2789       undoState(FrameInstructions[State]);
2790   }
2791 
2792   return NewStates;
2793 }
2794 
2795 void BinaryFunction::normalizeCFIState() {
2796   // Reordering blocks with remember-restore state instructions can be specially
2797   // tricky. When rewriting the CFI, we omit remember-restore state instructions
2798   // entirely. For restore state, we build a map expanding each restore to the
2799   // equivalent unwindCFIState sequence required at that point to achieve the
2800   // same effect of the restore. All remember state are then just ignored.
2801   std::stack<int32_t> Stack;
2802   for (BinaryBasicBlock *CurBB : BasicBlocksLayout) {
2803     for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2804       if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2805         if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2806           Stack.push(II->getOperand(0).getImm());
2807           continue;
2808         }
2809         if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2810           const int32_t RememberState = Stack.top();
2811           const int32_t CurState = II->getOperand(0).getImm();
2812           FrameRestoreEquivalents[CurState] =
2813               unwindCFIState(CurState, RememberState, CurBB, II);
2814           Stack.pop();
2815         }
2816       }
2817     }
2818   }
2819 }
2820 
2821 bool BinaryFunction::finalizeCFIState() {
2822   LLVM_DEBUG(
2823       dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2824   LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2825                     << ": ");
2826 
2827   int32_t State = 0;
2828   bool SeenCold = false;
2829   const char *Sep = "";
2830   (void)Sep;
2831   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
2832     const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2833 
2834     // Hot-cold border: check if this is the first BB to be allocated in a cold
2835     // region (with a different FDE). If yes, we need to reset the CFI state.
2836     if (!SeenCold && BB->isCold()) {
2837       State = 0;
2838       SeenCold = true;
2839     }
2840 
2841     // We need to recover the correct state if it doesn't match expected
2842     // state at BB entry point.
2843     if (BB->getCFIState() < State) {
2844       // In this case, State is currently higher than what this BB expect it
2845       // to be. To solve this, we need to insert CFI instructions to undo
2846       // the effect of all CFI from BB's state to current State.
2847       auto InsertIt = BB->begin();
2848       unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2849     } else if (BB->getCFIState() > State) {
2850       // If BB's CFI state is greater than State, it means we are behind in the
2851       // state. Just emit all instructions to reach this state at the
2852       // beginning of this BB. If this sequence of instructions involve
2853       // remember state or restore state, bail out.
2854       if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2855         return false;
2856     }
2857 
2858     State = CFIStateAtExit;
2859     LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2860   }
2861   LLVM_DEBUG(dbgs() << "\n");
2862 
2863   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
2864     for (auto II = BB->begin(); II != BB->end();) {
2865       const MCCFIInstruction *CFI = getCFIFor(*II);
2866       if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2867                   CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2868         II = BB->eraseInstruction(II);
2869       } else {
2870         ++II;
2871       }
2872     }
2873   }
2874 
2875   return true;
2876 }
2877 
2878 bool BinaryFunction::requiresAddressTranslation() const {
2879   return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2880 }
2881 
2882 uint64_t BinaryFunction::getInstructionCount() const {
2883   uint64_t Count = 0;
2884   for (BinaryBasicBlock *const &Block : BasicBlocksLayout)
2885     Count += Block->getNumNonPseudos();
2886   return Count;
2887 }
2888 
2889 bool BinaryFunction::hasLayoutChanged() const { return ModifiedLayout; }
2890 
2891 uint64_t BinaryFunction::getEditDistance() const {
2892   return ComputeEditDistance<BinaryBasicBlock *>(BasicBlocksPreviousLayout,
2893                                                  BasicBlocksLayout);
2894 }
2895 
2896 void BinaryFunction::clearDisasmState() {
2897   clearList(Instructions);
2898   clearList(IgnoredBranches);
2899   clearList(TakenBranches);
2900   clearList(InterproceduralReferences);
2901 
2902   if (BC.HasRelocations) {
2903     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2904       BC.UndefinedSymbols.insert(LI.second);
2905     if (FunctionEndLabel)
2906       BC.UndefinedSymbols.insert(FunctionEndLabel);
2907   }
2908 }
2909 
2910 void BinaryFunction::setTrapOnEntry() {
2911   clearDisasmState();
2912 
2913   auto addTrapAtOffset = [&](uint64_t Offset) {
2914     MCInst TrapInstr;
2915     BC.MIB->createTrap(TrapInstr);
2916     addInstruction(Offset, std::move(TrapInstr));
2917   };
2918 
2919   addTrapAtOffset(0);
2920   for (const std::pair<const uint32_t, MCSymbol *> &KV : getLabels())
2921     if (getSecondaryEntryPointSymbol(KV.second))
2922       addTrapAtOffset(KV.first);
2923 
2924   TrapsOnEntry = true;
2925 }
2926 
2927 void BinaryFunction::setIgnored() {
2928   if (opts::processAllFunctions()) {
2929     // We can accept ignored functions before they've been disassembled.
2930     // In that case, they would still get disassembled and emited, but not
2931     // optimized.
2932     assert(CurrentState == State::Empty &&
2933            "cannot ignore non-empty functions in current mode");
2934     IsIgnored = true;
2935     return;
2936   }
2937 
2938   clearDisasmState();
2939 
2940   // Clear CFG state too.
2941   if (hasCFG()) {
2942     releaseCFG();
2943 
2944     for (BinaryBasicBlock *BB : BasicBlocks)
2945       delete BB;
2946     clearList(BasicBlocks);
2947 
2948     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2949       delete BB;
2950     clearList(DeletedBasicBlocks);
2951 
2952     clearList(BasicBlocksLayout);
2953     clearList(BasicBlocksPreviousLayout);
2954   }
2955 
2956   CurrentState = State::Empty;
2957 
2958   IsIgnored = true;
2959   IsSimple = false;
2960   LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2961 }
2962 
2963 void BinaryFunction::duplicateConstantIslands() {
2964   assert(Islands && "function expected to have constant islands");
2965 
2966   for (BinaryBasicBlock *BB : layout()) {
2967     if (!BB->isCold())
2968       continue;
2969 
2970     for (MCInst &Inst : *BB) {
2971       int OpNum = 0;
2972       for (MCOperand &Operand : Inst) {
2973         if (!Operand.isExpr()) {
2974           ++OpNum;
2975           continue;
2976         }
2977         const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2978         // Check if this is an island symbol
2979         if (!Islands->Symbols.count(Symbol) &&
2980             !Islands->ProxySymbols.count(Symbol))
2981           continue;
2982 
2983         // Create cold symbol, if missing
2984         auto ISym = Islands->ColdSymbols.find(Symbol);
2985         MCSymbol *ColdSymbol;
2986         if (ISym != Islands->ColdSymbols.end()) {
2987           ColdSymbol = ISym->second;
2988         } else {
2989           ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
2990           Islands->ColdSymbols[Symbol] = ColdSymbol;
2991           // Check if this is a proxy island symbol and update owner proxy map
2992           if (Islands->ProxySymbols.count(Symbol)) {
2993             BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
2994             auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
2995             Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
2996           }
2997         }
2998 
2999         // Update instruction reference
3000         Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
3001             Inst,
3002             MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
3003                                     *BC.Ctx),
3004             *BC.Ctx, 0));
3005         ++OpNum;
3006       }
3007     }
3008   }
3009 }
3010 
3011 namespace {
3012 
3013 #ifndef MAX_PATH
3014 #define MAX_PATH 255
3015 #endif
3016 
3017 std::string constructFilename(std::string Filename, std::string Annotation,
3018                               std::string Suffix) {
3019   std::replace(Filename.begin(), Filename.end(), '/', '-');
3020   if (!Annotation.empty())
3021     Annotation.insert(0, "-");
3022   if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
3023     assert(Suffix.size() + Annotation.size() <= MAX_PATH);
3024     if (opts::Verbosity >= 1) {
3025       errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
3026              << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
3027     }
3028     Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
3029   }
3030   Filename += Annotation;
3031   Filename += Suffix;
3032   return Filename;
3033 }
3034 
3035 std::string formatEscapes(const std::string &Str) {
3036   std::string Result;
3037   for (unsigned I = 0; I < Str.size(); ++I) {
3038     char C = Str[I];
3039     switch (C) {
3040     case '\n':
3041       Result += "&#13;";
3042       break;
3043     case '"':
3044       break;
3045     default:
3046       Result += C;
3047       break;
3048     }
3049   }
3050   return Result;
3051 }
3052 
3053 } // namespace
3054 
3055 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3056   OS << "strict digraph \"" << getPrintName() << "\" {\n";
3057   uint64_t Offset = Address;
3058   for (BinaryBasicBlock *BB : BasicBlocks) {
3059     auto LayoutPos =
3060         std::find(BasicBlocksLayout.begin(), BasicBlocksLayout.end(), BB);
3061     unsigned Layout = LayoutPos - BasicBlocksLayout.begin();
3062     const char *ColdStr = BB->isCold() ? " (cold)" : "";
3063     OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u:CFI:%u)\"]\n",
3064                  BB->getName().data(), BB->getName().data(), ColdStr,
3065                  (BB->ExecutionCount != BinaryBasicBlock::COUNT_NO_PROFILE
3066                       ? BB->ExecutionCount
3067                       : 0),
3068                  BB->getOffset(), getIndex(BB), Layout, BB->getCFIState());
3069     OS << format("\"%s\" [shape=box]\n", BB->getName().data());
3070     if (opts::DotToolTipCode) {
3071       std::string Str;
3072       raw_string_ostream CS(Str);
3073       Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this);
3074       const std::string Code = formatEscapes(CS.str());
3075       OS << format("\"%s\" [tooltip=\"%s\"]\n", BB->getName().data(),
3076                    Code.c_str());
3077     }
3078 
3079     // analyzeBranch is just used to get the names of the branch
3080     // opcodes.
3081     const MCSymbol *TBB = nullptr;
3082     const MCSymbol *FBB = nullptr;
3083     MCInst *CondBranch = nullptr;
3084     MCInst *UncondBranch = nullptr;
3085     const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3086 
3087     const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3088     const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3089 
3090     auto BI = BB->branch_info_begin();
3091     for (BinaryBasicBlock *Succ : BB->successors()) {
3092       std::string Branch;
3093       if (Success) {
3094         if (Succ == BB->getConditionalSuccessor(true)) {
3095           Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3096                                     CondBranch->getOpcode()))
3097                               : "TB";
3098         } else if (Succ == BB->getConditionalSuccessor(false)) {
3099           Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3100                                       UncondBranch->getOpcode()))
3101                                 : "FB";
3102         } else {
3103           Branch = "FT";
3104         }
3105       }
3106       if (IsJumpTable)
3107         Branch = "JT";
3108       OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3109                    Succ->getName().data(), Branch.c_str());
3110 
3111       if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3112           BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3113         OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3114       } else if (ExecutionCount != COUNT_NO_PROFILE &&
3115                  BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3116         OS << "\\n(IC:" << BI->Count << ")";
3117       }
3118       OS << "\"]\n";
3119 
3120       ++BI;
3121     }
3122     for (BinaryBasicBlock *LP : BB->landing_pads()) {
3123       OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3124                    BB->getName().data(), LP->getName().data());
3125     }
3126   }
3127   OS << "}\n";
3128 }
3129 
3130 void BinaryFunction::viewGraph() const {
3131   SmallString<MAX_PATH> Filename;
3132   if (std::error_code EC =
3133           sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3134     errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3135            << " bolt-cfg-XXXXX.dot temporary file.\n";
3136     return;
3137   }
3138   dumpGraphToFile(std::string(Filename));
3139   if (DisplayGraph(Filename))
3140     errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3141   if (std::error_code EC = sys::fs::remove(Filename)) {
3142     errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3143            << Filename << "\n";
3144   }
3145 }
3146 
3147 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3148   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3149   outs() << "BOLT-DEBUG: Dumping CFG to " << Filename << "\n";
3150   dumpGraphToFile(Filename);
3151 }
3152 
3153 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3154   std::error_code EC;
3155   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3156   if (EC) {
3157     if (opts::Verbosity >= 1) {
3158       errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3159              << Filename << " for output.\n";
3160     }
3161     return;
3162   }
3163   dumpGraph(of);
3164 }
3165 
3166 bool BinaryFunction::validateCFG() const {
3167   bool Valid = true;
3168   for (BinaryBasicBlock *BB : BasicBlocks)
3169     Valid &= BB->validateSuccessorInvariants();
3170 
3171   if (!Valid)
3172     return Valid;
3173 
3174   // Make sure all blocks in CFG are valid.
3175   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3176     if (!BB->isValid()) {
3177       errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3178              << " detected in:\n";
3179       this->dump();
3180       return false;
3181     }
3182     return true;
3183   };
3184   for (const BinaryBasicBlock *BB : BasicBlocks) {
3185     if (!validateBlock(BB, "block"))
3186       return false;
3187     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3188       if (!validateBlock(PredBB, "predecessor"))
3189         return false;
3190     for (const BinaryBasicBlock *SuccBB : BB->successors())
3191       if (!validateBlock(SuccBB, "successor"))
3192         return false;
3193     for (const BinaryBasicBlock *LP : BB->landing_pads())
3194       if (!validateBlock(LP, "landing pad"))
3195         return false;
3196     for (const BinaryBasicBlock *Thrower : BB->throwers())
3197       if (!validateBlock(Thrower, "thrower"))
3198         return false;
3199   }
3200 
3201   for (const BinaryBasicBlock *BB : BasicBlocks) {
3202     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3203     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3204       if (BBLandingPads.count(LP)) {
3205         errs() << "BOLT-ERROR: duplicate landing pad detected in"
3206                << BB->getName() << " in function " << *this << '\n';
3207         return false;
3208       }
3209       BBLandingPads.insert(LP);
3210     }
3211 
3212     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3213     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3214       if (BBThrowers.count(Thrower)) {
3215         errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3216                << " in function " << *this << '\n';
3217         return false;
3218       }
3219       BBThrowers.insert(Thrower);
3220     }
3221 
3222     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3223       if (std::find(LPBlock->throw_begin(), LPBlock->throw_end(), BB) ==
3224           LPBlock->throw_end()) {
3225         errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3226                << ": " << BB->getName() << " is in LandingPads but not in "
3227                << LPBlock->getName() << " Throwers\n";
3228         return false;
3229       }
3230     }
3231     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3232       if (std::find(Thrower->lp_begin(), Thrower->lp_end(), BB) ==
3233           Thrower->lp_end()) {
3234         errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3235                << ": " << BB->getName() << " is in Throwers list but not in "
3236                << Thrower->getName() << " LandingPads\n";
3237         return false;
3238       }
3239     }
3240   }
3241 
3242   return Valid;
3243 }
3244 
3245 void BinaryFunction::fixBranches() {
3246   auto &MIB = BC.MIB;
3247   MCContext *Ctx = BC.Ctx.get();
3248 
3249   for (unsigned I = 0, E = BasicBlocksLayout.size(); I != E; ++I) {
3250     BinaryBasicBlock *BB = BasicBlocksLayout[I];
3251     const MCSymbol *TBB = nullptr;
3252     const MCSymbol *FBB = nullptr;
3253     MCInst *CondBranch = nullptr;
3254     MCInst *UncondBranch = nullptr;
3255     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3256       continue;
3257 
3258     // We will create unconditional branch with correct destination if needed.
3259     if (UncondBranch)
3260       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3261 
3262     // Basic block that follows the current one in the final layout.
3263     const BinaryBasicBlock *NextBB = nullptr;
3264     if (I + 1 != E && BB->isCold() == BasicBlocksLayout[I + 1]->isCold())
3265       NextBB = BasicBlocksLayout[I + 1];
3266 
3267     if (BB->succ_size() == 1) {
3268       // __builtin_unreachable() could create a conditional branch that
3269       // falls-through into the next function - hence the block will have only
3270       // one valid successor. Since behaviour is undefined - we replace
3271       // the conditional branch with an unconditional if required.
3272       if (CondBranch)
3273         BB->eraseInstruction(BB->findInstruction(CondBranch));
3274       if (BB->getSuccessor() == NextBB)
3275         continue;
3276       BB->addBranchInstruction(BB->getSuccessor());
3277     } else if (BB->succ_size() == 2) {
3278       assert(CondBranch && "conditional branch expected");
3279       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3280       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3281       // Check whether we support reversing this branch direction
3282       const bool IsSupported =
3283           !MIB->isUnsupportedBranch(CondBranch->getOpcode());
3284       if (NextBB && NextBB == TSuccessor && IsSupported) {
3285         std::swap(TSuccessor, FSuccessor);
3286         {
3287           auto L = BC.scopeLock();
3288           MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3289         }
3290         BB->swapConditionalSuccessors();
3291       } else {
3292         auto L = BC.scopeLock();
3293         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3294       }
3295       if (TSuccessor == FSuccessor)
3296         BB->removeDuplicateConditionalSuccessor(CondBranch);
3297       if (!NextBB ||
3298           ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3299         // If one of the branches is guaranteed to be "long" while the other
3300         // could be "short", then prioritize short for "taken". This will
3301         // generate a sequence 1 byte shorter on x86.
3302         if (IsSupported && BC.isX86() &&
3303             TSuccessor->isCold() != FSuccessor->isCold() &&
3304             BB->isCold() != TSuccessor->isCold()) {
3305           std::swap(TSuccessor, FSuccessor);
3306           {
3307             auto L = BC.scopeLock();
3308             MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3309                                         Ctx);
3310           }
3311           BB->swapConditionalSuccessors();
3312         }
3313         BB->addBranchInstruction(FSuccessor);
3314       }
3315     }
3316     // Cases where the number of successors is 0 (block ends with a
3317     // terminator) or more than 2 (switch table) don't require branch
3318     // instruction adjustments.
3319   }
3320   assert((!isSimple() || validateCFG()) &&
3321          "Invalid CFG detected after fixing branches");
3322 }
3323 
3324 void BinaryFunction::propagateGnuArgsSizeInfo(
3325     MCPlusBuilder::AllocatorIdTy AllocId) {
3326   assert(CurrentState == State::Disassembled && "unexpected function state");
3327 
3328   if (!hasEHRanges() || !usesGnuArgsSize())
3329     return;
3330 
3331   // The current value of DW_CFA_GNU_args_size affects all following
3332   // invoke instructions until the next CFI overrides it.
3333   // It is important to iterate basic blocks in the original order when
3334   // assigning the value.
3335   uint64_t CurrentGnuArgsSize = 0;
3336   for (BinaryBasicBlock *BB : BasicBlocks) {
3337     for (auto II = BB->begin(); II != BB->end();) {
3338       MCInst &Instr = *II;
3339       if (BC.MIB->isCFI(Instr)) {
3340         const MCCFIInstruction *CFI = getCFIFor(Instr);
3341         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3342           CurrentGnuArgsSize = CFI->getOffset();
3343           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3344           // during the final code emission. The information is embedded
3345           // inside call instructions.
3346           II = BB->erasePseudoInstruction(II);
3347           continue;
3348         }
3349       } else if (BC.MIB->isInvoke(Instr)) {
3350         // Add the value of GNU_args_size as an extra operand to invokes.
3351         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3352       }
3353       ++II;
3354     }
3355   }
3356 }
3357 
3358 void BinaryFunction::postProcessBranches() {
3359   if (!isSimple())
3360     return;
3361   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
3362     auto LastInstrRI = BB->getLastNonPseudo();
3363     if (BB->succ_size() == 1) {
3364       if (LastInstrRI != BB->rend() &&
3365           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3366         // __builtin_unreachable() could create a conditional branch that
3367         // falls-through into the next function - hence the block will have only
3368         // one valid successor. Such behaviour is undefined and thus we remove
3369         // the conditional branch while leaving a valid successor.
3370         BB->eraseInstruction(std::prev(LastInstrRI.base()));
3371         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3372                           << BB->getName() << " in function " << *this << '\n');
3373       }
3374     } else if (BB->succ_size() == 0) {
3375       // Ignore unreachable basic blocks.
3376       if (BB->pred_size() == 0 || BB->isLandingPad())
3377         continue;
3378 
3379       // If it's the basic block that does not end up with a terminator - we
3380       // insert a return instruction unless it's a call instruction.
3381       if (LastInstrRI == BB->rend()) {
3382         LLVM_DEBUG(
3383             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3384                    << BB->getName() << " in function " << *this << '\n');
3385         continue;
3386       }
3387       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3388           !BC.MIB->isCall(*LastInstrRI)) {
3389         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3390                           << BB->getName() << " in function " << *this << '\n');
3391         MCInst ReturnInstr;
3392         BC.MIB->createReturn(ReturnInstr);
3393         BB->addInstruction(ReturnInstr);
3394       }
3395     }
3396   }
3397   assert(validateCFG() && "invalid CFG");
3398 }
3399 
3400 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3401   assert(Offset && "cannot add primary entry point");
3402   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3403 
3404   const uint64_t EntryPointAddress = getAddress() + Offset;
3405   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3406 
3407   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3408   if (EntrySymbol)
3409     return EntrySymbol;
3410 
3411   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3412     EntrySymbol = EntryBD->getSymbol();
3413   } else {
3414     EntrySymbol = BC.getOrCreateGlobalSymbol(
3415         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3416   }
3417   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3418 
3419   BC.setSymbolToFunctionMap(EntrySymbol, this);
3420 
3421   return EntrySymbol;
3422 }
3423 
3424 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3425   assert(CurrentState == State::CFG &&
3426          "basic block can be added as an entry only in a function with CFG");
3427 
3428   if (&BB == BasicBlocks.front())
3429     return getSymbol();
3430 
3431   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3432   if (EntrySymbol)
3433     return EntrySymbol;
3434 
3435   EntrySymbol =
3436       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3437 
3438   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3439 
3440   BC.setSymbolToFunctionMap(EntrySymbol, this);
3441 
3442   return EntrySymbol;
3443 }
3444 
3445 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3446   if (EntryID == 0)
3447     return getSymbol();
3448 
3449   if (!isMultiEntry())
3450     return nullptr;
3451 
3452   uint64_t NumEntries = 0;
3453   if (hasCFG()) {
3454     for (BinaryBasicBlock *BB : BasicBlocks) {
3455       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3456       if (!EntrySymbol)
3457         continue;
3458       if (NumEntries == EntryID)
3459         return EntrySymbol;
3460       ++NumEntries;
3461     }
3462   } else {
3463     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3464       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3465       if (!EntrySymbol)
3466         continue;
3467       if (NumEntries == EntryID)
3468         return EntrySymbol;
3469       ++NumEntries;
3470     }
3471   }
3472 
3473   return nullptr;
3474 }
3475 
3476 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3477   if (!isMultiEntry())
3478     return 0;
3479 
3480   for (const MCSymbol *FunctionSymbol : getSymbols())
3481     if (FunctionSymbol == Symbol)
3482       return 0;
3483 
3484   // Check all secondary entries available as either basic blocks or lables.
3485   uint64_t NumEntries = 0;
3486   for (const BinaryBasicBlock *BB : BasicBlocks) {
3487     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3488     if (!EntrySymbol)
3489       continue;
3490     if (EntrySymbol == Symbol)
3491       return NumEntries;
3492     ++NumEntries;
3493   }
3494   NumEntries = 0;
3495   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3496     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3497     if (!EntrySymbol)
3498       continue;
3499     if (EntrySymbol == Symbol)
3500       return NumEntries;
3501     ++NumEntries;
3502   }
3503 
3504   llvm_unreachable("symbol not found");
3505 }
3506 
3507 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3508   bool Status = Callback(0, getSymbol());
3509   if (!isMultiEntry())
3510     return Status;
3511 
3512   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3513     if (!Status)
3514       break;
3515 
3516     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3517     if (!EntrySymbol)
3518       continue;
3519 
3520     Status = Callback(KV.first, EntrySymbol);
3521   }
3522 
3523   return Status;
3524 }
3525 
3526 BinaryFunction::BasicBlockOrderType BinaryFunction::dfs() const {
3527   BasicBlockOrderType DFS;
3528   unsigned Index = 0;
3529   std::stack<BinaryBasicBlock *> Stack;
3530 
3531   // Push entry points to the stack in reverse order.
3532   //
3533   // NB: we rely on the original order of entries to match.
3534   for (auto BBI = layout_rbegin(); BBI != layout_rend(); ++BBI) {
3535     BinaryBasicBlock *BB = *BBI;
3536     if (isEntryPoint(*BB))
3537       Stack.push(BB);
3538     BB->setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3539   }
3540 
3541   while (!Stack.empty()) {
3542     BinaryBasicBlock *BB = Stack.top();
3543     Stack.pop();
3544 
3545     if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3546       continue;
3547 
3548     BB->setLayoutIndex(Index++);
3549     DFS.push_back(BB);
3550 
3551     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3552       Stack.push(SuccBB);
3553     }
3554 
3555     const MCSymbol *TBB = nullptr;
3556     const MCSymbol *FBB = nullptr;
3557     MCInst *CondBranch = nullptr;
3558     MCInst *UncondBranch = nullptr;
3559     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3560         BB->succ_size() == 2) {
3561       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3562               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3563         Stack.push(BB->getConditionalSuccessor(true));
3564         Stack.push(BB->getConditionalSuccessor(false));
3565       } else {
3566         Stack.push(BB->getConditionalSuccessor(false));
3567         Stack.push(BB->getConditionalSuccessor(true));
3568       }
3569     } else {
3570       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3571         Stack.push(SuccBB);
3572       }
3573     }
3574   }
3575 
3576   return DFS;
3577 }
3578 
3579 size_t BinaryFunction::computeHash(bool UseDFS,
3580                                    OperandHashFuncTy OperandHashFunc) const {
3581   if (size() == 0)
3582     return 0;
3583 
3584   assert(hasCFG() && "function is expected to have CFG");
3585 
3586   const BasicBlockOrderType &Order = UseDFS ? dfs() : BasicBlocksLayout;
3587 
3588   // The hash is computed by creating a string of all instruction opcodes and
3589   // possibly their operands and then hashing that string with std::hash.
3590   std::string HashString;
3591   for (const BinaryBasicBlock *BB : Order) {
3592     for (const MCInst &Inst : *BB) {
3593       unsigned Opcode = Inst.getOpcode();
3594 
3595       if (BC.MIB->isPseudo(Inst))
3596         continue;
3597 
3598       // Ignore unconditional jumps since we check CFG consistency by processing
3599       // basic blocks in order and do not rely on branches to be in-sync with
3600       // CFG. Note that we still use condition code of conditional jumps.
3601       if (BC.MIB->isUnconditionalBranch(Inst))
3602         continue;
3603 
3604       if (Opcode == 0)
3605         HashString.push_back(0);
3606 
3607       while (Opcode) {
3608         uint8_t LSB = Opcode & 0xff;
3609         HashString.push_back(LSB);
3610         Opcode = Opcode >> 8;
3611       }
3612 
3613       for (const MCOperand &Op : MCPlus::primeOperands(Inst))
3614         HashString.append(OperandHashFunc(Op));
3615     }
3616   }
3617 
3618   return Hash = std::hash<std::string>{}(HashString);
3619 }
3620 
3621 void BinaryFunction::insertBasicBlocks(
3622     BinaryBasicBlock *Start,
3623     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3624     const bool UpdateLayout, const bool UpdateCFIState,
3625     const bool RecomputeLandingPads) {
3626   const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3627   const size_t NumNewBlocks = NewBBs.size();
3628 
3629   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3630                      nullptr);
3631 
3632   int64_t I = StartIndex + 1;
3633   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3634     assert(!BasicBlocks[I]);
3635     BasicBlocks[I++] = BB.release();
3636   }
3637 
3638   if (RecomputeLandingPads)
3639     recomputeLandingPads();
3640   else
3641     updateBBIndices(0);
3642 
3643   if (UpdateLayout)
3644     updateLayout(Start, NumNewBlocks);
3645 
3646   if (UpdateCFIState)
3647     updateCFIState(Start, NumNewBlocks);
3648 }
3649 
3650 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3651     BinaryFunction::iterator StartBB,
3652     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3653     const bool UpdateLayout, const bool UpdateCFIState,
3654     const bool RecomputeLandingPads) {
3655   const unsigned StartIndex = getIndex(&*StartBB);
3656   const size_t NumNewBlocks = NewBBs.size();
3657 
3658   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3659                      nullptr);
3660   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3661 
3662   unsigned I = StartIndex + 1;
3663   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3664     assert(!BasicBlocks[I]);
3665     BasicBlocks[I++] = BB.release();
3666   }
3667 
3668   if (RecomputeLandingPads)
3669     recomputeLandingPads();
3670   else
3671     updateBBIndices(0);
3672 
3673   if (UpdateLayout)
3674     updateLayout(*std::prev(RetIter), NumNewBlocks);
3675 
3676   if (UpdateCFIState)
3677     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3678 
3679   return RetIter;
3680 }
3681 
3682 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3683   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3684     BasicBlocks[I]->Index = I;
3685 }
3686 
3687 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3688                                     const unsigned NumNewBlocks) {
3689   const int32_t CFIState = Start->getCFIStateAtExit();
3690   const unsigned StartIndex = getIndex(Start) + 1;
3691   for (unsigned I = 0; I < NumNewBlocks; ++I)
3692     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3693 }
3694 
3695 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3696                                   const unsigned NumNewBlocks) {
3697   // If start not provided insert new blocks at the beginning
3698   if (!Start) {
3699     BasicBlocksLayout.insert(layout_begin(), BasicBlocks.begin(),
3700                              BasicBlocks.begin() + NumNewBlocks);
3701     updateLayoutIndices();
3702     return;
3703   }
3704 
3705   // Insert new blocks in the layout immediately after Start.
3706   auto Pos = std::find(layout_begin(), layout_end(), Start);
3707   assert(Pos != layout_end());
3708   BasicBlockListType::iterator Begin =
3709       std::next(BasicBlocks.begin(), getIndex(Start) + 1);
3710   BasicBlockListType::iterator End =
3711       std::next(BasicBlocks.begin(), getIndex(Start) + NumNewBlocks + 1);
3712   BasicBlocksLayout.insert(Pos + 1, Begin, End);
3713   updateLayoutIndices();
3714 }
3715 
3716 bool BinaryFunction::checkForAmbiguousJumpTables() {
3717   SmallSet<uint64_t, 4> JumpTables;
3718   for (BinaryBasicBlock *&BB : BasicBlocks) {
3719     for (MCInst &Inst : *BB) {
3720       if (!BC.MIB->isIndirectBranch(Inst))
3721         continue;
3722       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3723       if (!JTAddress)
3724         continue;
3725       // This address can be inside another jump table, but we only consider
3726       // it ambiguous when the same start address is used, not the same JT
3727       // object.
3728       if (!JumpTables.count(JTAddress)) {
3729         JumpTables.insert(JTAddress);
3730         continue;
3731       }
3732       return true;
3733     }
3734   }
3735   return false;
3736 }
3737 
3738 void BinaryFunction::disambiguateJumpTables(
3739     MCPlusBuilder::AllocatorIdTy AllocId) {
3740   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3741   SmallPtrSet<JumpTable *, 4> JumpTables;
3742   for (BinaryBasicBlock *&BB : BasicBlocks) {
3743     for (MCInst &Inst : *BB) {
3744       if (!BC.MIB->isIndirectBranch(Inst))
3745         continue;
3746       JumpTable *JT = getJumpTable(Inst);
3747       if (!JT)
3748         continue;
3749       auto Iter = JumpTables.find(JT);
3750       if (Iter == JumpTables.end()) {
3751         JumpTables.insert(JT);
3752         continue;
3753       }
3754       // This instruction is an indirect jump using a jump table, but it is
3755       // using the same jump table of another jump. Try all our tricks to
3756       // extract the jump table symbol and make it point to a new, duplicated JT
3757       MCPhysReg BaseReg1;
3758       uint64_t Scale;
3759       const MCSymbol *Target;
3760       // In case we match if our first matcher, first instruction is the one to
3761       // patch
3762       MCInst *JTLoadInst = &Inst;
3763       // Try a standard indirect jump matcher, scale 8
3764       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3765           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3766                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3767                               /*Offset=*/BC.MIB->matchSymbol(Target));
3768       if (!IndJmpMatcher->match(
3769               *BC.MRI, *BC.MIB,
3770               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3771           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3772         MCPhysReg BaseReg2;
3773         uint64_t Offset;
3774         // Standard JT matching failed. Trying now:
3775         //     movq  "jt.2397/1"(,%rax,8), %rax
3776         //     jmpq  *%rax
3777         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3778             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3779                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3780                               /*Offset=*/BC.MIB->matchSymbol(Target));
3781         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3782         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3783             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3784         if (!IndJmpMatcher2->match(
3785                 *BC.MRI, *BC.MIB,
3786                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3787             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3788           // JT matching failed. Trying now:
3789           // PIC-style matcher, scale 4
3790           //    addq    %rdx, %rsi
3791           //    addq    %rdx, %rdi
3792           //    leaq    DATAat0x402450(%rip), %r11
3793           //    movslq  (%r11,%rdx,4), %rcx
3794           //    addq    %r11, %rcx
3795           //    jmpq    *%rcx # JUMPTABLE @0x402450
3796           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3797               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3798                   BC.MIB->matchReg(BaseReg1),
3799                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3800                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3801                                     BC.MIB->matchImm(Offset))));
3802           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3803               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3804           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3805           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3806               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3807                                                    BC.MIB->matchAnyOperand()));
3808           if (!PICIndJmpMatcher->match(
3809                   *BC.MRI, *BC.MIB,
3810                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3811               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3812               !PICBaseAddrMatcher->match(
3813                   *BC.MRI, *BC.MIB,
3814                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3815             llvm_unreachable("Failed to extract jump table base");
3816             continue;
3817           }
3818           // Matched PIC, identify the instruction with the reference to the JT
3819           JTLoadInst = LEAMatcher->CurInst;
3820         } else {
3821           // Matched non-PIC
3822           JTLoadInst = LoadMatcher->CurInst;
3823         }
3824       }
3825 
3826       uint64_t NewJumpTableID = 0;
3827       const MCSymbol *NewJTLabel;
3828       std::tie(NewJumpTableID, NewJTLabel) =
3829           BC.duplicateJumpTable(*this, JT, Target);
3830       {
3831         auto L = BC.scopeLock();
3832         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3833       }
3834       // We use a unique ID with the high bit set as address for this "injected"
3835       // jump table (not originally in the input binary).
3836       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3837     }
3838   }
3839 }
3840 
3841 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3842                                              BinaryBasicBlock *OldDest,
3843                                              BinaryBasicBlock *NewDest) {
3844   MCInst *Instr = BB->getLastNonPseudoInstr();
3845   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3846     return false;
3847   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3848   assert(JTAddress && "Invalid jump table address");
3849   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3850   assert(JT && "No jump table structure for this indirect branch");
3851   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3852                                         NewDest->getLabel());
3853   (void)Patched;
3854   assert(Patched && "Invalid entry to be replaced in jump table");
3855   return true;
3856 }
3857 
3858 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3859                                             BinaryBasicBlock *To) {
3860   // Create intermediate BB
3861   MCSymbol *Tmp;
3862   {
3863     auto L = BC.scopeLock();
3864     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3865   }
3866   // Link new BBs to the original input offset of the From BB, so we can map
3867   // samples recorded in new BBs back to the original BB seem in the input
3868   // binary (if using BAT)
3869   std::unique_ptr<BinaryBasicBlock> NewBB =
3870       createBasicBlock(From->getInputOffset(), Tmp);
3871   BinaryBasicBlock *NewBBPtr = NewBB.get();
3872 
3873   // Update "From" BB
3874   auto I = From->succ_begin();
3875   auto BI = From->branch_info_begin();
3876   for (; I != From->succ_end(); ++I) {
3877     if (*I == To)
3878       break;
3879     ++BI;
3880   }
3881   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3882   uint64_t OrigCount = BI->Count;
3883   uint64_t OrigMispreds = BI->MispredictedCount;
3884   replaceJumpTableEntryIn(From, To, NewBBPtr);
3885   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3886 
3887   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3888   NewBB->setExecutionCount(OrigCount);
3889   NewBB->setIsCold(From->isCold());
3890 
3891   // Update CFI and BB layout with new intermediate BB
3892   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3893   NewBBs.emplace_back(std::move(NewBB));
3894   insertBasicBlocks(From, std::move(NewBBs), true, true,
3895                     /*RecomputeLandingPads=*/false);
3896   return NewBBPtr;
3897 }
3898 
3899 void BinaryFunction::deleteConservativeEdges() {
3900   // Our goal is to aggressively remove edges from the CFG that we believe are
3901   // wrong. This is used for instrumentation, where it is safe to remove
3902   // fallthrough edges because we won't reorder blocks.
3903   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3904     BinaryBasicBlock *BB = *I;
3905     if (BB->succ_size() != 1 || BB->size() == 0)
3906       continue;
3907 
3908     auto NextBB = std::next(I);
3909     MCInst *Last = BB->getLastNonPseudoInstr();
3910     // Fallthrough is a landing pad? Delete this edge (as long as we don't
3911     // have a direct jump to it)
3912     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3913         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3914       BB->removeAllSuccessors();
3915       continue;
3916     }
3917 
3918     // Look for suspicious calls at the end of BB where gcc may optimize it and
3919     // remove the jump to the epilogue when it knows the call won't return.
3920     if (!Last || !BC.MIB->isCall(*Last))
3921       continue;
3922 
3923     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3924     if (!CalleeSymbol)
3925       continue;
3926 
3927     StringRef CalleeName = CalleeSymbol->getName();
3928     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3929         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3930         CalleeName != "abort@PLT")
3931       continue;
3932 
3933     BB->removeAllSuccessors();
3934   }
3935 }
3936 
3937 bool BinaryFunction::isDataMarker(const SymbolRef &Symbol,
3938                                   uint64_t SymbolSize) const {
3939   // For aarch64, the ABI defines mapping symbols so we identify data in the
3940   // code section (see IHI0056B). $d identifies a symbol starting data contents.
3941   if (BC.isAArch64() && Symbol.getType() &&
3942       cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && SymbolSize == 0 &&
3943       Symbol.getName() &&
3944       (cantFail(Symbol.getName()) == "$d" ||
3945        cantFail(Symbol.getName()).startswith("$d.")))
3946     return true;
3947   return false;
3948 }
3949 
3950 bool BinaryFunction::isCodeMarker(const SymbolRef &Symbol,
3951                                   uint64_t SymbolSize) const {
3952   // For aarch64, the ABI defines mapping symbols so we identify data in the
3953   // code section (see IHI0056B). $x identifies a symbol starting code or the
3954   // end of a data chunk inside code.
3955   if (BC.isAArch64() && Symbol.getType() &&
3956       cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && SymbolSize == 0 &&
3957       Symbol.getName() &&
3958       (cantFail(Symbol.getName()) == "$x" ||
3959        cantFail(Symbol.getName()).startswith("$x.")))
3960     return true;
3961   return false;
3962 }
3963 
3964 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3965                                           uint64_t SymbolSize) const {
3966   // If this symbol is in a different section from the one where the
3967   // function symbol is, don't consider it as valid.
3968   if (!getOriginSection()->containsAddress(
3969           cantFail(Symbol.getAddress(), "cannot get symbol address")))
3970     return false;
3971 
3972   // Some symbols are tolerated inside function bodies, others are not.
3973   // The real function boundaries may not be known at this point.
3974   if (isDataMarker(Symbol, SymbolSize) || isCodeMarker(Symbol, SymbolSize))
3975     return true;
3976 
3977   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3978   // function.
3979   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3980     return true;
3981 
3982   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3983     return false;
3984 
3985   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3986     return false;
3987 
3988   return true;
3989 }
3990 
3991 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3992   if (getKnownExecutionCount() == 0 || Count == 0)
3993     return;
3994 
3995   if (ExecutionCount < Count)
3996     Count = ExecutionCount;
3997 
3998   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
3999   if (AdjustmentRatio < 0.0)
4000     AdjustmentRatio = 0.0;
4001 
4002   for (BinaryBasicBlock *&BB : layout())
4003     BB->adjustExecutionCount(AdjustmentRatio);
4004 
4005   ExecutionCount -= Count;
4006 }
4007 
4008 BinaryFunction::~BinaryFunction() {
4009   for (BinaryBasicBlock *BB : BasicBlocks)
4010     delete BB;
4011   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
4012     delete BB;
4013 }
4014 
4015 void BinaryFunction::calculateLoopInfo() {
4016   // Discover loops.
4017   BinaryDominatorTree DomTree;
4018   DomTree.recalculate(*this);
4019   BLI.reset(new BinaryLoopInfo());
4020   BLI->analyze(DomTree);
4021 
4022   // Traverse discovered loops and add depth and profile information.
4023   std::stack<BinaryLoop *> St;
4024   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
4025     St.push(*I);
4026     ++BLI->OuterLoops;
4027   }
4028 
4029   while (!St.empty()) {
4030     BinaryLoop *L = St.top();
4031     St.pop();
4032     ++BLI->TotalLoops;
4033     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
4034 
4035     // Add nested loops in the stack.
4036     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4037       St.push(*I);
4038 
4039     // Skip if no valid profile is found.
4040     if (!hasValidProfile()) {
4041       L->EntryCount = COUNT_NO_PROFILE;
4042       L->ExitCount = COUNT_NO_PROFILE;
4043       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
4044       continue;
4045     }
4046 
4047     // Compute back edge count.
4048     SmallVector<BinaryBasicBlock *, 1> Latches;
4049     L->getLoopLatches(Latches);
4050 
4051     for (BinaryBasicBlock *Latch : Latches) {
4052       auto BI = Latch->branch_info_begin();
4053       for (BinaryBasicBlock *Succ : Latch->successors()) {
4054         if (Succ == L->getHeader()) {
4055           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4056                  "profile data not found");
4057           L->TotalBackEdgeCount += BI->Count;
4058         }
4059         ++BI;
4060       }
4061     }
4062 
4063     // Compute entry count.
4064     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4065 
4066     // Compute exit count.
4067     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4068     L->getExitEdges(ExitEdges);
4069     for (BinaryLoop::Edge &Exit : ExitEdges) {
4070       const BinaryBasicBlock *Exiting = Exit.first;
4071       const BinaryBasicBlock *ExitTarget = Exit.second;
4072       auto BI = Exiting->branch_info_begin();
4073       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4074         if (Succ == ExitTarget) {
4075           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4076                  "profile data not found");
4077           L->ExitCount += BI->Count;
4078         }
4079         ++BI;
4080       }
4081     }
4082   }
4083 }
4084 
4085 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4086   if (!isEmitted()) {
4087     assert(!isInjected() && "injected function should be emitted");
4088     setOutputAddress(getAddress());
4089     setOutputSize(getSize());
4090     return;
4091   }
4092 
4093   const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4094   ErrorOr<BinarySection &> ColdSection = getColdCodeSection();
4095   const uint64_t ColdBaseAddress =
4096       isSplit() ? ColdSection->getOutputAddress() : 0;
4097   if (BC.HasRelocations || isInjected()) {
4098     const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4099     const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4100     setOutputAddress(BaseAddress + StartOffset);
4101     setOutputSize(EndOffset - StartOffset);
4102     if (hasConstantIsland()) {
4103       const uint64_t DataOffset =
4104           Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4105       setOutputDataAddress(BaseAddress + DataOffset);
4106     }
4107     if (isSplit()) {
4108       const MCSymbol *ColdStartSymbol = getColdSymbol();
4109       assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4110              "split function should have defined cold symbol");
4111       const MCSymbol *ColdEndSymbol = getFunctionColdEndLabel();
4112       assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4113              "split function should have defined cold end symbol");
4114       const uint64_t ColdStartOffset = Layout.getSymbolOffset(*ColdStartSymbol);
4115       const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4116       cold().setAddress(ColdBaseAddress + ColdStartOffset);
4117       cold().setImageSize(ColdEndOffset - ColdStartOffset);
4118       if (hasConstantIsland()) {
4119         const uint64_t DataOffset =
4120             Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4121         setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4122       }
4123     }
4124   } else {
4125     setOutputAddress(getAddress());
4126     setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4127   }
4128 
4129   // Update basic block output ranges for the debug info, if we have
4130   // secondary entry points in the symbol table to update or if writing BAT.
4131   if (!opts::UpdateDebugSections && !isMultiEntry() &&
4132       !requiresAddressTranslation())
4133     return;
4134 
4135   // Output ranges should match the input if the body hasn't changed.
4136   if (!isSimple() && !BC.HasRelocations)
4137     return;
4138 
4139   // AArch64 may have functions that only contains a constant island (no code).
4140   if (layout_begin() == layout_end())
4141     return;
4142 
4143   BinaryBasicBlock *PrevBB = nullptr;
4144   for (auto BBI = layout_begin(), BBE = layout_end(); BBI != BBE; ++BBI) {
4145     BinaryBasicBlock *BB = *BBI;
4146     assert(BB->getLabel()->isDefined() && "symbol should be defined");
4147     const uint64_t BBBaseAddress = BB->isCold() ? ColdBaseAddress : BaseAddress;
4148     if (!BC.HasRelocations) {
4149       if (BB->isCold()) {
4150         assert(BBBaseAddress == cold().getAddress());
4151       } else {
4152         assert(BBBaseAddress == getOutputAddress());
4153       }
4154     }
4155     const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4156     const uint64_t BBAddress = BBBaseAddress + BBOffset;
4157     BB->setOutputStartAddress(BBAddress);
4158 
4159     if (PrevBB) {
4160       uint64_t PrevBBEndAddress = BBAddress;
4161       if (BB->isCold() != PrevBB->isCold())
4162         PrevBBEndAddress = getOutputAddress() + getOutputSize();
4163       PrevBB->setOutputEndAddress(PrevBBEndAddress);
4164     }
4165     PrevBB = BB;
4166 
4167     BB->updateOutputValues(Layout);
4168   }
4169   PrevBB->setOutputEndAddress(PrevBB->isCold()
4170                                   ? cold().getAddress() + cold().getImageSize()
4171                                   : getOutputAddress() + getOutputSize());
4172 }
4173 
4174 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4175   DebugAddressRangesVector OutputRanges;
4176 
4177   if (isFolded())
4178     return OutputRanges;
4179 
4180   if (IsFragment)
4181     return OutputRanges;
4182 
4183   OutputRanges.emplace_back(getOutputAddress(),
4184                             getOutputAddress() + getOutputSize());
4185   if (isSplit()) {
4186     assert(isEmitted() && "split function should be emitted");
4187     OutputRanges.emplace_back(cold().getAddress(),
4188                               cold().getAddress() + cold().getImageSize());
4189   }
4190 
4191   if (isSimple())
4192     return OutputRanges;
4193 
4194   for (BinaryFunction *Frag : Fragments) {
4195     assert(!Frag->isSimple() &&
4196            "fragment of non-simple function should also be non-simple");
4197     OutputRanges.emplace_back(Frag->getOutputAddress(),
4198                               Frag->getOutputAddress() + Frag->getOutputSize());
4199   }
4200 
4201   return OutputRanges;
4202 }
4203 
4204 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4205   if (isFolded())
4206     return 0;
4207 
4208   // If the function hasn't changed return the same address.
4209   if (!isEmitted())
4210     return Address;
4211 
4212   if (Address < getAddress())
4213     return 0;
4214 
4215   // Check if the address is associated with an instruction that is tracked
4216   // by address translation.
4217   auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4218   if (KV != InputOffsetToAddressMap.end())
4219     return KV->second;
4220 
4221   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4222   //        intact. Instead we can use pseudo instructions and/or annotations.
4223   const uint64_t Offset = Address - getAddress();
4224   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4225   if (!BB) {
4226     // Special case for address immediately past the end of the function.
4227     if (Offset == getSize())
4228       return getOutputAddress() + getOutputSize();
4229 
4230     return 0;
4231   }
4232 
4233   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4234                   BB->getOutputAddressRange().second);
4235 }
4236 
4237 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4238     const DWARFAddressRangesVector &InputRanges) const {
4239   DebugAddressRangesVector OutputRanges;
4240 
4241   if (isFolded())
4242     return OutputRanges;
4243 
4244   // If the function hasn't changed return the same ranges.
4245   if (!isEmitted()) {
4246     OutputRanges.resize(InputRanges.size());
4247     std::transform(InputRanges.begin(), InputRanges.end(), OutputRanges.begin(),
4248                    [](const DWARFAddressRange &Range) {
4249                      return DebugAddressRange(Range.LowPC, Range.HighPC);
4250                    });
4251     return OutputRanges;
4252   }
4253 
4254   // Even though we will merge ranges in a post-processing pass, we attempt to
4255   // merge them in a main processing loop as it improves the processing time.
4256   uint64_t PrevEndAddress = 0;
4257   for (const DWARFAddressRange &Range : InputRanges) {
4258     if (!containsAddress(Range.LowPC)) {
4259       LLVM_DEBUG(
4260           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4261                  << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4262                  << Twine::utohexstr(Range.HighPC) << "]\n");
4263       PrevEndAddress = 0;
4264       continue;
4265     }
4266     uint64_t InputOffset = Range.LowPC - getAddress();
4267     const uint64_t InputEndOffset =
4268         std::min(Range.HighPC - getAddress(), getSize());
4269 
4270     auto BBI = std::upper_bound(
4271         BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
4272         BasicBlockOffset(InputOffset, nullptr), CompareBasicBlockOffsets());
4273     --BBI;
4274     do {
4275       const BinaryBasicBlock *BB = BBI->second;
4276       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4277         LLVM_DEBUG(
4278             dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4279                    << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4280                    << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4281         PrevEndAddress = 0;
4282         break;
4283       }
4284 
4285       // Skip the range if the block was deleted.
4286       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4287         const uint64_t StartAddress =
4288             OutputStart + InputOffset - BB->getOffset();
4289         uint64_t EndAddress = BB->getOutputAddressRange().second;
4290         if (InputEndOffset < BB->getEndOffset())
4291           EndAddress = StartAddress + InputEndOffset - InputOffset;
4292 
4293         if (StartAddress == PrevEndAddress) {
4294           OutputRanges.back().HighPC =
4295               std::max(OutputRanges.back().HighPC, EndAddress);
4296         } else {
4297           OutputRanges.emplace_back(StartAddress,
4298                                     std::max(StartAddress, EndAddress));
4299         }
4300         PrevEndAddress = OutputRanges.back().HighPC;
4301       }
4302 
4303       InputOffset = BB->getEndOffset();
4304       ++BBI;
4305     } while (InputOffset < InputEndOffset);
4306   }
4307 
4308   // Post-processing pass to sort and merge ranges.
4309   std::sort(OutputRanges.begin(), OutputRanges.end());
4310   DebugAddressRangesVector MergedRanges;
4311   PrevEndAddress = 0;
4312   for (const DebugAddressRange &Range : OutputRanges) {
4313     if (Range.LowPC <= PrevEndAddress) {
4314       MergedRanges.back().HighPC =
4315           std::max(MergedRanges.back().HighPC, Range.HighPC);
4316     } else {
4317       MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4318     }
4319     PrevEndAddress = MergedRanges.back().HighPC;
4320   }
4321 
4322   return MergedRanges;
4323 }
4324 
4325 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4326   if (CurrentState == State::Disassembled) {
4327     auto II = Instructions.find(Offset);
4328     return (II == Instructions.end()) ? nullptr : &II->second;
4329   } else if (CurrentState == State::CFG) {
4330     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4331     if (!BB)
4332       return nullptr;
4333 
4334     for (MCInst &Inst : *BB) {
4335       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4336       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4337         return &Inst;
4338     }
4339 
4340     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4341       const uint32_t Size =
4342           BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4343       if (BB->getEndOffset() - Offset == Size)
4344         return LastInstr;
4345     }
4346 
4347     return nullptr;
4348   } else {
4349     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4350   }
4351 }
4352 
4353 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4354     const DebugLocationsVector &InputLL) const {
4355   DebugLocationsVector OutputLL;
4356 
4357   if (isFolded())
4358     return OutputLL;
4359 
4360   // If the function hasn't changed - there's nothing to update.
4361   if (!isEmitted())
4362     return InputLL;
4363 
4364   uint64_t PrevEndAddress = 0;
4365   SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4366   for (const DebugLocationEntry &Entry : InputLL) {
4367     const uint64_t Start = Entry.LowPC;
4368     const uint64_t End = Entry.HighPC;
4369     if (!containsAddress(Start)) {
4370       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4371                            "for "
4372                         << *this << " : [0x" << Twine::utohexstr(Start)
4373                         << ", 0x" << Twine::utohexstr(End) << "]\n");
4374       continue;
4375     }
4376     uint64_t InputOffset = Start - getAddress();
4377     const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4378     auto BBI = std::upper_bound(
4379         BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
4380         BasicBlockOffset(InputOffset, nullptr), CompareBasicBlockOffsets());
4381     --BBI;
4382     do {
4383       const BinaryBasicBlock *BB = BBI->second;
4384       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4385         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4386                              "for "
4387                           << *this << " : [0x" << Twine::utohexstr(Start)
4388                           << ", 0x" << Twine::utohexstr(End) << "]\n");
4389         PrevEndAddress = 0;
4390         break;
4391       }
4392 
4393       // Skip the range if the block was deleted.
4394       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4395         const uint64_t StartAddress =
4396             OutputStart + InputOffset - BB->getOffset();
4397         uint64_t EndAddress = BB->getOutputAddressRange().second;
4398         if (InputEndOffset < BB->getEndOffset())
4399           EndAddress = StartAddress + InputEndOffset - InputOffset;
4400 
4401         if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4402           OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4403         } else {
4404           OutputLL.emplace_back(DebugLocationEntry{
4405               StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4406         }
4407         PrevEndAddress = OutputLL.back().HighPC;
4408         PrevExpr = &OutputLL.back().Expr;
4409       }
4410 
4411       ++BBI;
4412       InputOffset = BB->getEndOffset();
4413     } while (InputOffset < InputEndOffset);
4414   }
4415 
4416   // Sort and merge adjacent entries with identical location.
4417   std::stable_sort(
4418       OutputLL.begin(), OutputLL.end(),
4419       [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4420         return A.LowPC < B.LowPC;
4421       });
4422   DebugLocationsVector MergedLL;
4423   PrevEndAddress = 0;
4424   PrevExpr = nullptr;
4425   for (const DebugLocationEntry &Entry : OutputLL) {
4426     if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4427       MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4428     } else {
4429       const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4430       const uint64_t End = std::max(Begin, Entry.HighPC);
4431       MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4432     }
4433     PrevEndAddress = MergedLL.back().HighPC;
4434     PrevExpr = &MergedLL.back().Expr;
4435   }
4436 
4437   return MergedLL;
4438 }
4439 
4440 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4441   OS << "Loop Info for Function \"" << *this << "\"";
4442   if (hasValidProfile())
4443     OS << " (count: " << getExecutionCount() << ")";
4444   OS << "\n";
4445 
4446   std::stack<BinaryLoop *> St;
4447   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I)
4448     St.push(*I);
4449   while (!St.empty()) {
4450     BinaryLoop *L = St.top();
4451     St.pop();
4452 
4453     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4454       St.push(*I);
4455 
4456     if (!hasValidProfile())
4457       continue;
4458 
4459     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4460        << " loop header: " << L->getHeader()->getName();
4461     OS << "\n";
4462     OS << "Loop basic blocks: ";
4463     const char *Sep = "";
4464     for (auto BI = L->block_begin(), BE = L->block_end(); BI != BE; ++BI) {
4465       OS << Sep << (*BI)->getName();
4466       Sep = ", ";
4467     }
4468     OS << "\n";
4469     if (hasValidProfile()) {
4470       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4471       OS << "Loop entry count: " << L->EntryCount << "\n";
4472       OS << "Loop exit count: " << L->ExitCount << "\n";
4473       if (L->EntryCount > 0) {
4474         OS << "Average iters per entry: "
4475            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4476            << "\n";
4477       }
4478     }
4479     OS << "----\n";
4480   }
4481 
4482   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4483   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4484   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4485 }
4486 
4487 bool BinaryFunction::isAArch64Veneer() const {
4488   if (BasicBlocks.size() != 1)
4489     return false;
4490 
4491   BinaryBasicBlock &BB = **BasicBlocks.begin();
4492   if (BB.size() != 3)
4493     return false;
4494 
4495   for (MCInst &Inst : BB)
4496     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4497       return false;
4498 
4499   return true;
4500 }
4501 
4502 } // namespace bolt
4503 } // namespace llvm
4504