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