xref: /llvm-project/bolt/lib/Core/BinaryFunction.cpp (revision 35efe1d806358df6e45dde8218a143138dd8f0a8)
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 * BB->getNumNonPseudos();
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   if (!opts::shouldPrint(*this))
3101     return;
3102 
3103   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3104   if (opts::Verbosity >= 1)
3105     outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n";
3106   dumpGraphToFile(Filename);
3107 }
3108 
3109 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3110   std::error_code EC;
3111   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3112   if (EC) {
3113     if (opts::Verbosity >= 1) {
3114       errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3115              << Filename << " for output.\n";
3116     }
3117     return;
3118   }
3119   dumpGraph(of);
3120 }
3121 
3122 bool BinaryFunction::validateCFG() const {
3123   bool Valid = true;
3124   for (BinaryBasicBlock *BB : BasicBlocks)
3125     Valid &= BB->validateSuccessorInvariants();
3126 
3127   if (!Valid)
3128     return Valid;
3129 
3130   // Make sure all blocks in CFG are valid.
3131   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3132     if (!BB->isValid()) {
3133       errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3134              << " detected in:\n";
3135       this->dump();
3136       return false;
3137     }
3138     return true;
3139   };
3140   for (const BinaryBasicBlock *BB : BasicBlocks) {
3141     if (!validateBlock(BB, "block"))
3142       return false;
3143     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3144       if (!validateBlock(PredBB, "predecessor"))
3145         return false;
3146     for (const BinaryBasicBlock *SuccBB : BB->successors())
3147       if (!validateBlock(SuccBB, "successor"))
3148         return false;
3149     for (const BinaryBasicBlock *LP : BB->landing_pads())
3150       if (!validateBlock(LP, "landing pad"))
3151         return false;
3152     for (const BinaryBasicBlock *Thrower : BB->throwers())
3153       if (!validateBlock(Thrower, "thrower"))
3154         return false;
3155   }
3156 
3157   for (const BinaryBasicBlock *BB : BasicBlocks) {
3158     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3159     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3160       if (BBLandingPads.count(LP)) {
3161         errs() << "BOLT-ERROR: duplicate landing pad detected in"
3162                << BB->getName() << " in function " << *this << '\n';
3163         return false;
3164       }
3165       BBLandingPads.insert(LP);
3166     }
3167 
3168     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3169     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3170       if (BBThrowers.count(Thrower)) {
3171         errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3172                << " in function " << *this << '\n';
3173         return false;
3174       }
3175       BBThrowers.insert(Thrower);
3176     }
3177 
3178     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3179       if (!llvm::is_contained(LPBlock->throwers(), BB)) {
3180         errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3181                << ": " << BB->getName() << " is in LandingPads but not in "
3182                << LPBlock->getName() << " Throwers\n";
3183         return false;
3184       }
3185     }
3186     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3187       if (!llvm::is_contained(Thrower->landing_pads(), BB)) {
3188         errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3189                << ": " << BB->getName() << " is in Throwers list but not in "
3190                << Thrower->getName() << " LandingPads\n";
3191         return false;
3192       }
3193     }
3194   }
3195 
3196   return Valid;
3197 }
3198 
3199 void BinaryFunction::fixBranches() {
3200   auto &MIB = BC.MIB;
3201   MCContext *Ctx = BC.Ctx.get();
3202 
3203   for (unsigned I = 0, E = BasicBlocksLayout.size(); I != E; ++I) {
3204     BinaryBasicBlock *BB = BasicBlocksLayout[I];
3205     const MCSymbol *TBB = nullptr;
3206     const MCSymbol *FBB = nullptr;
3207     MCInst *CondBranch = nullptr;
3208     MCInst *UncondBranch = nullptr;
3209     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3210       continue;
3211 
3212     // We will create unconditional branch with correct destination if needed.
3213     if (UncondBranch)
3214       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3215 
3216     // Basic block that follows the current one in the final layout.
3217     const BinaryBasicBlock *NextBB = nullptr;
3218     if (I + 1 != E && BB->isCold() == BasicBlocksLayout[I + 1]->isCold())
3219       NextBB = BasicBlocksLayout[I + 1];
3220 
3221     if (BB->succ_size() == 1) {
3222       // __builtin_unreachable() could create a conditional branch that
3223       // falls-through into the next function - hence the block will have only
3224       // one valid successor. Since behaviour is undefined - we replace
3225       // the conditional branch with an unconditional if required.
3226       if (CondBranch)
3227         BB->eraseInstruction(BB->findInstruction(CondBranch));
3228       if (BB->getSuccessor() == NextBB)
3229         continue;
3230       BB->addBranchInstruction(BB->getSuccessor());
3231     } else if (BB->succ_size() == 2) {
3232       assert(CondBranch && "conditional branch expected");
3233       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3234       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3235       // Check whether we support reversing this branch direction
3236       const bool IsSupported =
3237           !MIB->isUnsupportedBranch(CondBranch->getOpcode());
3238       if (NextBB && NextBB == TSuccessor && IsSupported) {
3239         std::swap(TSuccessor, FSuccessor);
3240         {
3241           auto L = BC.scopeLock();
3242           MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3243         }
3244         BB->swapConditionalSuccessors();
3245       } else {
3246         auto L = BC.scopeLock();
3247         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3248       }
3249       if (TSuccessor == FSuccessor)
3250         BB->removeDuplicateConditionalSuccessor(CondBranch);
3251       if (!NextBB ||
3252           ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3253         // If one of the branches is guaranteed to be "long" while the other
3254         // could be "short", then prioritize short for "taken". This will
3255         // generate a sequence 1 byte shorter on x86.
3256         if (IsSupported && BC.isX86() &&
3257             TSuccessor->isCold() != FSuccessor->isCold() &&
3258             BB->isCold() != TSuccessor->isCold()) {
3259           std::swap(TSuccessor, FSuccessor);
3260           {
3261             auto L = BC.scopeLock();
3262             MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3263                                         Ctx);
3264           }
3265           BB->swapConditionalSuccessors();
3266         }
3267         BB->addBranchInstruction(FSuccessor);
3268       }
3269     }
3270     // Cases where the number of successors is 0 (block ends with a
3271     // terminator) or more than 2 (switch table) don't require branch
3272     // instruction adjustments.
3273   }
3274   assert((!isSimple() || validateCFG()) &&
3275          "Invalid CFG detected after fixing branches");
3276 }
3277 
3278 void BinaryFunction::propagateGnuArgsSizeInfo(
3279     MCPlusBuilder::AllocatorIdTy AllocId) {
3280   assert(CurrentState == State::Disassembled && "unexpected function state");
3281 
3282   if (!hasEHRanges() || !usesGnuArgsSize())
3283     return;
3284 
3285   // The current value of DW_CFA_GNU_args_size affects all following
3286   // invoke instructions until the next CFI overrides it.
3287   // It is important to iterate basic blocks in the original order when
3288   // assigning the value.
3289   uint64_t CurrentGnuArgsSize = 0;
3290   for (BinaryBasicBlock *BB : BasicBlocks) {
3291     for (auto II = BB->begin(); II != BB->end();) {
3292       MCInst &Instr = *II;
3293       if (BC.MIB->isCFI(Instr)) {
3294         const MCCFIInstruction *CFI = getCFIFor(Instr);
3295         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3296           CurrentGnuArgsSize = CFI->getOffset();
3297           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3298           // during the final code emission. The information is embedded
3299           // inside call instructions.
3300           II = BB->erasePseudoInstruction(II);
3301           continue;
3302         }
3303       } else if (BC.MIB->isInvoke(Instr)) {
3304         // Add the value of GNU_args_size as an extra operand to invokes.
3305         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3306       }
3307       ++II;
3308     }
3309   }
3310 }
3311 
3312 void BinaryFunction::postProcessBranches() {
3313   if (!isSimple())
3314     return;
3315   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
3316     auto LastInstrRI = BB->getLastNonPseudo();
3317     if (BB->succ_size() == 1) {
3318       if (LastInstrRI != BB->rend() &&
3319           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3320         // __builtin_unreachable() could create a conditional branch that
3321         // falls-through into the next function - hence the block will have only
3322         // one valid successor. Such behaviour is undefined and thus we remove
3323         // the conditional branch while leaving a valid successor.
3324         BB->eraseInstruction(std::prev(LastInstrRI.base()));
3325         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3326                           << BB->getName() << " in function " << *this << '\n');
3327       }
3328     } else if (BB->succ_size() == 0) {
3329       // Ignore unreachable basic blocks.
3330       if (BB->pred_size() == 0 || BB->isLandingPad())
3331         continue;
3332 
3333       // If it's the basic block that does not end up with a terminator - we
3334       // insert a return instruction unless it's a call instruction.
3335       if (LastInstrRI == BB->rend()) {
3336         LLVM_DEBUG(
3337             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3338                    << BB->getName() << " in function " << *this << '\n');
3339         continue;
3340       }
3341       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3342           !BC.MIB->isCall(*LastInstrRI)) {
3343         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3344                           << BB->getName() << " in function " << *this << '\n');
3345         MCInst ReturnInstr;
3346         BC.MIB->createReturn(ReturnInstr);
3347         BB->addInstruction(ReturnInstr);
3348       }
3349     }
3350   }
3351   assert(validateCFG() && "invalid CFG");
3352 }
3353 
3354 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3355   assert(Offset && "cannot add primary entry point");
3356   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3357 
3358   const uint64_t EntryPointAddress = getAddress() + Offset;
3359   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3360 
3361   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3362   if (EntrySymbol)
3363     return EntrySymbol;
3364 
3365   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3366     EntrySymbol = EntryBD->getSymbol();
3367   } else {
3368     EntrySymbol = BC.getOrCreateGlobalSymbol(
3369         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3370   }
3371   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3372 
3373   BC.setSymbolToFunctionMap(EntrySymbol, this);
3374 
3375   return EntrySymbol;
3376 }
3377 
3378 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3379   assert(CurrentState == State::CFG &&
3380          "basic block can be added as an entry only in a function with CFG");
3381 
3382   if (&BB == BasicBlocks.front())
3383     return getSymbol();
3384 
3385   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3386   if (EntrySymbol)
3387     return EntrySymbol;
3388 
3389   EntrySymbol =
3390       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3391 
3392   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3393 
3394   BC.setSymbolToFunctionMap(EntrySymbol, this);
3395 
3396   return EntrySymbol;
3397 }
3398 
3399 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3400   if (EntryID == 0)
3401     return getSymbol();
3402 
3403   if (!isMultiEntry())
3404     return nullptr;
3405 
3406   uint64_t NumEntries = 0;
3407   if (hasCFG()) {
3408     for (BinaryBasicBlock *BB : BasicBlocks) {
3409       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3410       if (!EntrySymbol)
3411         continue;
3412       if (NumEntries == EntryID)
3413         return EntrySymbol;
3414       ++NumEntries;
3415     }
3416   } else {
3417     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3418       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3419       if (!EntrySymbol)
3420         continue;
3421       if (NumEntries == EntryID)
3422         return EntrySymbol;
3423       ++NumEntries;
3424     }
3425   }
3426 
3427   return nullptr;
3428 }
3429 
3430 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3431   if (!isMultiEntry())
3432     return 0;
3433 
3434   for (const MCSymbol *FunctionSymbol : getSymbols())
3435     if (FunctionSymbol == Symbol)
3436       return 0;
3437 
3438   // Check all secondary entries available as either basic blocks or lables.
3439   uint64_t NumEntries = 0;
3440   for (const BinaryBasicBlock *BB : BasicBlocks) {
3441     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3442     if (!EntrySymbol)
3443       continue;
3444     if (EntrySymbol == Symbol)
3445       return NumEntries;
3446     ++NumEntries;
3447   }
3448   NumEntries = 0;
3449   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3450     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3451     if (!EntrySymbol)
3452       continue;
3453     if (EntrySymbol == Symbol)
3454       return NumEntries;
3455     ++NumEntries;
3456   }
3457 
3458   llvm_unreachable("symbol not found");
3459 }
3460 
3461 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3462   bool Status = Callback(0, getSymbol());
3463   if (!isMultiEntry())
3464     return Status;
3465 
3466   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3467     if (!Status)
3468       break;
3469 
3470     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3471     if (!EntrySymbol)
3472       continue;
3473 
3474     Status = Callback(KV.first, EntrySymbol);
3475   }
3476 
3477   return Status;
3478 }
3479 
3480 BinaryFunction::BasicBlockOrderType BinaryFunction::dfs() const {
3481   BasicBlockOrderType DFS;
3482   unsigned Index = 0;
3483   std::stack<BinaryBasicBlock *> Stack;
3484 
3485   // Push entry points to the stack in reverse order.
3486   //
3487   // NB: we rely on the original order of entries to match.
3488   for (auto BBI = layout_rbegin(); BBI != layout_rend(); ++BBI) {
3489     BinaryBasicBlock *BB = *BBI;
3490     if (isEntryPoint(*BB))
3491       Stack.push(BB);
3492     BB->setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3493   }
3494 
3495   while (!Stack.empty()) {
3496     BinaryBasicBlock *BB = Stack.top();
3497     Stack.pop();
3498 
3499     if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3500       continue;
3501 
3502     BB->setLayoutIndex(Index++);
3503     DFS.push_back(BB);
3504 
3505     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3506       Stack.push(SuccBB);
3507     }
3508 
3509     const MCSymbol *TBB = nullptr;
3510     const MCSymbol *FBB = nullptr;
3511     MCInst *CondBranch = nullptr;
3512     MCInst *UncondBranch = nullptr;
3513     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3514         BB->succ_size() == 2) {
3515       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3516               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3517         Stack.push(BB->getConditionalSuccessor(true));
3518         Stack.push(BB->getConditionalSuccessor(false));
3519       } else {
3520         Stack.push(BB->getConditionalSuccessor(false));
3521         Stack.push(BB->getConditionalSuccessor(true));
3522       }
3523     } else {
3524       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3525         Stack.push(SuccBB);
3526       }
3527     }
3528   }
3529 
3530   return DFS;
3531 }
3532 
3533 size_t BinaryFunction::computeHash(bool UseDFS,
3534                                    OperandHashFuncTy OperandHashFunc) const {
3535   if (size() == 0)
3536     return 0;
3537 
3538   assert(hasCFG() && "function is expected to have CFG");
3539 
3540   const BasicBlockOrderType &Order = UseDFS ? dfs() : BasicBlocksLayout;
3541 
3542   // The hash is computed by creating a string of all instruction opcodes and
3543   // possibly their operands and then hashing that string with std::hash.
3544   std::string HashString;
3545   for (const BinaryBasicBlock *BB : Order) {
3546     for (const MCInst &Inst : *BB) {
3547       unsigned Opcode = Inst.getOpcode();
3548 
3549       if (BC.MIB->isPseudo(Inst))
3550         continue;
3551 
3552       // Ignore unconditional jumps since we check CFG consistency by processing
3553       // basic blocks in order and do not rely on branches to be in-sync with
3554       // CFG. Note that we still use condition code of conditional jumps.
3555       if (BC.MIB->isUnconditionalBranch(Inst))
3556         continue;
3557 
3558       if (Opcode == 0)
3559         HashString.push_back(0);
3560 
3561       while (Opcode) {
3562         uint8_t LSB = Opcode & 0xff;
3563         HashString.push_back(LSB);
3564         Opcode = Opcode >> 8;
3565       }
3566 
3567       for (const MCOperand &Op : MCPlus::primeOperands(Inst))
3568         HashString.append(OperandHashFunc(Op));
3569     }
3570   }
3571 
3572   return Hash = std::hash<std::string>{}(HashString);
3573 }
3574 
3575 void BinaryFunction::insertBasicBlocks(
3576     BinaryBasicBlock *Start,
3577     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3578     const bool UpdateLayout, const bool UpdateCFIState,
3579     const bool RecomputeLandingPads) {
3580   const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3581   const size_t NumNewBlocks = NewBBs.size();
3582 
3583   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3584                      nullptr);
3585 
3586   int64_t I = StartIndex + 1;
3587   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3588     assert(!BasicBlocks[I]);
3589     BasicBlocks[I++] = BB.release();
3590   }
3591 
3592   if (RecomputeLandingPads)
3593     recomputeLandingPads();
3594   else
3595     updateBBIndices(0);
3596 
3597   if (UpdateLayout)
3598     updateLayout(Start, NumNewBlocks);
3599 
3600   if (UpdateCFIState)
3601     updateCFIState(Start, NumNewBlocks);
3602 }
3603 
3604 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3605     BinaryFunction::iterator StartBB,
3606     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3607     const bool UpdateLayout, const bool UpdateCFIState,
3608     const bool RecomputeLandingPads) {
3609   const unsigned StartIndex = getIndex(&*StartBB);
3610   const size_t NumNewBlocks = NewBBs.size();
3611 
3612   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3613                      nullptr);
3614   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3615 
3616   unsigned I = StartIndex + 1;
3617   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3618     assert(!BasicBlocks[I]);
3619     BasicBlocks[I++] = BB.release();
3620   }
3621 
3622   if (RecomputeLandingPads)
3623     recomputeLandingPads();
3624   else
3625     updateBBIndices(0);
3626 
3627   if (UpdateLayout)
3628     updateLayout(*std::prev(RetIter), NumNewBlocks);
3629 
3630   if (UpdateCFIState)
3631     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3632 
3633   return RetIter;
3634 }
3635 
3636 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3637   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3638     BasicBlocks[I]->Index = I;
3639 }
3640 
3641 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3642                                     const unsigned NumNewBlocks) {
3643   const int32_t CFIState = Start->getCFIStateAtExit();
3644   const unsigned StartIndex = getIndex(Start) + 1;
3645   for (unsigned I = 0; I < NumNewBlocks; ++I)
3646     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3647 }
3648 
3649 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3650                                   const unsigned NumNewBlocks) {
3651   // If start not provided insert new blocks at the beginning
3652   if (!Start) {
3653     BasicBlocksLayout.insert(layout_begin(), BasicBlocks.begin(),
3654                              BasicBlocks.begin() + NumNewBlocks);
3655     updateLayoutIndices();
3656     return;
3657   }
3658 
3659   // Insert new blocks in the layout immediately after Start.
3660   auto Pos = llvm::find(layout(), Start);
3661   assert(Pos != layout_end());
3662   BasicBlockListType::iterator Begin =
3663       std::next(BasicBlocks.begin(), getIndex(Start) + 1);
3664   BasicBlockListType::iterator End =
3665       std::next(BasicBlocks.begin(), getIndex(Start) + NumNewBlocks + 1);
3666   BasicBlocksLayout.insert(Pos + 1, Begin, End);
3667   updateLayoutIndices();
3668 }
3669 
3670 bool BinaryFunction::checkForAmbiguousJumpTables() {
3671   SmallSet<uint64_t, 4> JumpTables;
3672   for (BinaryBasicBlock *&BB : BasicBlocks) {
3673     for (MCInst &Inst : *BB) {
3674       if (!BC.MIB->isIndirectBranch(Inst))
3675         continue;
3676       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3677       if (!JTAddress)
3678         continue;
3679       // This address can be inside another jump table, but we only consider
3680       // it ambiguous when the same start address is used, not the same JT
3681       // object.
3682       if (!JumpTables.count(JTAddress)) {
3683         JumpTables.insert(JTAddress);
3684         continue;
3685       }
3686       return true;
3687     }
3688   }
3689   return false;
3690 }
3691 
3692 void BinaryFunction::disambiguateJumpTables(
3693     MCPlusBuilder::AllocatorIdTy AllocId) {
3694   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3695   SmallPtrSet<JumpTable *, 4> JumpTables;
3696   for (BinaryBasicBlock *&BB : BasicBlocks) {
3697     for (MCInst &Inst : *BB) {
3698       if (!BC.MIB->isIndirectBranch(Inst))
3699         continue;
3700       JumpTable *JT = getJumpTable(Inst);
3701       if (!JT)
3702         continue;
3703       auto Iter = JumpTables.find(JT);
3704       if (Iter == JumpTables.end()) {
3705         JumpTables.insert(JT);
3706         continue;
3707       }
3708       // This instruction is an indirect jump using a jump table, but it is
3709       // using the same jump table of another jump. Try all our tricks to
3710       // extract the jump table symbol and make it point to a new, duplicated JT
3711       MCPhysReg BaseReg1;
3712       uint64_t Scale;
3713       const MCSymbol *Target;
3714       // In case we match if our first matcher, first instruction is the one to
3715       // patch
3716       MCInst *JTLoadInst = &Inst;
3717       // Try a standard indirect jump matcher, scale 8
3718       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3719           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3720                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3721                               /*Offset=*/BC.MIB->matchSymbol(Target));
3722       if (!IndJmpMatcher->match(
3723               *BC.MRI, *BC.MIB,
3724               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3725           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3726         MCPhysReg BaseReg2;
3727         uint64_t Offset;
3728         // Standard JT matching failed. Trying now:
3729         //     movq  "jt.2397/1"(,%rax,8), %rax
3730         //     jmpq  *%rax
3731         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3732             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3733                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3734                               /*Offset=*/BC.MIB->matchSymbol(Target));
3735         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3736         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3737             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3738         if (!IndJmpMatcher2->match(
3739                 *BC.MRI, *BC.MIB,
3740                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3741             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3742           // JT matching failed. Trying now:
3743           // PIC-style matcher, scale 4
3744           //    addq    %rdx, %rsi
3745           //    addq    %rdx, %rdi
3746           //    leaq    DATAat0x402450(%rip), %r11
3747           //    movslq  (%r11,%rdx,4), %rcx
3748           //    addq    %r11, %rcx
3749           //    jmpq    *%rcx # JUMPTABLE @0x402450
3750           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3751               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3752                   BC.MIB->matchReg(BaseReg1),
3753                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3754                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3755                                     BC.MIB->matchImm(Offset))));
3756           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3757               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3758           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3759           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3760               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3761                                                    BC.MIB->matchAnyOperand()));
3762           if (!PICIndJmpMatcher->match(
3763                   *BC.MRI, *BC.MIB,
3764                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3765               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3766               !PICBaseAddrMatcher->match(
3767                   *BC.MRI, *BC.MIB,
3768                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3769             llvm_unreachable("Failed to extract jump table base");
3770             continue;
3771           }
3772           // Matched PIC, identify the instruction with the reference to the JT
3773           JTLoadInst = LEAMatcher->CurInst;
3774         } else {
3775           // Matched non-PIC
3776           JTLoadInst = LoadMatcher->CurInst;
3777         }
3778       }
3779 
3780       uint64_t NewJumpTableID = 0;
3781       const MCSymbol *NewJTLabel;
3782       std::tie(NewJumpTableID, NewJTLabel) =
3783           BC.duplicateJumpTable(*this, JT, Target);
3784       {
3785         auto L = BC.scopeLock();
3786         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3787       }
3788       // We use a unique ID with the high bit set as address for this "injected"
3789       // jump table (not originally in the input binary).
3790       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3791     }
3792   }
3793 }
3794 
3795 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3796                                              BinaryBasicBlock *OldDest,
3797                                              BinaryBasicBlock *NewDest) {
3798   MCInst *Instr = BB->getLastNonPseudoInstr();
3799   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3800     return false;
3801   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3802   assert(JTAddress && "Invalid jump table address");
3803   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3804   assert(JT && "No jump table structure for this indirect branch");
3805   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3806                                         NewDest->getLabel());
3807   (void)Patched;
3808   assert(Patched && "Invalid entry to be replaced in jump table");
3809   return true;
3810 }
3811 
3812 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3813                                             BinaryBasicBlock *To) {
3814   // Create intermediate BB
3815   MCSymbol *Tmp;
3816   {
3817     auto L = BC.scopeLock();
3818     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3819   }
3820   // Link new BBs to the original input offset of the From BB, so we can map
3821   // samples recorded in new BBs back to the original BB seem in the input
3822   // binary (if using BAT)
3823   std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp);
3824   NewBB->setOffset(From->getInputOffset());
3825   BinaryBasicBlock *NewBBPtr = NewBB.get();
3826 
3827   // Update "From" BB
3828   auto I = From->succ_begin();
3829   auto BI = From->branch_info_begin();
3830   for (; I != From->succ_end(); ++I) {
3831     if (*I == To)
3832       break;
3833     ++BI;
3834   }
3835   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3836   uint64_t OrigCount = BI->Count;
3837   uint64_t OrigMispreds = BI->MispredictedCount;
3838   replaceJumpTableEntryIn(From, To, NewBBPtr);
3839   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3840 
3841   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3842   NewBB->setExecutionCount(OrigCount);
3843   NewBB->setIsCold(From->isCold());
3844 
3845   // Update CFI and BB layout with new intermediate BB
3846   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3847   NewBBs.emplace_back(std::move(NewBB));
3848   insertBasicBlocks(From, std::move(NewBBs), true, true,
3849                     /*RecomputeLandingPads=*/false);
3850   return NewBBPtr;
3851 }
3852 
3853 void BinaryFunction::deleteConservativeEdges() {
3854   // Our goal is to aggressively remove edges from the CFG that we believe are
3855   // wrong. This is used for instrumentation, where it is safe to remove
3856   // fallthrough edges because we won't reorder blocks.
3857   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3858     BinaryBasicBlock *BB = *I;
3859     if (BB->succ_size() != 1 || BB->size() == 0)
3860       continue;
3861 
3862     auto NextBB = std::next(I);
3863     MCInst *Last = BB->getLastNonPseudoInstr();
3864     // Fallthrough is a landing pad? Delete this edge (as long as we don't
3865     // have a direct jump to it)
3866     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3867         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3868       BB->removeAllSuccessors();
3869       continue;
3870     }
3871 
3872     // Look for suspicious calls at the end of BB where gcc may optimize it and
3873     // remove the jump to the epilogue when it knows the call won't return.
3874     if (!Last || !BC.MIB->isCall(*Last))
3875       continue;
3876 
3877     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3878     if (!CalleeSymbol)
3879       continue;
3880 
3881     StringRef CalleeName = CalleeSymbol->getName();
3882     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3883         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3884         CalleeName != "abort@PLT")
3885       continue;
3886 
3887     BB->removeAllSuccessors();
3888   }
3889 }
3890 
3891 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3892                                           uint64_t SymbolSize) const {
3893   // If this symbol is in a different section from the one where the
3894   // function symbol is, don't consider it as valid.
3895   if (!getOriginSection()->containsAddress(
3896           cantFail(Symbol.getAddress(), "cannot get symbol address")))
3897     return false;
3898 
3899   // Some symbols are tolerated inside function bodies, others are not.
3900   // The real function boundaries may not be known at this point.
3901   if (BC.isMarker(Symbol))
3902     return true;
3903 
3904   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3905   // function.
3906   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3907     return true;
3908 
3909   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3910     return false;
3911 
3912   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3913     return false;
3914 
3915   return true;
3916 }
3917 
3918 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3919   if (getKnownExecutionCount() == 0 || Count == 0)
3920     return;
3921 
3922   if (ExecutionCount < Count)
3923     Count = ExecutionCount;
3924 
3925   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
3926   if (AdjustmentRatio < 0.0)
3927     AdjustmentRatio = 0.0;
3928 
3929   for (BinaryBasicBlock *&BB : layout())
3930     BB->adjustExecutionCount(AdjustmentRatio);
3931 
3932   ExecutionCount -= Count;
3933 }
3934 
3935 BinaryFunction::~BinaryFunction() {
3936   for (BinaryBasicBlock *BB : BasicBlocks)
3937     delete BB;
3938   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
3939     delete BB;
3940 }
3941 
3942 void BinaryFunction::calculateLoopInfo() {
3943   // Discover loops.
3944   BinaryDominatorTree DomTree;
3945   DomTree.recalculate(*this);
3946   BLI.reset(new BinaryLoopInfo());
3947   BLI->analyze(DomTree);
3948 
3949   // Traverse discovered loops and add depth and profile information.
3950   std::stack<BinaryLoop *> St;
3951   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
3952     St.push(*I);
3953     ++BLI->OuterLoops;
3954   }
3955 
3956   while (!St.empty()) {
3957     BinaryLoop *L = St.top();
3958     St.pop();
3959     ++BLI->TotalLoops;
3960     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
3961 
3962     // Add nested loops in the stack.
3963     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3964       St.push(*I);
3965 
3966     // Skip if no valid profile is found.
3967     if (!hasValidProfile()) {
3968       L->EntryCount = COUNT_NO_PROFILE;
3969       L->ExitCount = COUNT_NO_PROFILE;
3970       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
3971       continue;
3972     }
3973 
3974     // Compute back edge count.
3975     SmallVector<BinaryBasicBlock *, 1> Latches;
3976     L->getLoopLatches(Latches);
3977 
3978     for (BinaryBasicBlock *Latch : Latches) {
3979       auto BI = Latch->branch_info_begin();
3980       for (BinaryBasicBlock *Succ : Latch->successors()) {
3981         if (Succ == L->getHeader()) {
3982           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
3983                  "profile data not found");
3984           L->TotalBackEdgeCount += BI->Count;
3985         }
3986         ++BI;
3987       }
3988     }
3989 
3990     // Compute entry count.
3991     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
3992 
3993     // Compute exit count.
3994     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
3995     L->getExitEdges(ExitEdges);
3996     for (BinaryLoop::Edge &Exit : ExitEdges) {
3997       const BinaryBasicBlock *Exiting = Exit.first;
3998       const BinaryBasicBlock *ExitTarget = Exit.second;
3999       auto BI = Exiting->branch_info_begin();
4000       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4001         if (Succ == ExitTarget) {
4002           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4003                  "profile data not found");
4004           L->ExitCount += BI->Count;
4005         }
4006         ++BI;
4007       }
4008     }
4009   }
4010 }
4011 
4012 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4013   if (!isEmitted()) {
4014     assert(!isInjected() && "injected function should be emitted");
4015     setOutputAddress(getAddress());
4016     setOutputSize(getSize());
4017     return;
4018   }
4019 
4020   const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4021   ErrorOr<BinarySection &> ColdSection = getColdCodeSection();
4022   const uint64_t ColdBaseAddress =
4023       isSplit() ? ColdSection->getOutputAddress() : 0;
4024   if (BC.HasRelocations || isInjected()) {
4025     const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4026     const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4027     setOutputAddress(BaseAddress + StartOffset);
4028     setOutputSize(EndOffset - StartOffset);
4029     if (hasConstantIsland()) {
4030       const uint64_t DataOffset =
4031           Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4032       setOutputDataAddress(BaseAddress + DataOffset);
4033     }
4034     if (isSplit()) {
4035       const MCSymbol *ColdStartSymbol = getColdSymbol();
4036       assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4037              "split function should have defined cold symbol");
4038       const MCSymbol *ColdEndSymbol = getFunctionColdEndLabel();
4039       assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4040              "split function should have defined cold end symbol");
4041       const uint64_t ColdStartOffset = Layout.getSymbolOffset(*ColdStartSymbol);
4042       const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4043       cold().setAddress(ColdBaseAddress + ColdStartOffset);
4044       cold().setImageSize(ColdEndOffset - ColdStartOffset);
4045       if (hasConstantIsland()) {
4046         const uint64_t DataOffset =
4047             Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4048         setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4049       }
4050     }
4051   } else {
4052     setOutputAddress(getAddress());
4053     setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4054   }
4055 
4056   // Update basic block output ranges for the debug info, if we have
4057   // secondary entry points in the symbol table to update or if writing BAT.
4058   if (!opts::UpdateDebugSections && !isMultiEntry() &&
4059       !requiresAddressTranslation())
4060     return;
4061 
4062   // Output ranges should match the input if the body hasn't changed.
4063   if (!isSimple() && !BC.HasRelocations)
4064     return;
4065 
4066   // AArch64 may have functions that only contains a constant island (no code).
4067   if (layout_begin() == layout_end())
4068     return;
4069 
4070   BinaryBasicBlock *PrevBB = nullptr;
4071   for (auto BBI = layout_begin(), BBE = layout_end(); BBI != BBE; ++BBI) {
4072     BinaryBasicBlock *BB = *BBI;
4073     assert(BB->getLabel()->isDefined() && "symbol should be defined");
4074     const uint64_t BBBaseAddress = BB->isCold() ? ColdBaseAddress : BaseAddress;
4075     if (!BC.HasRelocations) {
4076       if (BB->isCold()) {
4077         assert(BBBaseAddress == cold().getAddress());
4078       } else {
4079         assert(BBBaseAddress == getOutputAddress());
4080       }
4081     }
4082     const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4083     const uint64_t BBAddress = BBBaseAddress + BBOffset;
4084     BB->setOutputStartAddress(BBAddress);
4085 
4086     if (PrevBB) {
4087       uint64_t PrevBBEndAddress = BBAddress;
4088       if (BB->isCold() != PrevBB->isCold())
4089         PrevBBEndAddress = getOutputAddress() + getOutputSize();
4090       PrevBB->setOutputEndAddress(PrevBBEndAddress);
4091     }
4092     PrevBB = BB;
4093 
4094     BB->updateOutputValues(Layout);
4095   }
4096   PrevBB->setOutputEndAddress(PrevBB->isCold()
4097                                   ? cold().getAddress() + cold().getImageSize()
4098                                   : getOutputAddress() + getOutputSize());
4099 }
4100 
4101 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4102   DebugAddressRangesVector OutputRanges;
4103 
4104   if (isFolded())
4105     return OutputRanges;
4106 
4107   if (IsFragment)
4108     return OutputRanges;
4109 
4110   OutputRanges.emplace_back(getOutputAddress(),
4111                             getOutputAddress() + getOutputSize());
4112   if (isSplit()) {
4113     assert(isEmitted() && "split function should be emitted");
4114     OutputRanges.emplace_back(cold().getAddress(),
4115                               cold().getAddress() + cold().getImageSize());
4116   }
4117 
4118   if (isSimple())
4119     return OutputRanges;
4120 
4121   for (BinaryFunction *Frag : Fragments) {
4122     assert(!Frag->isSimple() &&
4123            "fragment of non-simple function should also be non-simple");
4124     OutputRanges.emplace_back(Frag->getOutputAddress(),
4125                               Frag->getOutputAddress() + Frag->getOutputSize());
4126   }
4127 
4128   return OutputRanges;
4129 }
4130 
4131 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4132   if (isFolded())
4133     return 0;
4134 
4135   // If the function hasn't changed return the same address.
4136   if (!isEmitted())
4137     return Address;
4138 
4139   if (Address < getAddress())
4140     return 0;
4141 
4142   // Check if the address is associated with an instruction that is tracked
4143   // by address translation.
4144   auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4145   if (KV != InputOffsetToAddressMap.end())
4146     return KV->second;
4147 
4148   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4149   //        intact. Instead we can use pseudo instructions and/or annotations.
4150   const uint64_t Offset = Address - getAddress();
4151   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4152   if (!BB) {
4153     // Special case for address immediately past the end of the function.
4154     if (Offset == getSize())
4155       return getOutputAddress() + getOutputSize();
4156 
4157     return 0;
4158   }
4159 
4160   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4161                   BB->getOutputAddressRange().second);
4162 }
4163 
4164 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4165     const DWARFAddressRangesVector &InputRanges) const {
4166   DebugAddressRangesVector OutputRanges;
4167 
4168   if (isFolded())
4169     return OutputRanges;
4170 
4171   // If the function hasn't changed return the same ranges.
4172   if (!isEmitted()) {
4173     OutputRanges.resize(InputRanges.size());
4174     llvm::transform(InputRanges, OutputRanges.begin(),
4175                     [](const DWARFAddressRange &Range) {
4176                       return DebugAddressRange(Range.LowPC, Range.HighPC);
4177                     });
4178     return OutputRanges;
4179   }
4180 
4181   // Even though we will merge ranges in a post-processing pass, we attempt to
4182   // merge them in a main processing loop as it improves the processing time.
4183   uint64_t PrevEndAddress = 0;
4184   for (const DWARFAddressRange &Range : InputRanges) {
4185     if (!containsAddress(Range.LowPC)) {
4186       LLVM_DEBUG(
4187           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4188                  << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4189                  << Twine::utohexstr(Range.HighPC) << "]\n");
4190       PrevEndAddress = 0;
4191       continue;
4192     }
4193     uint64_t InputOffset = Range.LowPC - getAddress();
4194     const uint64_t InputEndOffset =
4195         std::min(Range.HighPC - getAddress(), getSize());
4196 
4197     auto BBI = llvm::upper_bound(BasicBlockOffsets,
4198                                  BasicBlockOffset(InputOffset, nullptr),
4199                                  CompareBasicBlockOffsets());
4200     --BBI;
4201     do {
4202       const BinaryBasicBlock *BB = BBI->second;
4203       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4204         LLVM_DEBUG(
4205             dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4206                    << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4207                    << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4208         PrevEndAddress = 0;
4209         break;
4210       }
4211 
4212       // Skip the range if the block was deleted.
4213       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4214         const uint64_t StartAddress =
4215             OutputStart + InputOffset - BB->getOffset();
4216         uint64_t EndAddress = BB->getOutputAddressRange().second;
4217         if (InputEndOffset < BB->getEndOffset())
4218           EndAddress = StartAddress + InputEndOffset - InputOffset;
4219 
4220         if (StartAddress == PrevEndAddress) {
4221           OutputRanges.back().HighPC =
4222               std::max(OutputRanges.back().HighPC, EndAddress);
4223         } else {
4224           OutputRanges.emplace_back(StartAddress,
4225                                     std::max(StartAddress, EndAddress));
4226         }
4227         PrevEndAddress = OutputRanges.back().HighPC;
4228       }
4229 
4230       InputOffset = BB->getEndOffset();
4231       ++BBI;
4232     } while (InputOffset < InputEndOffset);
4233   }
4234 
4235   // Post-processing pass to sort and merge ranges.
4236   llvm::sort(OutputRanges);
4237   DebugAddressRangesVector MergedRanges;
4238   PrevEndAddress = 0;
4239   for (const DebugAddressRange &Range : OutputRanges) {
4240     if (Range.LowPC <= PrevEndAddress) {
4241       MergedRanges.back().HighPC =
4242           std::max(MergedRanges.back().HighPC, Range.HighPC);
4243     } else {
4244       MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4245     }
4246     PrevEndAddress = MergedRanges.back().HighPC;
4247   }
4248 
4249   return MergedRanges;
4250 }
4251 
4252 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4253   if (CurrentState == State::Disassembled) {
4254     auto II = Instructions.find(Offset);
4255     return (II == Instructions.end()) ? nullptr : &II->second;
4256   } else if (CurrentState == State::CFG) {
4257     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4258     if (!BB)
4259       return nullptr;
4260 
4261     for (MCInst &Inst : *BB) {
4262       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4263       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4264         return &Inst;
4265     }
4266 
4267     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4268       const uint32_t Size =
4269           BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4270       if (BB->getEndOffset() - Offset == Size)
4271         return LastInstr;
4272     }
4273 
4274     return nullptr;
4275   } else {
4276     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4277   }
4278 }
4279 
4280 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4281     const DebugLocationsVector &InputLL) const {
4282   DebugLocationsVector OutputLL;
4283 
4284   if (isFolded())
4285     return OutputLL;
4286 
4287   // If the function hasn't changed - there's nothing to update.
4288   if (!isEmitted())
4289     return InputLL;
4290 
4291   uint64_t PrevEndAddress = 0;
4292   SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4293   for (const DebugLocationEntry &Entry : InputLL) {
4294     const uint64_t Start = Entry.LowPC;
4295     const uint64_t End = Entry.HighPC;
4296     if (!containsAddress(Start)) {
4297       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4298                            "for "
4299                         << *this << " : [0x" << Twine::utohexstr(Start)
4300                         << ", 0x" << Twine::utohexstr(End) << "]\n");
4301       continue;
4302     }
4303     uint64_t InputOffset = Start - getAddress();
4304     const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4305     auto BBI = llvm::upper_bound(BasicBlockOffsets,
4306                                  BasicBlockOffset(InputOffset, nullptr),
4307                                  CompareBasicBlockOffsets());
4308     --BBI;
4309     do {
4310       const BinaryBasicBlock *BB = BBI->second;
4311       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4312         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4313                              "for "
4314                           << *this << " : [0x" << Twine::utohexstr(Start)
4315                           << ", 0x" << Twine::utohexstr(End) << "]\n");
4316         PrevEndAddress = 0;
4317         break;
4318       }
4319 
4320       // Skip the range if the block was deleted.
4321       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4322         const uint64_t StartAddress =
4323             OutputStart + InputOffset - BB->getOffset();
4324         uint64_t EndAddress = BB->getOutputAddressRange().second;
4325         if (InputEndOffset < BB->getEndOffset())
4326           EndAddress = StartAddress + InputEndOffset - InputOffset;
4327 
4328         if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4329           OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4330         } else {
4331           OutputLL.emplace_back(DebugLocationEntry{
4332               StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4333         }
4334         PrevEndAddress = OutputLL.back().HighPC;
4335         PrevExpr = &OutputLL.back().Expr;
4336       }
4337 
4338       ++BBI;
4339       InputOffset = BB->getEndOffset();
4340     } while (InputOffset < InputEndOffset);
4341   }
4342 
4343   // Sort and merge adjacent entries with identical location.
4344   llvm::stable_sort(
4345       OutputLL, [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4346         return A.LowPC < B.LowPC;
4347       });
4348   DebugLocationsVector MergedLL;
4349   PrevEndAddress = 0;
4350   PrevExpr = nullptr;
4351   for (const DebugLocationEntry &Entry : OutputLL) {
4352     if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4353       MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4354     } else {
4355       const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4356       const uint64_t End = std::max(Begin, Entry.HighPC);
4357       MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4358     }
4359     PrevEndAddress = MergedLL.back().HighPC;
4360     PrevExpr = &MergedLL.back().Expr;
4361   }
4362 
4363   return MergedLL;
4364 }
4365 
4366 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4367   if (!opts::shouldPrint(*this))
4368     return;
4369 
4370   OS << "Loop Info for Function \"" << *this << "\"";
4371   if (hasValidProfile())
4372     OS << " (count: " << getExecutionCount() << ")";
4373   OS << "\n";
4374 
4375   std::stack<BinaryLoop *> St;
4376   for_each(*BLI, [&](BinaryLoop *L) { St.push(L); });
4377   while (!St.empty()) {
4378     BinaryLoop *L = St.top();
4379     St.pop();
4380 
4381     for_each(*L, [&](BinaryLoop *Inner) { St.push(Inner); });
4382 
4383     if (!hasValidProfile())
4384       continue;
4385 
4386     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4387        << " loop header: " << L->getHeader()->getName();
4388     OS << "\n";
4389     OS << "Loop basic blocks: ";
4390     ListSeparator LS;
4391     for (BinaryBasicBlock *BB : L->blocks())
4392       OS << LS << BB->getName();
4393     OS << "\n";
4394     if (hasValidProfile()) {
4395       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4396       OS << "Loop entry count: " << L->EntryCount << "\n";
4397       OS << "Loop exit count: " << L->ExitCount << "\n";
4398       if (L->EntryCount > 0) {
4399         OS << "Average iters per entry: "
4400            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4401            << "\n";
4402       }
4403     }
4404     OS << "----\n";
4405   }
4406 
4407   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4408   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4409   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4410 }
4411 
4412 bool BinaryFunction::isAArch64Veneer() const {
4413   if (empty())
4414     return false;
4415 
4416   BinaryBasicBlock &BB = **BasicBlocks.begin();
4417   for (MCInst &Inst : BB)
4418     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4419       return false;
4420 
4421   for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) {
4422     for (MCInst &Inst : **I)
4423       if (!BC.MIB->isNoop(Inst))
4424         return false;
4425   }
4426 
4427   return true;
4428 }
4429 
4430 } // namespace bolt
4431 } // namespace llvm
4432