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