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