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