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