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