1 //===- bolt/Core/BinaryFunction.h - Low-level function ----------*- C++ -*-===//
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 contains the declaration of the BinaryFunction class. It represents
10 // a function at the lowest IR level. Typically, a BinaryFunction represents a
11 // function object in a compiled and linked binary file. However, a
12 // BinaryFunction can also be constructed manually, e.g. for injecting into a
13 // binary file.
14 //
15 // A BinaryFunction could be in one of the several states described in
16 // BinaryFunction::State. While in the disassembled state, it will contain a
17 // list of instructions with their offsets. In the CFG state, it will contain a
18 // list of BinaryBasicBlocks that form a control-flow graph. This state is best
19 // suited for binary analysis and optimizations. However, sometimes it's
20 // impossible to build the precise CFG due to the ambiguity of indirect
21 // branches.
22 //
23 //===----------------------------------------------------------------------===//
24 
25 #ifndef BOLT_CORE_BINARY_FUNCTION_H
26 #define BOLT_CORE_BINARY_FUNCTION_H
27 
28 #include "bolt/Core/BinaryBasicBlock.h"
29 #include "bolt/Core/BinaryContext.h"
30 #include "bolt/Core/BinaryLoop.h"
31 #include "bolt/Core/BinarySection.h"
32 #include "bolt/Core/DebugData.h"
33 #include "bolt/Core/JumpTable.h"
34 #include "bolt/Core/MCPlus.h"
35 #include "bolt/Utils/NameResolver.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/iterator.h"
38 #include "llvm/BinaryFormat/Dwarf.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCDwarf.h"
41 #include "llvm/MC/MCInst.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Object/ObjectFile.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <limits>
47 #include <unordered_map>
48 #include <unordered_set>
49 #include <vector>
50 
51 using namespace llvm::object;
52 
53 namespace llvm {
54 
55 class DWARFUnit;
56 
57 namespace bolt {
58 
59 using InputOffsetToAddressMapTy = std::unordered_multimap<uint64_t, uint64_t>;
60 
61 /// Types of macro-fusion alignment corrections.
62 enum MacroFusionType { MFT_NONE, MFT_HOT, MFT_ALL };
63 
64 enum IndirectCallPromotionType : char {
65   ICP_NONE,        /// Don't perform ICP.
66   ICP_CALLS,       /// Perform ICP on indirect calls.
67   ICP_JUMP_TABLES, /// Perform ICP on jump tables.
68   ICP_ALL          /// Perform ICP on calls and jump tables.
69 };
70 
71 /// Information on a single indirect call to a particular callee.
72 struct IndirectCallProfile {
73   MCSymbol *Symbol;
74   uint32_t Offset;
75   uint64_t Count;
76   uint64_t Mispreds;
77 
78   IndirectCallProfile(MCSymbol *Symbol, uint64_t Count, uint64_t Mispreds,
79                       uint32_t Offset = 0)
80       : Symbol(Symbol), Offset(Offset), Count(Count), Mispreds(Mispreds) {}
81 
82   bool operator==(const IndirectCallProfile &Other) const {
83     return Symbol == Other.Symbol && Offset == Other.Offset;
84   }
85 };
86 
87 /// Aggregated information for an indirect call site.
88 using IndirectCallSiteProfile = SmallVector<IndirectCallProfile, 4>;
89 
90 inline raw_ostream &operator<<(raw_ostream &OS,
91                                const bolt::IndirectCallSiteProfile &ICSP) {
92   std::string TempString;
93   raw_string_ostream SS(TempString);
94 
95   const char *Sep = "\n        ";
96   uint64_t TotalCount = 0;
97   uint64_t TotalMispreds = 0;
98   for (const IndirectCallProfile &CSP : ICSP) {
99     SS << Sep << "{ " << (CSP.Symbol ? CSP.Symbol->getName() : "<unknown>")
100        << ": " << CSP.Count << " (" << CSP.Mispreds << " misses) }";
101     Sep = ",\n        ";
102     TotalCount += CSP.Count;
103     TotalMispreds += CSP.Mispreds;
104   }
105   SS.flush();
106 
107   OS << TotalCount << " (" << TotalMispreds << " misses) :" << TempString;
108   return OS;
109 }
110 
111 /// BinaryFunction is a representation of machine-level function.
112 ///
113 /// In the input binary, an instance of BinaryFunction can represent a fragment
114 /// of a function if the higher-level function was split, e.g. into hot and cold
115 /// parts. The fragment containing the main entry point is called a parent
116 /// or the main fragment.
117 class BinaryFunction {
118 public:
119   enum class State : char {
120     Empty = 0,     /// Function body is empty.
121     Disassembled,  /// Function have been disassembled.
122     CFG,           /// Control flow graph has been built.
123     CFG_Finalized, /// CFG is finalized. No optimizations allowed.
124     EmittedCFG,    /// Instructions have been emitted to output.
125     Emitted,       /// Same as above plus CFG is destroyed.
126   };
127 
128   /// Types of profile the function can use. Could be a combination.
129   enum {
130     PF_NONE = 0,     /// No profile.
131     PF_LBR = 1,      /// Profile is based on last branch records.
132     PF_SAMPLE = 2,   /// Non-LBR sample-based profile.
133     PF_MEMEVENT = 4, /// Profile has mem events.
134   };
135 
136   /// Struct for tracking exception handling ranges.
137   struct CallSite {
138     const MCSymbol *Start;
139     const MCSymbol *End;
140     const MCSymbol *LP;
141     uint64_t Action;
142   };
143 
144   using CallSitesType = SmallVector<CallSite, 0>;
145 
146   using IslandProxiesType =
147       std::map<BinaryFunction *, std::map<const MCSymbol *, MCSymbol *>>;
148 
149   struct IslandInfo {
150     /// Temporary holder of offsets that are data markers (used in AArch)
151     /// It is possible to have data in code sections. To ease the identification
152     /// of data in code sections, the ABI requires the symbol table to have
153     /// symbols named "$d" identifying the start of data inside code and "$x"
154     /// identifying the end of a chunk of data inside code. DataOffsets contain
155     /// all offsets of $d symbols and CodeOffsets all offsets of $x symbols.
156     std::set<uint64_t> DataOffsets;
157     std::set<uint64_t> CodeOffsets;
158 
159     /// List of relocations associated with data in the constant island
160     std::map<uint64_t, Relocation> Relocations;
161 
162     /// Offsets in function that are data values in a constant island identified
163     /// after disassembling
164     std::map<uint64_t, MCSymbol *> Offsets;
165     SmallPtrSet<MCSymbol *, 4> Symbols;
166     DenseMap<const MCSymbol *, BinaryFunction *> ProxySymbols;
167     DenseMap<const MCSymbol *, MCSymbol *> ColdSymbols;
168     /// Keeps track of other functions we depend on because there is a reference
169     /// to the constant islands in them.
170     IslandProxiesType Proxies, ColdProxies;
171     SmallPtrSet<BinaryFunction *, 1> Dependency; // The other way around
172 
173     mutable MCSymbol *FunctionConstantIslandLabel{nullptr};
174     mutable MCSymbol *FunctionColdConstantIslandLabel{nullptr};
175 
176     // Returns constant island alignment
177     uint16_t getAlignment() const { return sizeof(uint64_t); }
178   };
179 
180   static constexpr uint64_t COUNT_NO_PROFILE =
181       BinaryBasicBlock::COUNT_NO_PROFILE;
182 
183   /// We have to use at least 2-byte alignment for functions because of C++ ABI.
184   static constexpr unsigned MinAlign = 2;
185 
186   static const char TimerGroupName[];
187   static const char TimerGroupDesc[];
188 
189   using BasicBlockOrderType = SmallVector<BinaryBasicBlock *, 0>;
190 
191   /// Mark injected functions
192   bool IsInjected = false;
193 
194   using LSDATypeTableTy = SmallVector<uint64_t, 0>;
195 
196   /// List of DWARF CFI instructions. Original CFI from the binary must be
197   /// sorted w.r.t. offset that it appears. We rely on this to replay CFIs
198   /// if needed (to fix state after reordering BBs).
199   using CFIInstrMapType = SmallVector<MCCFIInstruction, 0>;
200   using cfi_iterator = CFIInstrMapType::iterator;
201   using const_cfi_iterator = CFIInstrMapType::const_iterator;
202 
203 private:
204   /// Current state of the function.
205   State CurrentState{State::Empty};
206 
207   /// A list of symbols associated with the function entry point.
208   ///
209   /// Multiple symbols would typically result from identical code-folding
210   /// optimization.
211   typedef SmallVector<MCSymbol *, 1> SymbolListTy;
212   SymbolListTy Symbols;
213 
214   /// The list of names this function is known under. Used for fuzzy-matching
215   /// the function to its name in a profile, command line, etc.
216   SmallVector<std::string, 0> Aliases;
217 
218   /// Containing section in the input file.
219   BinarySection *OriginSection = nullptr;
220 
221   /// Address of the function in memory. Also could be an offset from
222   /// base address for position independent binaries.
223   uint64_t Address;
224 
225   /// Original size of the function.
226   uint64_t Size;
227 
228   /// Address of the function in output.
229   uint64_t OutputAddress{0};
230 
231   /// Size of the function in the output file.
232   uint64_t OutputSize{0};
233 
234   /// Offset in the file.
235   uint64_t FileOffset{0};
236 
237   /// Maximum size this function is allowed to have.
238   uint64_t MaxSize{std::numeric_limits<uint64_t>::max()};
239 
240   /// Alignment requirements for the function.
241   uint16_t Alignment{2};
242 
243   /// Maximum number of bytes used for alignment of hot part of the function.
244   uint16_t MaxAlignmentBytes{0};
245 
246   /// Maximum number of bytes used for alignment of cold part of the function.
247   uint16_t MaxColdAlignmentBytes{0};
248 
249   const MCSymbol *PersonalityFunction{nullptr};
250   uint8_t PersonalityEncoding{dwarf::DW_EH_PE_sdata4 | dwarf::DW_EH_PE_pcrel};
251 
252   BinaryContext &BC;
253 
254   std::unique_ptr<BinaryLoopInfo> BLI;
255 
256   /// Set of external addresses in the code that are not a function start
257   /// and are referenced from this function.
258   std::set<uint64_t> InterproceduralReferences;
259 
260   /// All labels in the function that are referenced via relocations from
261   /// data objects. Typically these are jump table destinations and computed
262   /// goto labels.
263   std::set<uint64_t> ExternallyReferencedOffsets;
264 
265   /// Offsets of indirect branches with unknown destinations.
266   std::set<uint64_t> UnknownIndirectBranchOffsets;
267 
268   /// A set of local and global symbols corresponding to secondary entry points.
269   /// Each additional function entry point has a corresponding entry in the map.
270   /// The key is a local symbol corresponding to a basic block and the value
271   /// is a global symbol corresponding to an external entry point.
272   DenseMap<const MCSymbol *, MCSymbol *> SecondaryEntryPoints;
273 
274   /// False if the function is too complex to reconstruct its control
275   /// flow graph.
276   /// In relocation mode we still disassemble and re-assemble such functions.
277   bool IsSimple{true};
278 
279   /// Indication that the function should be ignored for optimization purposes.
280   /// If we can skip emission of some functions, then ignored functions could
281   /// be not fully disassembled and will not be emitted.
282   bool IsIgnored{false};
283 
284   /// Pseudo functions should not be disassembled or emitted.
285   bool IsPseudo{false};
286 
287   /// True if the original function code has all necessary relocations to track
288   /// addresses of functions emitted to new locations. Typically set for
289   /// functions that we are not going to emit.
290   bool HasExternalRefRelocations{false};
291 
292   /// True if the function has an indirect branch with unknown destination.
293   bool HasUnknownControlFlow{false};
294 
295   /// The code from inside the function references one of the code locations
296   /// from the same function as a data, i.e. it's possible the label is used
297   /// inside an address calculation or could be referenced from outside.
298   bool HasInternalLabelReference{false};
299 
300   /// In AArch64, preserve nops to maintain code equal to input (assuming no
301   /// optimizations are done).
302   bool PreserveNops{false};
303 
304   /// Indicate if this function has associated exception handling metadata.
305   bool HasEHRanges{false};
306 
307   /// True if the function uses DW_CFA_GNU_args_size CFIs.
308   bool UsesGnuArgsSize{false};
309 
310   /// True if the function might have a profile available externally.
311   /// Used to check if processing of the function is required under certain
312   /// conditions.
313   bool HasProfileAvailable{false};
314 
315   bool HasMemoryProfile{false};
316 
317   /// Execution halts whenever this function is entered.
318   bool TrapsOnEntry{false};
319 
320   /// True if the function had an indirect branch with a fixed internal
321   /// destination.
322   bool HasFixedIndirectBranch{false};
323 
324   /// True if the function is a fragment of another function. This means that
325   /// this function could only be entered via its parent or one of its sibling
326   /// fragments. It could be entered at any basic block. It can also return
327   /// the control to any basic block of its parent or its sibling.
328   bool IsFragment{false};
329 
330   /// Indicate that the function body has SDT marker
331   bool HasSDTMarker{false};
332 
333   /// Indicate that the function body has Pseudo Probe
334   bool HasPseudoProbe{BC.getUniqueSectionByName(".pseudo_probe_desc") &&
335                       BC.getUniqueSectionByName(".pseudo_probe")};
336 
337   /// True if the original entry point was patched.
338   bool IsPatched{false};
339 
340   /// True if the function contains jump table with entries pointing to
341   /// locations in fragments.
342   bool HasSplitJumpTable{false};
343 
344   /// True if there are no control-flow edges with successors in other functions
345   /// (i.e. if tail calls have edges to function-local basic blocks).
346   /// Set to false by SCTC. Dynostats can't be reliably computed for
347   /// functions with non-canonical CFG.
348   /// This attribute is only valid when hasCFG() == true.
349   bool HasCanonicalCFG{true};
350 
351   /// The address for the code for this function in codegen memory.
352   /// Used for functions that are emitted in a dedicated section with a fixed
353   /// address. E.g. for functions that are overwritten in-place.
354   uint64_t ImageAddress{0};
355 
356   /// The size of the code in memory.
357   uint64_t ImageSize{0};
358 
359   /// Name for the section this function code should reside in.
360   std::string CodeSectionName;
361 
362   /// Name for the corresponding cold code section.
363   std::string ColdCodeSectionName;
364 
365   /// Parent function fragment for split function fragments.
366   SmallPtrSet<BinaryFunction *, 1> ParentFragments;
367 
368   /// Indicate if the function body was folded into another function.
369   /// Used by ICF optimization.
370   BinaryFunction *FoldedIntoFunction{nullptr};
371 
372   /// All fragments for a parent function.
373   SmallPtrSet<BinaryFunction *, 1> Fragments;
374 
375   /// The profile data for the number of times the function was executed.
376   uint64_t ExecutionCount{COUNT_NO_PROFILE};
377 
378   /// Profile match ratio.
379   float ProfileMatchRatio{0.0f};
380 
381   /// Raw branch count for this function in the profile
382   uint64_t RawBranchCount{0};
383 
384   /// Indicates the type of profile the function is using.
385   uint16_t ProfileFlags{PF_NONE};
386 
387   /// For functions with mismatched profile we store all call profile
388   /// information at a function level (as opposed to tying it to
389   /// specific call sites).
390   IndirectCallSiteProfile AllCallSites;
391 
392   /// Score of the function (estimated number of instructions executed,
393   /// according to profile data). -1 if the score has not been calculated yet.
394   mutable int64_t FunctionScore{-1};
395 
396   /// Original LSDA address for the function.
397   uint64_t LSDAAddress{0};
398 
399   /// Containing compilation unit for the function.
400   DWARFUnit *DwarfUnit{nullptr};
401 
402   /// Last computed hash value. Note that the value could be recomputed using
403   /// different parameters by every pass.
404   mutable uint64_t Hash{0};
405 
406   /// For PLT functions it contains a symbol associated with a function
407   /// reference. It is nullptr for non-PLT functions.
408   const MCSymbol *PLTSymbol{nullptr};
409 
410   /// Function order for streaming into the destination binary.
411   uint32_t Index{-1U};
412 
413   /// Get basic block index assuming it belongs to this function.
414   unsigned getIndex(const BinaryBasicBlock *BB) const {
415     assert(BB->getIndex() < BasicBlocks.size());
416     return BB->getIndex();
417   }
418 
419   /// Return basic block that originally contained offset \p Offset
420   /// from the function start.
421   BinaryBasicBlock *getBasicBlockContainingOffset(uint64_t Offset);
422 
423   const BinaryBasicBlock *getBasicBlockContainingOffset(uint64_t Offset) const {
424     return const_cast<BinaryFunction *>(this)->getBasicBlockContainingOffset(
425         Offset);
426   }
427 
428   /// Return basic block that started at offset \p Offset.
429   BinaryBasicBlock *getBasicBlockAtOffset(uint64_t Offset) {
430     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
431     return BB && BB->getOffset() == Offset ? BB : nullptr;
432   }
433 
434   /// Release memory taken by the list.
435   template <typename T> BinaryFunction &clearList(T &List) {
436     T TempList;
437     TempList.swap(List);
438     return *this;
439   }
440 
441   /// Update the indices of all the basic blocks starting at StartIndex.
442   void updateBBIndices(const unsigned StartIndex);
443 
444   /// Annotate each basic block entry with its current CFI state. This is
445   /// run right after the construction of CFG while basic blocks are in their
446   /// original order.
447   void annotateCFIState();
448 
449   /// Associate DW_CFA_GNU_args_size info with invoke instructions
450   /// (call instructions with non-empty landing pad).
451   void propagateGnuArgsSizeInfo(MCPlusBuilder::AllocatorIdTy AllocId);
452 
453   /// Synchronize branch instructions with CFG.
454   void postProcessBranches();
455 
456   /// The address offset where we emitted the constant island, that is, the
457   /// chunk of data in the function code area (AArch only)
458   int64_t OutputDataOffset{0};
459   int64_t OutputColdDataOffset{0};
460 
461   /// Map labels to corresponding basic blocks.
462   DenseMap<const MCSymbol *, BinaryBasicBlock *> LabelToBB;
463 
464   using BranchListType = SmallVector<std::pair<uint32_t, uint32_t>, 0>;
465   BranchListType TakenBranches;   /// All local taken branches.
466   BranchListType IgnoredBranches; /// Branches ignored by CFG purposes.
467 
468   /// Map offset in the function to a label.
469   /// Labels are used for building CFG for simple functions. For non-simple
470   /// function in relocation mode we need to emit them for relocations
471   /// referencing function internals to work (e.g. jump tables).
472   using LabelsMapType = std::map<uint32_t, MCSymbol *>;
473   LabelsMapType Labels;
474 
475   /// Temporary holder of instructions before CFG is constructed.
476   /// Map offset in the function to MCInst.
477   using InstrMapType = std::map<uint32_t, MCInst>;
478   InstrMapType Instructions;
479 
480   /// We don't decode Call Frame Info encoded in DWARF program state
481   /// machine. Instead we define a "CFI State" - a frame information that
482   /// is a result of executing FDE CFI program up to a given point. The
483   /// program consists of opaque Call Frame Instructions:
484   ///
485   ///   CFI #0
486   ///   CFI #1
487   ///   ....
488   ///   CFI #N
489   ///
490   /// When we refer to "CFI State K" - it corresponds to a row in an abstract
491   /// Call Frame Info table. This row is reached right before executing CFI #K.
492   ///
493   /// At any point of execution in a function we are in any one of (N + 2)
494   /// states described in the original FDE program. We can't have more states
495   /// without intelligent processing of CFIs.
496   ///
497   /// When the final layout of basic blocks is known, and we finalize CFG,
498   /// we modify the original program to make sure the same state could be
499   /// reached even when basic blocks containing CFI instructions are executed
500   /// in a different order.
501   CFIInstrMapType FrameInstructions;
502 
503   /// A map of restore state CFI instructions to their equivalent CFI
504   /// instructions that produce the same state, in order to eliminate
505   /// remember-restore CFI instructions when rewriting CFI.
506   DenseMap<int32_t, SmallVector<int32_t, 4>> FrameRestoreEquivalents;
507 
508   // For tracking exception handling ranges.
509   CallSitesType CallSites;
510   CallSitesType ColdCallSites;
511 
512   /// Binary blobs representing action, type, and type index tables for this
513   /// function' LSDA (exception handling).
514   ArrayRef<uint8_t> LSDAActionTable;
515   ArrayRef<uint8_t> LSDATypeIndexTable;
516 
517   /// Vector of addresses of types referenced by LSDA.
518   LSDATypeTableTy LSDATypeTable;
519 
520   /// Vector of addresses of entries in LSDATypeTable used for indirect
521   /// addressing.
522   LSDATypeTableTy LSDATypeAddressTable;
523 
524   /// Marking for the beginning of language-specific data area for the function.
525   MCSymbol *LSDASymbol{nullptr};
526   MCSymbol *ColdLSDASymbol{nullptr};
527 
528   /// Map to discover which CFIs are attached to a given instruction offset.
529   /// Maps an instruction offset into a FrameInstructions offset.
530   /// This is only relevant to the buildCFG phase and is discarded afterwards.
531   std::multimap<uint32_t, uint32_t> OffsetToCFI;
532 
533   /// List of CFI instructions associated with the CIE (common to more than one
534   /// function and that apply before the entry basic block).
535   CFIInstrMapType CIEFrameInstructions;
536 
537   /// All compound jump tables for this function. This duplicates what's stored
538   /// in the BinaryContext, but additionally it gives quick access for all
539   /// jump tables used by this function.
540   ///
541   /// <OriginalAddress> -> <JumpTable *>
542   std::map<uint64_t, JumpTable *> JumpTables;
543 
544   /// All jump table sites in the function before CFG is built.
545   SmallVector<std::pair<uint64_t, uint64_t>, 0> JTSites;
546 
547   /// List of relocations in this function.
548   std::map<uint64_t, Relocation> Relocations;
549 
550   /// Information on function constant islands.
551   std::unique_ptr<IslandInfo> Islands;
552 
553   // Blocks are kept sorted in the layout order. If we need to change the
554   // layout (if BasicBlocksLayout stores a different order than BasicBlocks),
555   // the terminating instructions need to be modified.
556   using BasicBlockListType = SmallVector<BinaryBasicBlock *, 0>;
557   BasicBlockListType BasicBlocks;
558   BasicBlockListType DeletedBasicBlocks;
559   BasicBlockOrderType BasicBlocksLayout;
560   /// Previous layout replaced by modifyLayout
561   BasicBlockOrderType BasicBlocksPreviousLayout;
562   bool ModifiedLayout{false};
563 
564   /// BasicBlockOffsets are used during CFG construction to map from code
565   /// offsets to BinaryBasicBlocks.  Any modifications made to the CFG
566   /// after initial construction are not reflected in this data structure.
567   using BasicBlockOffset = std::pair<uint64_t, BinaryBasicBlock *>;
568   struct CompareBasicBlockOffsets {
569     bool operator()(const BasicBlockOffset &A,
570                     const BasicBlockOffset &B) const {
571       return A.first < B.first;
572     }
573   };
574   SmallVector<BasicBlockOffset, 0> BasicBlockOffsets;
575 
576   MCSymbol *ColdSymbol{nullptr};
577 
578   /// Symbol at the end of the function.
579   mutable MCSymbol *FunctionEndLabel{nullptr};
580 
581   /// Symbol at the end of the cold part of split function.
582   mutable MCSymbol *FunctionColdEndLabel{nullptr};
583 
584   /// Unique number associated with the function.
585   uint64_t FunctionNumber;
586 
587   /// Count the number of functions created.
588   static uint64_t Count;
589 
590   /// Map offsets of special instructions to addresses in the output.
591   InputOffsetToAddressMapTy InputOffsetToAddressMap;
592 
593   /// Register alternative function name.
594   void addAlternativeName(std::string NewName) {
595     Aliases.push_back(std::move(NewName));
596   }
597 
598   /// Return a label at a given \p Address in the function. If the label does
599   /// not exist - create it. Assert if the \p Address does not belong to
600   /// the function. If \p CreatePastEnd is true, then return the function
601   /// end label when the \p Address points immediately past the last byte
602   /// of the function.
603   /// NOTE: the function always returns a local (temp) symbol, even if there's
604   ///       a global symbol that corresponds to an entry at this address.
605   MCSymbol *getOrCreateLocalLabel(uint64_t Address, bool CreatePastEnd = false);
606 
607   /// Register an data entry at a given \p Offset into the function.
608   void markDataAtOffset(uint64_t Offset) {
609     if (!Islands)
610       Islands = std::make_unique<IslandInfo>();
611     Islands->DataOffsets.emplace(Offset);
612   }
613 
614   /// Register an entry point at a given \p Offset into the function.
615   void markCodeAtOffset(uint64_t Offset) {
616     if (!Islands)
617       Islands = std::make_unique<IslandInfo>();
618     Islands->CodeOffsets.emplace(Offset);
619   }
620 
621   /// Register secondary entry point at a given \p Offset into the function.
622   /// Return global symbol for use by extern function references.
623   MCSymbol *addEntryPointAtOffset(uint64_t Offset);
624 
625   /// Register an internal offset in a function referenced from outside.
626   void registerReferencedOffset(uint64_t Offset) {
627     ExternallyReferencedOffsets.emplace(Offset);
628   }
629 
630   /// True if there are references to internals of this function from data,
631   /// e.g. from jump tables.
632   bool hasInternalReference() const {
633     return !ExternallyReferencedOffsets.empty();
634   }
635 
636   /// Return an entry ID corresponding to a symbol known to belong to
637   /// the function.
638   ///
639   /// Prefer to use BinaryContext::getFunctionForSymbol(EntrySymbol, &ID)
640   /// instead of calling this function directly.
641   uint64_t getEntryIDForSymbol(const MCSymbol *EntrySymbol) const;
642 
643   /// If the function represents a secondary split function fragment, set its
644   /// parent fragment to \p BF.
645   void addParentFragment(BinaryFunction &BF) {
646     assert(this != &BF);
647     assert(IsFragment && "function must be a fragment to have a parent");
648     ParentFragments.insert(&BF);
649   }
650 
651   /// Register a child fragment for the main fragment of a split function.
652   void addFragment(BinaryFunction &BF) {
653     assert(this != &BF);
654     Fragments.insert(&BF);
655   }
656 
657   void addInstruction(uint64_t Offset, MCInst &&Instruction) {
658     Instructions.emplace(Offset, std::forward<MCInst>(Instruction));
659   }
660 
661   /// Convert CFI instructions to a standard form (remove remember/restore).
662   void normalizeCFIState();
663 
664   /// Analyze and process indirect branch \p Instruction before it is
665   /// added to Instructions list.
666   IndirectBranchType processIndirectBranch(MCInst &Instruction, unsigned Size,
667                                            uint64_t Offset,
668                                            uint64_t &TargetAddress);
669 
670   DenseMap<const MCInst *, SmallVector<MCInst *, 4>>
671   computeLocalUDChain(const MCInst *CurInstr);
672 
673   BinaryFunction &operator=(const BinaryFunction &) = delete;
674   BinaryFunction(const BinaryFunction &) = delete;
675 
676   friend class MachORewriteInstance;
677   friend class RewriteInstance;
678   friend class BinaryContext;
679   friend class DataReader;
680   friend class DataAggregator;
681 
682   static std::string buildCodeSectionName(StringRef Name,
683                                           const BinaryContext &BC);
684   static std::string buildColdCodeSectionName(StringRef Name,
685                                               const BinaryContext &BC);
686 
687   /// Creation should be handled by RewriteInstance or BinaryContext
688   BinaryFunction(const std::string &Name, BinarySection &Section,
689                  uint64_t Address, uint64_t Size, BinaryContext &BC)
690       : OriginSection(&Section), Address(Address), Size(Size), BC(BC),
691         CodeSectionName(buildCodeSectionName(Name, BC)),
692         ColdCodeSectionName(buildColdCodeSectionName(Name, BC)),
693         FunctionNumber(++Count) {
694     Symbols.push_back(BC.Ctx->getOrCreateSymbol(Name));
695   }
696 
697   /// This constructor is used to create an injected function
698   BinaryFunction(const std::string &Name, BinaryContext &BC, bool IsSimple)
699       : Address(0), Size(0), BC(BC), IsSimple(IsSimple),
700         CodeSectionName(buildCodeSectionName(Name, BC)),
701         ColdCodeSectionName(buildColdCodeSectionName(Name, BC)),
702         FunctionNumber(++Count) {
703     Symbols.push_back(BC.Ctx->getOrCreateSymbol(Name));
704     IsInjected = true;
705   }
706 
707   /// Clear state of the function that could not be disassembled or if its
708   /// disassembled state was later invalidated.
709   void clearDisasmState();
710 
711   /// Release memory allocated for CFG and instructions.
712   /// We still keep basic blocks for address translation/mapping purposes.
713   void releaseCFG() {
714     for (BinaryBasicBlock *BB : BasicBlocks)
715       BB->releaseCFG();
716     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
717       BB->releaseCFG();
718 
719     clearList(CallSites);
720     clearList(ColdCallSites);
721     clearList(LSDATypeTable);
722     clearList(LSDATypeAddressTable);
723 
724     clearList(LabelToBB);
725 
726     if (!isMultiEntry())
727       clearList(Labels);
728 
729     clearList(FrameInstructions);
730     clearList(FrameRestoreEquivalents);
731   }
732 
733 public:
734   BinaryFunction(BinaryFunction &&) = default;
735 
736   using iterator = pointee_iterator<BasicBlockListType::iterator>;
737   using const_iterator = pointee_iterator<BasicBlockListType::const_iterator>;
738   using reverse_iterator =
739       pointee_iterator<BasicBlockListType::reverse_iterator>;
740   using const_reverse_iterator =
741       pointee_iterator<BasicBlockListType::const_reverse_iterator>;
742 
743   typedef BasicBlockOrderType::iterator order_iterator;
744   typedef BasicBlockOrderType::const_iterator const_order_iterator;
745   typedef BasicBlockOrderType::reverse_iterator reverse_order_iterator;
746   typedef BasicBlockOrderType::const_reverse_iterator
747       const_reverse_order_iterator;
748 
749   // CFG iterators.
750   iterator                 begin()       { return BasicBlocks.begin(); }
751   const_iterator           begin() const { return BasicBlocks.begin(); }
752   iterator                 end  ()       { return BasicBlocks.end();   }
753   const_iterator           end  () const { return BasicBlocks.end();   }
754 
755   reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
756   const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
757   reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
758   const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
759 
760   size_t                    size() const { return BasicBlocks.size();}
761   bool                     empty() const { return BasicBlocks.empty(); }
762   const BinaryBasicBlock &front() const  { return *BasicBlocks.front(); }
763         BinaryBasicBlock &front()        { return *BasicBlocks.front(); }
764   const BinaryBasicBlock & back() const  { return *BasicBlocks.back(); }
765         BinaryBasicBlock & back()        { return *BasicBlocks.back(); }
766   inline iterator_range<iterator> blocks() {
767     return iterator_range<iterator>(begin(), end());
768   }
769   inline iterator_range<const_iterator> blocks() const {
770     return iterator_range<const_iterator>(begin(), end());
771   }
772 
773   // Iterators by pointer.
774   BasicBlockListType::iterator pbegin()  { return BasicBlocks.begin(); }
775   BasicBlockListType::iterator pend()    { return BasicBlocks.end(); }
776 
777   order_iterator       layout_begin()    { return BasicBlocksLayout.begin(); }
778   const_order_iterator layout_begin()    const
779                                          { return BasicBlocksLayout.begin(); }
780   order_iterator       layout_end()      { return BasicBlocksLayout.end(); }
781   const_order_iterator layout_end()      const
782                                          { return BasicBlocksLayout.end(); }
783   reverse_order_iterator       layout_rbegin()
784                                          { return BasicBlocksLayout.rbegin(); }
785   const_reverse_order_iterator layout_rbegin() const
786                                          { return BasicBlocksLayout.rbegin(); }
787   reverse_order_iterator       layout_rend()
788                                          { return BasicBlocksLayout.rend(); }
789   const_reverse_order_iterator layout_rend()   const
790                                          { return BasicBlocksLayout.rend(); }
791   size_t   layout_size()  const { return BasicBlocksLayout.size(); }
792   bool     layout_empty() const { return BasicBlocksLayout.empty(); }
793   const BinaryBasicBlock *layout_front() const
794                                          { return BasicBlocksLayout.front(); }
795         BinaryBasicBlock *layout_front() { return BasicBlocksLayout.front(); }
796   const BinaryBasicBlock *layout_back()  const
797                                          { return BasicBlocksLayout.back(); }
798         BinaryBasicBlock *layout_back()  { return BasicBlocksLayout.back(); }
799 
800   inline iterator_range<order_iterator> layout() {
801     return iterator_range<order_iterator>(BasicBlocksLayout.begin(),
802                                           BasicBlocksLayout.end());
803   }
804 
805   inline iterator_range<const_order_iterator> layout() const {
806     return iterator_range<const_order_iterator>(BasicBlocksLayout.begin(),
807                                                 BasicBlocksLayout.end());
808   }
809 
810   inline iterator_range<reverse_order_iterator> rlayout() {
811     return iterator_range<reverse_order_iterator>(BasicBlocksLayout.rbegin(),
812                                                   BasicBlocksLayout.rend());
813   }
814 
815   inline iterator_range<const_reverse_order_iterator> rlayout() const {
816     return iterator_range<const_reverse_order_iterator>(
817         BasicBlocksLayout.rbegin(), BasicBlocksLayout.rend());
818   }
819 
820   cfi_iterator        cie_begin()       { return CIEFrameInstructions.begin(); }
821   const_cfi_iterator  cie_begin() const { return CIEFrameInstructions.begin(); }
822   cfi_iterator        cie_end()         { return CIEFrameInstructions.end(); }
823   const_cfi_iterator  cie_end()   const { return CIEFrameInstructions.end(); }
824   bool                cie_empty() const { return CIEFrameInstructions.empty(); }
825 
826   inline iterator_range<cfi_iterator> cie() {
827     return iterator_range<cfi_iterator>(cie_begin(), cie_end());
828   }
829   inline iterator_range<const_cfi_iterator> cie() const {
830     return iterator_range<const_cfi_iterator>(cie_begin(), cie_end());
831   }
832 
833   /// Iterate over all jump tables associated with this function.
834   iterator_range<std::map<uint64_t, JumpTable *>::const_iterator>
835   jumpTables() const {
836     return make_range(JumpTables.begin(), JumpTables.end());
837   }
838 
839   /// Returns the raw binary encoding of this function.
840   ErrorOr<ArrayRef<uint8_t>> getData() const;
841 
842   BinaryFunction &updateState(BinaryFunction::State State) {
843     CurrentState = State;
844     return *this;
845   }
846 
847   /// Update layout of basic blocks used for output.
848   void updateBasicBlockLayout(BasicBlockOrderType &NewLayout) {
849     BasicBlocksPreviousLayout = BasicBlocksLayout;
850 
851     if (NewLayout != BasicBlocksLayout) {
852       ModifiedLayout = true;
853       BasicBlocksLayout.clear();
854       BasicBlocksLayout.swap(NewLayout);
855     }
856   }
857 
858   /// Recompute landing pad information for the function and all its blocks.
859   void recomputeLandingPads();
860 
861   /// Return current basic block layout.
862   const BasicBlockOrderType &getLayout() const { return BasicBlocksLayout; }
863 
864   /// Return a list of basic blocks sorted using DFS and update layout indices
865   /// using the same order. Does not modify the current layout.
866   BasicBlockOrderType dfs() const;
867 
868   /// Find the loops in the CFG of the function and store information about
869   /// them.
870   void calculateLoopInfo();
871 
872   /// Calculate missed macro-fusion opportunities and update BinaryContext
873   /// stats.
874   void calculateMacroOpFusionStats();
875 
876   /// Returns if loop detection has been run for this function.
877   bool hasLoopInfo() const { return BLI != nullptr; }
878 
879   const BinaryLoopInfo &getLoopInfo() { return *BLI.get(); }
880 
881   bool isLoopFree() {
882     if (!hasLoopInfo())
883       calculateLoopInfo();
884     return BLI->empty();
885   }
886 
887   /// Print loop information about the function.
888   void printLoopInfo(raw_ostream &OS) const;
889 
890   /// View CFG in graphviz program
891   void viewGraph() const;
892 
893   /// Dump CFG in graphviz format
894   void dumpGraph(raw_ostream &OS) const;
895 
896   /// Dump CFG in graphviz format to file.
897   void dumpGraphToFile(std::string Filename) const;
898 
899   /// Dump CFG in graphviz format to a file with a filename that is derived
900   /// from the function name and Annotation strings.  Useful for dumping the
901   /// CFG after an optimization pass.
902   void dumpGraphForPass(std::string Annotation = "") const;
903 
904   /// Return BinaryContext for the function.
905   const BinaryContext &getBinaryContext() const { return BC; }
906 
907   /// Return BinaryContext for the function.
908   BinaryContext &getBinaryContext() { return BC; }
909 
910   /// Attempt to validate CFG invariants.
911   bool validateCFG() const;
912 
913   BinaryBasicBlock *getBasicBlockForLabel(const MCSymbol *Label) {
914     auto I = LabelToBB.find(Label);
915     return I == LabelToBB.end() ? nullptr : I->second;
916   }
917 
918   const BinaryBasicBlock *getBasicBlockForLabel(const MCSymbol *Label) const {
919     auto I = LabelToBB.find(Label);
920     return I == LabelToBB.end() ? nullptr : I->second;
921   }
922 
923   /// Returns the basic block after the given basic block in the layout or
924   /// nullptr the last basic block is given.
925   const BinaryBasicBlock *getBasicBlockAfter(const BinaryBasicBlock *BB,
926                                              bool IgnoreSplits = true) const {
927     return const_cast<BinaryFunction *>(this)->getBasicBlockAfter(BB,
928                                                                   IgnoreSplits);
929   }
930 
931   BinaryBasicBlock *getBasicBlockAfter(const BinaryBasicBlock *BB,
932                                        bool IgnoreSplits = true) {
933     for (auto I = layout_begin(), E = layout_end(); I != E; ++I) {
934       auto Next = std::next(I);
935       if (*I == BB && Next != E) {
936         return (IgnoreSplits || (*I)->isCold() == (*Next)->isCold()) ? *Next
937                                                                      : nullptr;
938       }
939     }
940     return nullptr;
941   }
942 
943   /// Retrieve the landing pad BB associated with invoke instruction \p Invoke
944   /// that is in \p BB. Return nullptr if none exists
945   BinaryBasicBlock *getLandingPadBBFor(const BinaryBasicBlock &BB,
946                                        const MCInst &InvokeInst) const {
947     assert(BC.MIB->isInvoke(InvokeInst) && "must be invoke instruction");
948     const Optional<MCPlus::MCLandingPad> LP = BC.MIB->getEHInfo(InvokeInst);
949     if (LP && LP->first) {
950       BinaryBasicBlock *LBB = BB.getLandingPad(LP->first);
951       assert(LBB && "Landing pad should be defined");
952       return LBB;
953     }
954     return nullptr;
955   }
956 
957   /// Return instruction at a given offset in the function. Valid before
958   /// CFG is constructed or while instruction offsets are available in CFG.
959   MCInst *getInstructionAtOffset(uint64_t Offset);
960 
961   const MCInst *getInstructionAtOffset(uint64_t Offset) const {
962     return const_cast<BinaryFunction *>(this)->getInstructionAtOffset(Offset);
963   }
964 
965   /// Return jump table that covers a given \p Address in memory.
966   JumpTable *getJumpTableContainingAddress(uint64_t Address) {
967     auto JTI = JumpTables.upper_bound(Address);
968     if (JTI == JumpTables.begin())
969       return nullptr;
970     --JTI;
971     if (JTI->first + JTI->second->getSize() > Address)
972       return JTI->second;
973     if (JTI->second->getSize() == 0 && JTI->first == Address)
974       return JTI->second;
975     return nullptr;
976   }
977 
978   const JumpTable *getJumpTableContainingAddress(uint64_t Address) const {
979     return const_cast<BinaryFunction *>(this)->getJumpTableContainingAddress(
980         Address);
981   }
982 
983   /// Return the name of the function if the function has just one name.
984   /// If the function has multiple names - return one followed
985   /// by "(*#<numnames>)".
986   ///
987   /// We should use getPrintName() for diagnostics and use
988   /// hasName() to match function name against a given string.
989   ///
990   /// NOTE: for disambiguating names of local symbols we use the following
991   ///       naming schemes:
992   ///           primary:     <function>/<id>
993   ///           alternative: <function>/<file>/<id2>
994   std::string getPrintName() const {
995     const size_t NumNames = Symbols.size() + Aliases.size();
996     return NumNames == 1
997                ? getOneName().str()
998                : (getOneName().str() + "(*" + std::to_string(NumNames) + ")");
999   }
1000 
1001   /// The function may have many names. For that reason, we avoid having
1002   /// getName() method as most of the time the user needs a different
1003   /// interface, such as forEachName(), hasName(), hasNameRegex(), etc.
1004   /// In some cases though, we need just a name uniquely identifying
1005   /// the function, and that's what this method is for.
1006   StringRef getOneName() const { return Symbols[0]->getName(); }
1007 
1008   /// Return the name of the function as getPrintName(), but also trying
1009   /// to demangle it.
1010   std::string getDemangledName() const;
1011 
1012   /// Call \p Callback for every name of this function as long as the Callback
1013   /// returns false. Stop if Callback returns true or all names have been used.
1014   /// Return the name for which the Callback returned true if any.
1015   template <typename FType>
1016   Optional<StringRef> forEachName(FType Callback) const {
1017     for (MCSymbol *Symbol : Symbols)
1018       if (Callback(Symbol->getName()))
1019         return Symbol->getName();
1020 
1021     for (const std::string &Name : Aliases)
1022       if (Callback(StringRef(Name)))
1023         return StringRef(Name);
1024 
1025     return NoneType();
1026   }
1027 
1028   /// Check if (possibly one out of many) function name matches the given
1029   /// string. Use this member function instead of direct name comparison.
1030   bool hasName(const std::string &FunctionName) const {
1031     auto Res =
1032         forEachName([&](StringRef Name) { return Name == FunctionName; });
1033     return Res.hasValue();
1034   }
1035 
1036   /// Check if any of function names matches the given regex.
1037   Optional<StringRef> hasNameRegex(const StringRef NameRegex) const;
1038 
1039   /// Check if any of restored function names matches the given regex.
1040   /// Restored name means stripping BOLT-added suffixes like "/1",
1041   Optional<StringRef> hasRestoredNameRegex(const StringRef NameRegex) const;
1042 
1043   /// Return a vector of all possible names for the function.
1044   const std::vector<StringRef> getNames() const {
1045     std::vector<StringRef> AllNames;
1046     forEachName([&AllNames](StringRef Name) {
1047       AllNames.push_back(Name);
1048       return false;
1049     });
1050 
1051     return AllNames;
1052   }
1053 
1054   /// Return a state the function is in (see BinaryFunction::State definition
1055   /// for description).
1056   State getState() const { return CurrentState; }
1057 
1058   /// Return true if function has a control flow graph available.
1059   bool hasCFG() const {
1060     return getState() == State::CFG || getState() == State::CFG_Finalized ||
1061            getState() == State::EmittedCFG;
1062   }
1063 
1064   /// Return true if the function state implies that it includes instructions.
1065   bool hasInstructions() const {
1066     return getState() == State::Disassembled || hasCFG();
1067   }
1068 
1069   bool isEmitted() const {
1070     return getState() == State::EmittedCFG || getState() == State::Emitted;
1071   }
1072 
1073   /// Return the section in the input binary this function originated from or
1074   /// nullptr if the function did not originate from the file.
1075   BinarySection *getOriginSection() const { return OriginSection; }
1076 
1077   void setOriginSection(BinarySection *Section) { OriginSection = Section; }
1078 
1079   /// Return true if the function did not originate from the primary input file.
1080   bool isInjected() const { return IsInjected; }
1081 
1082   /// Return original address of the function (or offset from base for PIC).
1083   uint64_t getAddress() const { return Address; }
1084 
1085   uint64_t getOutputAddress() const { return OutputAddress; }
1086 
1087   uint64_t getOutputSize() const { return OutputSize; }
1088 
1089   /// Does this function have a valid streaming order index?
1090   bool hasValidIndex() const { return Index != -1U; }
1091 
1092   /// Get the streaming order index for this function.
1093   uint32_t getIndex() const { return Index; }
1094 
1095   /// Set the streaming order index for this function.
1096   void setIndex(uint32_t Idx) {
1097     assert(!hasValidIndex());
1098     Index = Idx;
1099   }
1100 
1101   /// Return offset of the function body in the binary file.
1102   uint64_t getFileOffset() const { return FileOffset; }
1103 
1104   /// Return (original) byte size of the function.
1105   uint64_t getSize() const { return Size; }
1106 
1107   /// Return the maximum size the body of the function could have.
1108   uint64_t getMaxSize() const { return MaxSize; }
1109 
1110   /// Return the number of emitted instructions for this function.
1111   uint32_t getNumNonPseudos() const {
1112     uint32_t N = 0;
1113     for (BinaryBasicBlock *const &BB : layout())
1114       N += BB->getNumNonPseudos();
1115     return N;
1116   }
1117 
1118   /// Return MC symbol associated with the function.
1119   /// All references to the function should use this symbol.
1120   MCSymbol *getSymbol() { return Symbols[0]; }
1121 
1122   /// Return MC symbol associated with the function (const version).
1123   /// All references to the function should use this symbol.
1124   const MCSymbol *getSymbol() const { return Symbols[0]; }
1125 
1126   /// Return a list of symbols associated with the main entry of the function.
1127   SymbolListTy &getSymbols() { return Symbols; }
1128   const SymbolListTy &getSymbols() const { return Symbols; }
1129 
1130   /// If a local symbol \p BBLabel corresponds to a basic block that is a
1131   /// secondary entry point into the function, then return a global symbol
1132   /// that represents the secondary entry point. Otherwise return nullptr.
1133   MCSymbol *getSecondaryEntryPointSymbol(const MCSymbol *BBLabel) const {
1134     auto I = SecondaryEntryPoints.find(BBLabel);
1135     if (I == SecondaryEntryPoints.end())
1136       return nullptr;
1137 
1138     return I->second;
1139   }
1140 
1141   /// If the basic block serves as a secondary entry point to the function,
1142   /// return a global symbol representing the entry. Otherwise return nullptr.
1143   MCSymbol *getSecondaryEntryPointSymbol(const BinaryBasicBlock &BB) const {
1144     return getSecondaryEntryPointSymbol(BB.getLabel());
1145   }
1146 
1147   /// Return true if the basic block is an entry point into the function
1148   /// (either primary or secondary).
1149   bool isEntryPoint(const BinaryBasicBlock &BB) const {
1150     if (&BB == BasicBlocks.front())
1151       return true;
1152     return getSecondaryEntryPointSymbol(BB);
1153   }
1154 
1155   /// Return MC symbol corresponding to an enumerated entry for multiple-entry
1156   /// functions.
1157   MCSymbol *getSymbolForEntryID(uint64_t EntryNum);
1158   const MCSymbol *getSymbolForEntryID(uint64_t EntryNum) const {
1159     return const_cast<BinaryFunction *>(this)->getSymbolForEntryID(EntryNum);
1160   }
1161 
1162   using EntryPointCallbackTy = function_ref<bool(uint64_t, const MCSymbol *)>;
1163 
1164   /// Invoke \p Callback function for every entry point in the function starting
1165   /// with the main entry and using entries in the ascending address order.
1166   /// Stop calling the function after false is returned by the callback.
1167   ///
1168   /// Pass an offset of the entry point in the input binary and a corresponding
1169   /// global symbol to the callback function.
1170   ///
1171   /// Return true of all callbacks returned true, false otherwise.
1172   bool forEachEntryPoint(EntryPointCallbackTy Callback) const;
1173 
1174   MCSymbol *getColdSymbol() {
1175     if (ColdSymbol)
1176       return ColdSymbol;
1177 
1178     ColdSymbol = BC.Ctx->getOrCreateSymbol(
1179         NameResolver::append(getSymbol()->getName(), ".cold.0"));
1180 
1181     return ColdSymbol;
1182   }
1183 
1184   /// Return MC symbol associated with the end of the function.
1185   MCSymbol *getFunctionEndLabel() const {
1186     assert(BC.Ctx && "cannot be called with empty context");
1187     if (!FunctionEndLabel) {
1188       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1189       FunctionEndLabel = BC.Ctx->createNamedTempSymbol("func_end");
1190     }
1191     return FunctionEndLabel;
1192   }
1193 
1194   /// Return MC symbol associated with the end of the cold part of the function.
1195   MCSymbol *getFunctionColdEndLabel() const {
1196     if (!FunctionColdEndLabel) {
1197       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1198       FunctionColdEndLabel = BC.Ctx->createNamedTempSymbol("func_cold_end");
1199     }
1200     return FunctionColdEndLabel;
1201   }
1202 
1203   /// Return a label used to identify where the constant island was emitted
1204   /// (AArch only). This is used to update the symbol table accordingly,
1205   /// emitting data marker symbols as required by the ABI.
1206   MCSymbol *getFunctionConstantIslandLabel() const {
1207     assert(Islands && "function expected to have constant islands");
1208 
1209     if (!Islands->FunctionConstantIslandLabel) {
1210       Islands->FunctionConstantIslandLabel =
1211           BC.Ctx->createNamedTempSymbol("func_const_island");
1212     }
1213     return Islands->FunctionConstantIslandLabel;
1214   }
1215 
1216   MCSymbol *getFunctionColdConstantIslandLabel() const {
1217     assert(Islands && "function expected to have constant islands");
1218 
1219     if (!Islands->FunctionColdConstantIslandLabel) {
1220       Islands->FunctionColdConstantIslandLabel =
1221           BC.Ctx->createNamedTempSymbol("func_cold_const_island");
1222     }
1223     return Islands->FunctionColdConstantIslandLabel;
1224   }
1225 
1226   /// Return true if this is a function representing a PLT entry.
1227   bool isPLTFunction() const { return PLTSymbol != nullptr; }
1228 
1229   /// Return PLT function reference symbol for PLT functions and nullptr for
1230   /// non-PLT functions.
1231   const MCSymbol *getPLTSymbol() const { return PLTSymbol; }
1232 
1233   /// Set function PLT reference symbol for PLT functions.
1234   void setPLTSymbol(const MCSymbol *Symbol) {
1235     assert(Size == 0 && "function size should be 0 for PLT functions");
1236     PLTSymbol = Symbol;
1237     IsPseudo = true;
1238   }
1239 
1240   /// Update output values of the function based on the final \p Layout.
1241   void updateOutputValues(const MCAsmLayout &Layout);
1242 
1243   /// Return mapping of input to output addresses. Most users should call
1244   /// translateInputToOutputAddress() for address translation.
1245   InputOffsetToAddressMapTy &getInputOffsetToAddressMap() {
1246     assert(isEmitted() && "cannot use address mapping before code emission");
1247     return InputOffsetToAddressMap;
1248   }
1249 
1250   void addRelocationAArch64(uint64_t Offset, MCSymbol *Symbol, uint64_t RelType,
1251                             uint64_t Addend, uint64_t Value, bool IsCI) {
1252     std::map<uint64_t, Relocation> &Rels =
1253         (IsCI) ? Islands->Relocations : Relocations;
1254     switch (RelType) {
1255     case ELF::R_AARCH64_ABS64:
1256     case ELF::R_AARCH64_ABS32:
1257     case ELF::R_AARCH64_ABS16:
1258     case ELF::R_AARCH64_ADD_ABS_LO12_NC:
1259     case ELF::R_AARCH64_ADR_GOT_PAGE:
1260     case ELF::R_AARCH64_ADR_PREL_LO21:
1261     case ELF::R_AARCH64_ADR_PREL_PG_HI21:
1262     case ELF::R_AARCH64_ADR_PREL_PG_HI21_NC:
1263     case ELF::R_AARCH64_LD64_GOT_LO12_NC:
1264     case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
1265     case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
1266     case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
1267     case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
1268     case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
1269     case ELF::R_AARCH64_TLSDESC_ADD_LO12:
1270     case ELF::R_AARCH64_TLSDESC_ADR_PAGE21:
1271     case ELF::R_AARCH64_TLSDESC_ADR_PREL21:
1272     case ELF::R_AARCH64_TLSDESC_LD64_LO12:
1273     case ELF::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
1274     case ELF::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1275     case ELF::R_AARCH64_MOVW_UABS_G0:
1276     case ELF::R_AARCH64_MOVW_UABS_G0_NC:
1277     case ELF::R_AARCH64_MOVW_UABS_G1:
1278     case ELF::R_AARCH64_MOVW_UABS_G1_NC:
1279     case ELF::R_AARCH64_MOVW_UABS_G2:
1280     case ELF::R_AARCH64_MOVW_UABS_G2_NC:
1281     case ELF::R_AARCH64_MOVW_UABS_G3:
1282       Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
1283       return;
1284     case ELF::R_AARCH64_CALL26:
1285     case ELF::R_AARCH64_JUMP26:
1286     case ELF::R_AARCH64_TSTBR14:
1287     case ELF::R_AARCH64_CONDBR19:
1288     case ELF::R_AARCH64_TLSDESC_CALL:
1289     case ELF::R_AARCH64_TLSLE_ADD_TPREL_HI12:
1290     case ELF::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
1291       return;
1292     default:
1293       llvm_unreachable("Unexpected AArch64 relocation type in code");
1294     }
1295   }
1296 
1297   void addRelocationX86(uint64_t Offset, MCSymbol *Symbol, uint64_t RelType,
1298                         uint64_t Addend, uint64_t Value) {
1299     switch (RelType) {
1300     case ELF::R_X86_64_8:
1301     case ELF::R_X86_64_16:
1302     case ELF::R_X86_64_32:
1303     case ELF::R_X86_64_32S:
1304     case ELF::R_X86_64_64:
1305     case ELF::R_X86_64_PC8:
1306     case ELF::R_X86_64_PC32:
1307     case ELF::R_X86_64_PC64:
1308       Relocations[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
1309       return;
1310     case ELF::R_X86_64_PLT32:
1311     case ELF::R_X86_64_GOTPCRELX:
1312     case ELF::R_X86_64_REX_GOTPCRELX:
1313     case ELF::R_X86_64_GOTPCREL:
1314     case ELF::R_X86_64_TPOFF32:
1315     case ELF::R_X86_64_GOTTPOFF:
1316       return;
1317     default:
1318       llvm_unreachable("Unexpected x86 relocation type in code");
1319     }
1320   }
1321 
1322   /// Register relocation type \p RelType at a given \p Address in the function
1323   /// against \p Symbol.
1324   /// Assert if the \p Address is not inside this function.
1325   void addRelocation(uint64_t Address, MCSymbol *Symbol, uint64_t RelType,
1326                      uint64_t Addend, uint64_t Value) {
1327     assert(Address >= getAddress() && Address < getAddress() + getMaxSize() &&
1328            "address is outside of the function");
1329     uint64_t Offset = Address - getAddress();
1330     if (BC.isAArch64()) {
1331       return addRelocationAArch64(Offset, Symbol, RelType, Addend, Value,
1332                                   isInConstantIsland(Address));
1333     }
1334 
1335     return addRelocationX86(Offset, Symbol, RelType, Addend, Value);
1336   }
1337 
1338   /// Return the name of the section this function originated from.
1339   Optional<StringRef> getOriginSectionName() const {
1340     if (!OriginSection)
1341       return NoneType();
1342     return OriginSection->getName();
1343   }
1344 
1345   /// Return internal section name for this function.
1346   StringRef getCodeSectionName() const { return StringRef(CodeSectionName); }
1347 
1348   /// Assign a code section name to the function.
1349   void setCodeSectionName(StringRef Name) {
1350     CodeSectionName = std::string(Name);
1351   }
1352 
1353   /// Get output code section.
1354   ErrorOr<BinarySection &> getCodeSection() const {
1355     return BC.getUniqueSectionByName(getCodeSectionName());
1356   }
1357 
1358   /// Return cold code section name for the function.
1359   StringRef getColdCodeSectionName() const {
1360     return StringRef(ColdCodeSectionName);
1361   }
1362 
1363   /// Assign a section name for the cold part of the function.
1364   void setColdCodeSectionName(StringRef Name) {
1365     ColdCodeSectionName = std::string(Name);
1366   }
1367 
1368   /// Get output code section for cold code of this function.
1369   ErrorOr<BinarySection &> getColdCodeSection() const {
1370     return BC.getUniqueSectionByName(getColdCodeSectionName());
1371   }
1372 
1373   /// Return true iif the function will halt execution on entry.
1374   bool trapsOnEntry() const { return TrapsOnEntry; }
1375 
1376   /// Make the function always trap on entry. Other than the trap instruction,
1377   /// the function body will be empty.
1378   void setTrapOnEntry();
1379 
1380   /// Return true if the function could be correctly processed.
1381   bool isSimple() const { return IsSimple; }
1382 
1383   /// Return true if the function should be ignored for optimization purposes.
1384   bool isIgnored() const { return IsIgnored; }
1385 
1386   /// Return true if the function should not be disassembled, emitted, or
1387   /// otherwise processed.
1388   bool isPseudo() const { return IsPseudo; }
1389 
1390   /// Return true if the function contains a jump table with entries pointing
1391   /// to split fragments.
1392   bool hasSplitJumpTable() const { return HasSplitJumpTable; }
1393 
1394   /// Return true if all CFG edges have local successors.
1395   bool hasCanonicalCFG() const { return HasCanonicalCFG; }
1396 
1397   /// Return true if the original function code has all necessary relocations
1398   /// to track addresses of functions emitted to new locations.
1399   bool hasExternalRefRelocations() const { return HasExternalRefRelocations; }
1400 
1401   /// Return true if the function has instruction(s) with unknown control flow.
1402   bool hasUnknownControlFlow() const { return HasUnknownControlFlow; }
1403 
1404   /// Return true if the function body is non-contiguous.
1405   bool isSplit() const {
1406     return isSimple() && layout_size() &&
1407            layout_front()->isCold() != layout_back()->isCold();
1408   }
1409 
1410   bool shouldPreserveNops() const { return PreserveNops; }
1411 
1412   /// Return true if the function has exception handling tables.
1413   bool hasEHRanges() const { return HasEHRanges; }
1414 
1415   /// Return true if the function uses DW_CFA_GNU_args_size CFIs.
1416   bool usesGnuArgsSize() const { return UsesGnuArgsSize; }
1417 
1418   /// Return true if the function has more than one entry point.
1419   bool isMultiEntry() const { return !SecondaryEntryPoints.empty(); }
1420 
1421   /// Return true if the function might have a profile available externally,
1422   /// but not yet populated into the function.
1423   bool hasProfileAvailable() const { return HasProfileAvailable; }
1424 
1425   bool hasMemoryProfile() const { return HasMemoryProfile; }
1426 
1427   /// Return true if the body of the function was merged into another function.
1428   bool isFolded() const { return FoldedIntoFunction != nullptr; }
1429 
1430   /// If this function was folded, return the function it was folded into.
1431   BinaryFunction *getFoldedIntoFunction() const { return FoldedIntoFunction; }
1432 
1433   /// Return true if the function uses jump tables.
1434   bool hasJumpTables() const { return !JumpTables.empty(); }
1435 
1436   /// Return true if the function has SDT marker
1437   bool hasSDTMarker() const { return HasSDTMarker; }
1438 
1439   /// Return true if the function has Pseudo Probe
1440   bool hasPseudoProbe() const { return HasPseudoProbe; }
1441 
1442   /// Return true if the original entry point was patched.
1443   bool isPatched() const { return IsPatched; }
1444 
1445   const JumpTable *getJumpTable(const MCInst &Inst) const {
1446     const uint64_t Address = BC.MIB->getJumpTable(Inst);
1447     return getJumpTableContainingAddress(Address);
1448   }
1449 
1450   JumpTable *getJumpTable(const MCInst &Inst) {
1451     const uint64_t Address = BC.MIB->getJumpTable(Inst);
1452     return getJumpTableContainingAddress(Address);
1453   }
1454 
1455   const MCSymbol *getPersonalityFunction() const { return PersonalityFunction; }
1456 
1457   uint8_t getPersonalityEncoding() const { return PersonalityEncoding; }
1458 
1459   const CallSitesType &getCallSites() const { return CallSites; }
1460 
1461   const CallSitesType &getColdCallSites() const { return ColdCallSites; }
1462 
1463   const ArrayRef<uint8_t> getLSDAActionTable() const { return LSDAActionTable; }
1464 
1465   const LSDATypeTableTy &getLSDATypeTable() const { return LSDATypeTable; }
1466 
1467   const LSDATypeTableTy &getLSDATypeAddressTable() const {
1468     return LSDATypeAddressTable;
1469   }
1470 
1471   const ArrayRef<uint8_t> getLSDATypeIndexTable() const {
1472     return LSDATypeIndexTable;
1473   }
1474 
1475   const LabelsMapType &getLabels() const { return Labels; }
1476 
1477   IslandInfo &getIslandInfo() {
1478     assert(Islands && "function expected to have constant islands");
1479     return *Islands;
1480   }
1481 
1482   const IslandInfo &getIslandInfo() const {
1483     assert(Islands && "function expected to have constant islands");
1484     return *Islands;
1485   }
1486 
1487   /// Return true if the function has CFI instructions
1488   bool hasCFI() const {
1489     return !FrameInstructions.empty() || !CIEFrameInstructions.empty();
1490   }
1491 
1492   /// Return unique number associated with the function.
1493   uint64_t getFunctionNumber() const { return FunctionNumber; }
1494 
1495   /// Return true if the given address \p PC is inside the function body.
1496   bool containsAddress(uint64_t PC, bool UseMaxSize = false) const {
1497     if (UseMaxSize)
1498       return Address <= PC && PC < Address + MaxSize;
1499     return Address <= PC && PC < Address + Size;
1500   }
1501 
1502   /// Create a basic block at a given \p Offset in the
1503   /// function.
1504   /// If \p DeriveAlignment is true, set the alignment of the block based
1505   /// on the alignment of the existing offset.
1506   /// The new block is not inserted into the CFG.  The client must
1507   /// use insertBasicBlocks to add any new blocks to the CFG.
1508   std::unique_ptr<BinaryBasicBlock>
1509   createBasicBlock(uint64_t Offset, MCSymbol *Label = nullptr,
1510                    bool DeriveAlignment = false) {
1511     assert(BC.Ctx && "cannot be called with empty context");
1512     if (!Label) {
1513       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1514       Label = BC.Ctx->createNamedTempSymbol("BB");
1515     }
1516     auto BB = std::unique_ptr<BinaryBasicBlock>(
1517         new BinaryBasicBlock(this, Label, Offset));
1518 
1519     if (DeriveAlignment) {
1520       uint64_t DerivedAlignment = Offset & (1 + ~Offset);
1521       BB->setAlignment(std::min(DerivedAlignment, uint64_t(32)));
1522     }
1523 
1524     LabelToBB[Label] = BB.get();
1525 
1526     return BB;
1527   }
1528 
1529   /// Create a basic block at a given \p Offset in the
1530   /// function and append it to the end of list of blocks.
1531   /// If \p DeriveAlignment is true, set the alignment of the block based
1532   /// on the alignment of the existing offset.
1533   ///
1534   /// Returns NULL if basic block already exists at the \p Offset.
1535   BinaryBasicBlock *addBasicBlock(uint64_t Offset, MCSymbol *Label = nullptr,
1536                                   bool DeriveAlignment = false) {
1537     assert((CurrentState == State::CFG || !getBasicBlockAtOffset(Offset)) &&
1538            "basic block already exists in pre-CFG state");
1539 
1540     if (!Label) {
1541       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1542       Label = BC.Ctx->createNamedTempSymbol("BB");
1543     }
1544     std::unique_ptr<BinaryBasicBlock> BBPtr =
1545         createBasicBlock(Offset, Label, DeriveAlignment);
1546     BasicBlocks.emplace_back(BBPtr.release());
1547 
1548     BinaryBasicBlock *BB = BasicBlocks.back();
1549     BB->setIndex(BasicBlocks.size() - 1);
1550 
1551     if (CurrentState == State::Disassembled) {
1552       BasicBlockOffsets.emplace_back(Offset, BB);
1553     } else if (CurrentState == State::CFG) {
1554       BB->setLayoutIndex(layout_size());
1555       BasicBlocksLayout.emplace_back(BB);
1556     }
1557 
1558     assert(CurrentState == State::CFG ||
1559            (std::is_sorted(BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
1560                            CompareBasicBlockOffsets()) &&
1561             std::is_sorted(begin(), end())));
1562 
1563     return BB;
1564   }
1565 
1566   /// Add basic block \BB as an entry point to the function. Return global
1567   /// symbol associated with the entry.
1568   MCSymbol *addEntryPoint(const BinaryBasicBlock &BB);
1569 
1570   /// Mark all blocks that are unreachable from a root (entry point
1571   /// or landing pad) as invalid.
1572   void markUnreachableBlocks();
1573 
1574   /// Rebuilds BBs layout, ignoring dead BBs. Returns the number of removed
1575   /// BBs and the removed number of bytes of code.
1576   std::pair<unsigned, uint64_t> eraseInvalidBBs();
1577 
1578   /// Get the relative order between two basic blocks in the original
1579   /// layout.  The result is > 0 if B occurs before A and < 0 if B
1580   /// occurs after A.  If A and B are the same block, the result is 0.
1581   signed getOriginalLayoutRelativeOrder(const BinaryBasicBlock *A,
1582                                         const BinaryBasicBlock *B) const {
1583     return getIndex(A) - getIndex(B);
1584   }
1585 
1586   /// Insert the BBs contained in NewBBs into the basic blocks for this
1587   /// function. Update the associated state of all blocks as needed, i.e.
1588   /// BB offsets and BB indices. The new BBs are inserted after Start.
1589   /// This operation could affect fallthrough branches for Start.
1590   ///
1591   void
1592   insertBasicBlocks(BinaryBasicBlock *Start,
1593                     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
1594                     const bool UpdateLayout = true,
1595                     const bool UpdateCFIState = true,
1596                     const bool RecomputeLandingPads = true);
1597 
1598   iterator insertBasicBlocks(
1599       iterator StartBB, std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
1600       const bool UpdateLayout = true, const bool UpdateCFIState = true,
1601       const bool RecomputeLandingPads = true);
1602 
1603   /// Update the basic block layout for this function.  The BBs from
1604   /// [Start->Index, Start->Index + NumNewBlocks) are inserted into the
1605   /// layout after the BB indicated by Start.
1606   void updateLayout(BinaryBasicBlock *Start, const unsigned NumNewBlocks);
1607 
1608   /// Make sure basic blocks' indices match the current layout.
1609   void updateLayoutIndices() const {
1610     unsigned Index = 0;
1611     for (BinaryBasicBlock *BB : layout())
1612       BB->setLayoutIndex(Index++);
1613   }
1614 
1615   /// Recompute the CFI state for NumNewBlocks following Start after inserting
1616   /// new blocks into the CFG.  This must be called after updateLayout.
1617   void updateCFIState(BinaryBasicBlock *Start, const unsigned NumNewBlocks);
1618 
1619   /// Return true if we detected ambiguous jump tables in this function, which
1620   /// happen when one JT is used in more than one indirect jumps. This precludes
1621   /// us from splitting edges for this JT unless we duplicate the JT (see
1622   /// disambiguateJumpTables).
1623   bool checkForAmbiguousJumpTables();
1624 
1625   /// Detect when two distinct indirect jumps are using the same jump table and
1626   /// duplicate it, allocating a separate JT for each indirect branch. This is
1627   /// necessary for code transformations on the CFG that change an edge induced
1628   /// by an indirect branch, e.g.: instrumentation or shrink wrapping. However,
1629   /// this is only possible if we are not updating jump tables in place, but are
1630   /// writing it to a new location (moving them).
1631   void disambiguateJumpTables(MCPlusBuilder::AllocatorIdTy AllocId);
1632 
1633   /// Change \p OrigDest to \p NewDest in the jump table used at the end of
1634   /// \p BB. Returns false if \p OrigDest couldn't be find as a valid target
1635   /// and no replacement took place.
1636   bool replaceJumpTableEntryIn(BinaryBasicBlock *BB, BinaryBasicBlock *OldDest,
1637                                BinaryBasicBlock *NewDest);
1638 
1639   /// Split the CFG edge <From, To> by inserting an intermediate basic block.
1640   /// Returns a pointer to this new intermediate basic block. BB "From" will be
1641   /// updated to jump to the intermediate block, which in turn will have an
1642   /// unconditional branch to BB "To".
1643   /// User needs to manually call fixBranches(). This function only creates the
1644   /// correct CFG edges.
1645   BinaryBasicBlock *splitEdge(BinaryBasicBlock *From, BinaryBasicBlock *To);
1646 
1647   /// We may have built an overly conservative CFG for functions with calls
1648   /// to functions that the compiler knows will never return. In this case,
1649   /// clear all successors from these blocks.
1650   void deleteConservativeEdges();
1651 
1652   /// Determine direction of the branch based on the current layout.
1653   /// Callee is responsible of updating basic block indices prior to using
1654   /// this function (e.g. by calling BinaryFunction::updateLayoutIndices()).
1655   static bool isForwardBranch(const BinaryBasicBlock *From,
1656                               const BinaryBasicBlock *To) {
1657     assert(From->getFunction() == To->getFunction() &&
1658            "basic blocks should be in the same function");
1659     return To->getLayoutIndex() > From->getLayoutIndex();
1660   }
1661 
1662   /// Determine direction of the call to callee symbol relative to the start
1663   /// of this function.
1664   /// Note: this doesn't take function splitting into account.
1665   bool isForwardCall(const MCSymbol *CalleeSymbol) const;
1666 
1667   /// Dump function information to debug output. If \p PrintInstructions
1668   /// is true - include instruction disassembly.
1669   void dump(bool PrintInstructions = true) const;
1670 
1671   /// Print function information to the \p OS stream.
1672   void print(raw_ostream &OS, std::string Annotation = "",
1673              bool PrintInstructions = true) const;
1674 
1675   /// Print all relocations between \p Offset and \p Offset + \p Size in
1676   /// this function.
1677   void printRelocations(raw_ostream &OS, uint64_t Offset, uint64_t Size) const;
1678 
1679   /// Return true if function has a profile, even if the profile does not
1680   /// match CFG 100%.
1681   bool hasProfile() const { return ExecutionCount != COUNT_NO_PROFILE; }
1682 
1683   /// Return true if function profile is present and accurate.
1684   bool hasValidProfile() const {
1685     return ExecutionCount != COUNT_NO_PROFILE && ProfileMatchRatio == 1.0f;
1686   }
1687 
1688   /// Mark this function as having a valid profile.
1689   void markProfiled(uint16_t Flags) {
1690     if (ExecutionCount == COUNT_NO_PROFILE)
1691       ExecutionCount = 0;
1692     ProfileFlags = Flags;
1693     ProfileMatchRatio = 1.0f;
1694   }
1695 
1696   /// Return flags describing a profile for this function.
1697   uint16_t getProfileFlags() const { return ProfileFlags; }
1698 
1699   void addCFIInstruction(uint64_t Offset, MCCFIInstruction &&Inst) {
1700     assert(!Instructions.empty());
1701 
1702     // Fix CFI instructions skipping NOPs. We need to fix this because changing
1703     // CFI state after a NOP, besides being wrong and inaccurate,  makes it
1704     // harder for us to recover this information, since we can create empty BBs
1705     // with NOPs and then reorder it away.
1706     // We fix this by moving the CFI instruction just before any NOPs.
1707     auto I = Instructions.lower_bound(Offset);
1708     if (Offset == getSize()) {
1709       assert(I == Instructions.end() && "unexpected iterator value");
1710       // Sometimes compiler issues restore_state after all instructions
1711       // in the function (even after nop).
1712       --I;
1713       Offset = I->first;
1714     }
1715     assert(I->first == Offset && "CFI pointing to unknown instruction");
1716     if (I == Instructions.begin()) {
1717       CIEFrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst));
1718       return;
1719     }
1720 
1721     --I;
1722     while (I != Instructions.begin() && BC.MIB->isNoop(I->second)) {
1723       Offset = I->first;
1724       --I;
1725     }
1726     OffsetToCFI.emplace(Offset, FrameInstructions.size());
1727     FrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst));
1728     return;
1729   }
1730 
1731   BinaryBasicBlock::iterator addCFIInstruction(BinaryBasicBlock *BB,
1732                                                BinaryBasicBlock::iterator Pos,
1733                                                MCCFIInstruction &&Inst) {
1734     size_t Idx = FrameInstructions.size();
1735     FrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst));
1736     return addCFIPseudo(BB, Pos, Idx);
1737   }
1738 
1739   /// Insert a CFI pseudo instruction in a basic block. This pseudo instruction
1740   /// is a placeholder that refers to a real MCCFIInstruction object kept by
1741   /// this function that will be emitted at that position.
1742   BinaryBasicBlock::iterator addCFIPseudo(BinaryBasicBlock *BB,
1743                                           BinaryBasicBlock::iterator Pos,
1744                                           uint32_t Offset) {
1745     MCInst CFIPseudo;
1746     BC.MIB->createCFI(CFIPseudo, Offset);
1747     return BB->insertPseudoInstr(Pos, CFIPseudo);
1748   }
1749 
1750   /// Retrieve the MCCFIInstruction object associated with a CFI pseudo.
1751   const MCCFIInstruction *getCFIFor(const MCInst &Instr) const {
1752     if (!BC.MIB->isCFI(Instr))
1753       return nullptr;
1754     uint32_t Offset = Instr.getOperand(0).getImm();
1755     assert(Offset < FrameInstructions.size() && "Invalid CFI offset");
1756     return &FrameInstructions[Offset];
1757   }
1758 
1759   void setCFIFor(const MCInst &Instr, MCCFIInstruction &&CFIInst) {
1760     assert(BC.MIB->isCFI(Instr) &&
1761            "attempting to change CFI in a non-CFI inst");
1762     uint32_t Offset = Instr.getOperand(0).getImm();
1763     assert(Offset < FrameInstructions.size() && "Invalid CFI offset");
1764     FrameInstructions[Offset] = std::move(CFIInst);
1765   }
1766 
1767   void mutateCFIRegisterFor(const MCInst &Instr, MCPhysReg NewReg);
1768 
1769   const MCCFIInstruction *mutateCFIOffsetFor(const MCInst &Instr,
1770                                              int64_t NewOffset);
1771 
1772   BinaryFunction &setFileOffset(uint64_t Offset) {
1773     FileOffset = Offset;
1774     return *this;
1775   }
1776 
1777   BinaryFunction &setSize(uint64_t S) {
1778     Size = S;
1779     return *this;
1780   }
1781 
1782   BinaryFunction &setMaxSize(uint64_t Size) {
1783     MaxSize = Size;
1784     return *this;
1785   }
1786 
1787   BinaryFunction &setOutputAddress(uint64_t Address) {
1788     OutputAddress = Address;
1789     return *this;
1790   }
1791 
1792   BinaryFunction &setOutputSize(uint64_t Size) {
1793     OutputSize = Size;
1794     return *this;
1795   }
1796 
1797   BinaryFunction &setSimple(bool Simple) {
1798     IsSimple = Simple;
1799     return *this;
1800   }
1801 
1802   void setPseudo(bool Pseudo) { IsPseudo = Pseudo; }
1803 
1804   BinaryFunction &setUsesGnuArgsSize(bool Uses = true) {
1805     UsesGnuArgsSize = Uses;
1806     return *this;
1807   }
1808 
1809   BinaryFunction &setHasProfileAvailable(bool V = true) {
1810     HasProfileAvailable = V;
1811     return *this;
1812   }
1813 
1814   /// Mark function that should not be emitted.
1815   void setIgnored();
1816 
1817   void setIsPatched(bool V) { IsPatched = V; }
1818 
1819   void setHasSplitJumpTable(bool V) { HasSplitJumpTable = V; }
1820 
1821   void setHasCanonicalCFG(bool V) { HasCanonicalCFG = V; }
1822 
1823   void setFolded(BinaryFunction *BF) { FoldedIntoFunction = BF; }
1824 
1825   BinaryFunction &setPersonalityFunction(uint64_t Addr) {
1826     assert(!PersonalityFunction && "can't set personality function twice");
1827     PersonalityFunction = BC.getOrCreateGlobalSymbol(Addr, "FUNCat");
1828     return *this;
1829   }
1830 
1831   BinaryFunction &setPersonalityEncoding(uint8_t Encoding) {
1832     PersonalityEncoding = Encoding;
1833     return *this;
1834   }
1835 
1836   BinaryFunction &setAlignment(uint16_t Align) {
1837     Alignment = Align;
1838     return *this;
1839   }
1840 
1841   uint16_t getAlignment() const { return Alignment; }
1842 
1843   BinaryFunction &setMaxAlignmentBytes(uint16_t MaxAlignBytes) {
1844     MaxAlignmentBytes = MaxAlignBytes;
1845     return *this;
1846   }
1847 
1848   uint16_t getMaxAlignmentBytes() const { return MaxAlignmentBytes; }
1849 
1850   BinaryFunction &setMaxColdAlignmentBytes(uint16_t MaxAlignBytes) {
1851     MaxColdAlignmentBytes = MaxAlignBytes;
1852     return *this;
1853   }
1854 
1855   uint16_t getMaxColdAlignmentBytes() const { return MaxColdAlignmentBytes; }
1856 
1857   BinaryFunction &setImageAddress(uint64_t Address) {
1858     ImageAddress = Address;
1859     return *this;
1860   }
1861 
1862   /// Return the address of this function' image in memory.
1863   uint64_t getImageAddress() const { return ImageAddress; }
1864 
1865   BinaryFunction &setImageSize(uint64_t Size) {
1866     ImageSize = Size;
1867     return *this;
1868   }
1869 
1870   /// Return the size of this function' image in memory.
1871   uint64_t getImageSize() const { return ImageSize; }
1872 
1873   /// Return true if the function is a secondary fragment of another function.
1874   bool isFragment() const { return IsFragment; }
1875 
1876   /// Returns if the given function is a parent fragment of this function.
1877   bool isParentFragment(BinaryFunction *Parent) const {
1878     return ParentFragments.count(Parent);
1879   }
1880 
1881   /// Set the profile data for the number of times the function was called.
1882   BinaryFunction &setExecutionCount(uint64_t Count) {
1883     ExecutionCount = Count;
1884     return *this;
1885   }
1886 
1887   /// Adjust execution count for the function by a given \p Count. The value
1888   /// \p Count will be subtracted from the current function count.
1889   ///
1890   /// The function will proportionally adjust execution count for all
1891   /// basic blocks and edges in the control flow graph.
1892   void adjustExecutionCount(uint64_t Count);
1893 
1894   /// Set LSDA address for the function.
1895   BinaryFunction &setLSDAAddress(uint64_t Address) {
1896     LSDAAddress = Address;
1897     return *this;
1898   }
1899 
1900   /// Set LSDA symbol for the function.
1901   BinaryFunction &setLSDASymbol(MCSymbol *Symbol) {
1902     LSDASymbol = Symbol;
1903     return *this;
1904   }
1905 
1906   /// Return the profile information about the number of times
1907   /// the function was executed.
1908   ///
1909   /// Return COUNT_NO_PROFILE if there's no profile info.
1910   uint64_t getExecutionCount() const { return ExecutionCount; }
1911 
1912   /// Return the raw profile information about the number of branch
1913   /// executions corresponding to this function.
1914   uint64_t getRawBranchCount() const { return RawBranchCount; }
1915 
1916   /// Return the execution count for functions with known profile.
1917   /// Return 0 if the function has no profile.
1918   uint64_t getKnownExecutionCount() const {
1919     return ExecutionCount == COUNT_NO_PROFILE ? 0 : ExecutionCount;
1920   }
1921 
1922   /// Return original LSDA address for the function or NULL.
1923   uint64_t getLSDAAddress() const { return LSDAAddress; }
1924 
1925   /// Return symbol pointing to function's LSDA.
1926   MCSymbol *getLSDASymbol() {
1927     if (LSDASymbol)
1928       return LSDASymbol;
1929     if (CallSites.empty())
1930       return nullptr;
1931 
1932     LSDASymbol = BC.Ctx->getOrCreateSymbol(
1933         Twine("GCC_except_table") + Twine::utohexstr(getFunctionNumber()));
1934 
1935     return LSDASymbol;
1936   }
1937 
1938   /// Return symbol pointing to function's LSDA for the cold part.
1939   MCSymbol *getColdLSDASymbol() {
1940     if (ColdLSDASymbol)
1941       return ColdLSDASymbol;
1942     if (ColdCallSites.empty())
1943       return nullptr;
1944 
1945     ColdLSDASymbol = BC.Ctx->getOrCreateSymbol(
1946         Twine("GCC_cold_except_table") + Twine::utohexstr(getFunctionNumber()));
1947 
1948     return ColdLSDASymbol;
1949   }
1950 
1951   /// True if the symbol is a mapping symbol used in AArch64 to delimit
1952   /// data inside code section.
1953   bool isDataMarker(const SymbolRef &Symbol, uint64_t SymbolSize) const;
1954   bool isCodeMarker(const SymbolRef &Symbol, uint64_t SymbolSize) const;
1955 
1956   void setOutputDataAddress(uint64_t Address) { OutputDataOffset = Address; }
1957 
1958   uint64_t getOutputDataAddress() const { return OutputDataOffset; }
1959 
1960   void setOutputColdDataAddress(uint64_t Address) {
1961     OutputColdDataOffset = Address;
1962   }
1963 
1964   uint64_t getOutputColdDataAddress() const { return OutputColdDataOffset; }
1965 
1966   /// If \p Address represents an access to a constant island managed by this
1967   /// function, return a symbol so code can safely refer to it. Otherwise,
1968   /// return nullptr. First return value is the symbol for reference in the
1969   /// hot code area while the second return value is the symbol for reference
1970   /// in the cold code area, as when the function is split the islands are
1971   /// duplicated.
1972   MCSymbol *getOrCreateIslandAccess(uint64_t Address) {
1973     if (!Islands)
1974       return nullptr;
1975 
1976     MCSymbol *Symbol;
1977     if (!isInConstantIsland(Address))
1978       return nullptr;
1979 
1980     // Register our island at global namespace
1981     Symbol = BC.getOrCreateGlobalSymbol(Address, "ISLANDat");
1982 
1983     // Internal bookkeeping
1984     const uint64_t Offset = Address - getAddress();
1985     assert((!Islands->Offsets.count(Offset) ||
1986             Islands->Offsets[Offset] == Symbol) &&
1987            "Inconsistent island symbol management");
1988     if (!Islands->Offsets.count(Offset)) {
1989       Islands->Offsets[Offset] = Symbol;
1990       Islands->Symbols.insert(Symbol);
1991     }
1992     return Symbol;
1993   }
1994 
1995   /// Called by an external function which wishes to emit references to constant
1996   /// island symbols of this function. We create a proxy for it, so we emit
1997   /// separate symbols when emitting our constant island on behalf of this other
1998   /// function.
1999   MCSymbol *getOrCreateProxyIslandAccess(uint64_t Address,
2000                                          BinaryFunction &Referrer) {
2001     MCSymbol *Symbol = getOrCreateIslandAccess(Address);
2002     if (!Symbol)
2003       return nullptr;
2004 
2005     MCSymbol *Proxy;
2006     if (!Islands->Proxies[&Referrer].count(Symbol)) {
2007       Proxy = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".proxy.for." +
2008                                         Referrer.getPrintName());
2009       Islands->Proxies[&Referrer][Symbol] = Proxy;
2010       Islands->Proxies[&Referrer][Proxy] = Symbol;
2011     }
2012     Proxy = Islands->Proxies[&Referrer][Symbol];
2013     return Proxy;
2014   }
2015 
2016   /// Make this function depend on \p BF because we have a reference to its
2017   /// constant island. When emitting this function,  we will also emit
2018   //  \p BF's constants. This only happens in custom AArch64 assembly code.
2019   void createIslandDependency(MCSymbol *Island, BinaryFunction *BF) {
2020     if (!Islands)
2021       Islands = std::make_unique<IslandInfo>();
2022 
2023     Islands->Dependency.insert(BF);
2024     Islands->ProxySymbols[Island] = BF;
2025   }
2026 
2027   /// Detects whether \p Address is inside a data region in this function
2028   /// (constant islands).
2029   bool isInConstantIsland(uint64_t Address) const {
2030     if (!Islands)
2031       return false;
2032 
2033     if (Address < getAddress())
2034       return false;
2035 
2036     uint64_t Offset = Address - getAddress();
2037 
2038     if (Offset >= getMaxSize())
2039       return false;
2040 
2041     auto DataIter = Islands->DataOffsets.upper_bound(Offset);
2042     if (DataIter == Islands->DataOffsets.begin())
2043       return false;
2044     DataIter = std::prev(DataIter);
2045 
2046     auto CodeIter = Islands->CodeOffsets.upper_bound(Offset);
2047     if (CodeIter == Islands->CodeOffsets.begin())
2048       return true;
2049 
2050     return *std::prev(CodeIter) <= *DataIter;
2051   }
2052 
2053   uint16_t getConstantIslandAlignment() const {
2054     return Islands ? Islands->getAlignment() : 1;
2055   }
2056 
2057   uint64_t
2058   estimateConstantIslandSize(const BinaryFunction *OnBehalfOf = nullptr) const {
2059     if (!Islands)
2060       return 0;
2061 
2062     uint64_t Size = 0;
2063     for (auto DataIter = Islands->DataOffsets.begin();
2064          DataIter != Islands->DataOffsets.end(); ++DataIter) {
2065       auto NextData = std::next(DataIter);
2066       auto CodeIter = Islands->CodeOffsets.lower_bound(*DataIter);
2067       if (CodeIter == Islands->CodeOffsets.end() &&
2068           NextData == Islands->DataOffsets.end()) {
2069         Size += getMaxSize() - *DataIter;
2070         continue;
2071       }
2072 
2073       uint64_t NextMarker;
2074       if (CodeIter == Islands->CodeOffsets.end())
2075         NextMarker = *NextData;
2076       else if (NextData == Islands->DataOffsets.end())
2077         NextMarker = *CodeIter;
2078       else
2079         NextMarker = (*CodeIter > *NextData) ? *NextData : *CodeIter;
2080 
2081       Size += NextMarker - *DataIter;
2082     }
2083 
2084     if (!OnBehalfOf) {
2085       for (BinaryFunction *ExternalFunc : Islands->Dependency) {
2086         Size = alignTo(Size, ExternalFunc->getConstantIslandAlignment());
2087         Size += ExternalFunc->estimateConstantIslandSize(this);
2088       }
2089     }
2090 
2091     return Size;
2092   }
2093 
2094   bool hasIslandsInfo() const { return !!Islands; }
2095 
2096   bool hasConstantIsland() const {
2097     return Islands && !Islands->DataOffsets.empty();
2098   }
2099 
2100   /// Return true iff the symbol could be seen inside this function otherwise
2101   /// it is probably another function.
2102   bool isSymbolValidInScope(const SymbolRef &Symbol, uint64_t SymbolSize) const;
2103 
2104   /// Disassemble function from raw data.
2105   /// If successful, this function will populate the list of instructions
2106   /// for this function together with offsets from the function start
2107   /// in the input. It will also populate Labels with destinations for
2108   /// local branches, and TakenBranches with [from, to] info.
2109   ///
2110   /// The Function should be properly initialized before this function
2111   /// is called. I.e. function address and size should be set.
2112   ///
2113   /// Returns true on successful disassembly, and updates the current
2114   /// state to State:Disassembled.
2115   ///
2116   /// Returns false if disassembly failed.
2117   bool disassemble();
2118 
2119   /// Scan function for references to other functions. In relocation mode,
2120   /// add relocations for external references.
2121   ///
2122   /// Return true on success.
2123   bool scanExternalRefs();
2124 
2125   /// Return the size of a data object located at \p Offset in the function.
2126   /// Return 0 if there is no data object at the \p Offset.
2127   size_t getSizeOfDataInCodeAt(uint64_t Offset) const;
2128 
2129   /// Verify that starting at \p Offset function contents are filled with
2130   /// zero-value bytes.
2131   bool isZeroPaddingAt(uint64_t Offset) const;
2132 
2133   /// Check that entry points have an associated instruction at their
2134   /// offsets after disassembly.
2135   void postProcessEntryPoints();
2136 
2137   /// Post-processing for jump tables after disassembly. Since their
2138   /// boundaries are not known until all call sites are seen, we need this
2139   /// extra pass to perform any final adjustments.
2140   void postProcessJumpTables();
2141 
2142   /// Builds a list of basic blocks with successor and predecessor info.
2143   ///
2144   /// The function should in Disassembled state prior to call.
2145   ///
2146   /// Returns true on success and update the current function state to
2147   /// State::CFG. Returns false if CFG cannot be built.
2148   bool buildCFG(MCPlusBuilder::AllocatorIdTy);
2149 
2150   /// Perform post-processing of the CFG.
2151   void postProcessCFG();
2152 
2153   /// Verify that any assumptions we've made about indirect branches were
2154   /// correct and also make any necessary changes to unknown indirect branches.
2155   ///
2156   /// Catch-22: we need to know indirect branch targets to build CFG, and
2157   /// in order to determine the value for indirect branches we need to know CFG.
2158   ///
2159   /// As such, the process of decoding indirect branches is broken into 2 steps:
2160   /// first we make our best guess about a branch without knowing the CFG,
2161   /// and later after we have the CFG for the function, we verify our earlier
2162   /// assumptions and also do our best at processing unknown indirect branches.
2163   ///
2164   /// Return true upon successful processing, or false if the control flow
2165   /// cannot be statically evaluated for any given indirect branch.
2166   bool postProcessIndirectBranches(MCPlusBuilder::AllocatorIdTy AllocId);
2167 
2168   /// Return all call site profile info for this function.
2169   IndirectCallSiteProfile &getAllCallSites() { return AllCallSites; }
2170 
2171   const IndirectCallSiteProfile &getAllCallSites() const {
2172     return AllCallSites;
2173   }
2174 
2175   /// Walks the list of basic blocks filling in missing information about
2176   /// edge frequency for fall-throughs.
2177   ///
2178   /// Assumes the CFG has been built and edge frequency for taken branches
2179   /// has been filled with LBR data.
2180   void inferFallThroughCounts();
2181 
2182   /// Clear execution profile of the function.
2183   void clearProfile();
2184 
2185   /// Converts conditional tail calls to unconditional tail calls. We do this to
2186   /// handle conditional tail calls correctly and to give a chance to the
2187   /// simplify conditional tail call pass to decide whether to re-optimize them
2188   /// using profile information.
2189   void removeConditionalTailCalls();
2190 
2191   // Convert COUNT_NO_PROFILE to 0
2192   void removeTagsFromProfile();
2193 
2194   /// Computes a function hotness score: the sum of the products of BB frequency
2195   /// and size.
2196   uint64_t getFunctionScore() const;
2197 
2198   /// Return true if the layout has been changed by basic block reordering,
2199   /// false otherwise.
2200   bool hasLayoutChanged() const;
2201 
2202   /// Get the edit distance of the new layout with respect to the previous
2203   /// layout after basic block reordering.
2204   uint64_t getEditDistance() const;
2205 
2206   /// Get the number of instructions within this function.
2207   uint64_t getInstructionCount() const;
2208 
2209   const CFIInstrMapType &getFDEProgram() const { return FrameInstructions; }
2210 
2211   void moveRememberRestorePair(BinaryBasicBlock *BB);
2212 
2213   bool replayCFIInstrs(int32_t FromState, int32_t ToState,
2214                        BinaryBasicBlock *InBB,
2215                        BinaryBasicBlock::iterator InsertIt);
2216 
2217   /// unwindCFIState is used to unwind from a higher to a lower state number
2218   /// without using remember-restore instructions. We do that by keeping track
2219   /// of what values have been changed from state A to B and emitting
2220   /// instructions that undo this change.
2221   SmallVector<int32_t, 4> unwindCFIState(int32_t FromState, int32_t ToState,
2222                                          BinaryBasicBlock *InBB,
2223                                          BinaryBasicBlock::iterator &InsertIt);
2224 
2225   /// After reordering, this function checks the state of CFI and fixes it if it
2226   /// is corrupted. If it is unable to fix it, it returns false.
2227   bool finalizeCFIState();
2228 
2229   /// Return true if this function needs an address-transaltion table after
2230   /// its code emission.
2231   bool requiresAddressTranslation() const;
2232 
2233   /// Adjust branch instructions to match the CFG.
2234   ///
2235   /// As it comes to internal branches, the CFG represents "the ultimate source
2236   /// of truth". Transformations on functions and blocks have to update the CFG
2237   /// and fixBranches() would make sure the correct branch instructions are
2238   /// inserted at the end of basic blocks.
2239   ///
2240   /// We do require a conditional branch at the end of the basic block if
2241   /// the block has 2 successors as CFG currently lacks the conditional
2242   /// code support (it will probably stay that way). We only use this
2243   /// branch instruction for its conditional code, the destination is
2244   /// determined by CFG - first successor representing true/taken branch,
2245   /// while the second successor - false/fall-through branch.
2246   ///
2247   /// When we reverse the branch condition, the CFG is updated accordingly.
2248   void fixBranches();
2249 
2250   /// Mark function as finalized. No further optimizations are permitted.
2251   void setFinalized() { CurrentState = State::CFG_Finalized; }
2252 
2253   void setEmitted(bool KeepCFG = false) {
2254     CurrentState = State::EmittedCFG;
2255     if (!KeepCFG) {
2256       releaseCFG();
2257       CurrentState = State::Emitted;
2258     }
2259   }
2260 
2261   /// Process LSDA information for the function.
2262   void parseLSDA(ArrayRef<uint8_t> LSDAData, uint64_t LSDAAddress);
2263 
2264   /// Update exception handling ranges for the function.
2265   void updateEHRanges();
2266 
2267   /// Traverse cold basic blocks and replace references to constants in islands
2268   /// with a proxy symbol for the duplicated constant island that is going to be
2269   /// emitted in the cold region.
2270   void duplicateConstantIslands();
2271 
2272   /// Merge profile data of this function into those of the given
2273   /// function. The functions should have been proven identical with
2274   /// isIdenticalWith.
2275   void mergeProfileDataInto(BinaryFunction &BF) const;
2276 
2277   /// Returns the last computed hash value of the function.
2278   size_t getHash() const { return Hash; }
2279 
2280   using OperandHashFuncTy =
2281       function_ref<typename std::string(const MCOperand &)>;
2282 
2283   /// Compute the hash value of the function based on its contents.
2284   ///
2285   /// If \p UseDFS is set, process basic blocks in DFS order. Otherwise, use
2286   /// the existing layout order.
2287   ///
2288   /// By default, instruction operands are ignored while calculating the hash.
2289   /// The caller can change this via passing \p OperandHashFunc function.
2290   /// The return result of this function will be mixed with internal hash.
2291   size_t computeHash(
2292       bool UseDFS = false,
2293       OperandHashFuncTy OperandHashFunc = [](const MCOperand &) {
2294         return std::string();
2295       }) const;
2296 
2297   void setDWARFUnit(DWARFUnit *Unit) { DwarfUnit = Unit; }
2298 
2299   /// Return DWARF compile unit for this function.
2300   DWARFUnit *getDWARFUnit() const { return DwarfUnit; }
2301 
2302   /// Return line info table for this function.
2303   const DWARFDebugLine::LineTable *getDWARFLineTable() const {
2304     return getDWARFUnit() ? BC.DwCtx->getLineTableForUnit(getDWARFUnit())
2305                           : nullptr;
2306   }
2307 
2308   /// Finalize profile for the function.
2309   void postProcessProfile();
2310 
2311   /// Returns an estimate of the function's hot part after splitting.
2312   /// This is a very rough estimate, as with C++ exceptions there are
2313   /// blocks we don't move, and it makes no attempt at estimating the size
2314   /// of the added/removed branch instructions.
2315   /// Note that this size is optimistic and the actual size may increase
2316   /// after relaxation.
2317   size_t estimateHotSize(const bool UseSplitSize = true) const {
2318     size_t Estimate = 0;
2319     if (UseSplitSize && isSplit()) {
2320       for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2321         if (!BB->isCold())
2322           Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2323     } else {
2324       for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2325         if (BB->getKnownExecutionCount() != 0)
2326           Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2327     }
2328     return Estimate;
2329   }
2330 
2331   size_t estimateColdSize() const {
2332     if (!isSplit())
2333       return estimateSize();
2334     size_t Estimate = 0;
2335     for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2336       if (BB->isCold())
2337         Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2338     return Estimate;
2339   }
2340 
2341   size_t estimateSize() const {
2342     size_t Estimate = 0;
2343     for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2344       Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2345     return Estimate;
2346   }
2347 
2348   /// Return output address ranges for a function.
2349   DebugAddressRangesVector getOutputAddressRanges() const;
2350 
2351   /// Given an address corresponding to an instruction in the input binary,
2352   /// return an address of this instruction in output binary.
2353   ///
2354   /// Return 0 if no matching address could be found or the instruction was
2355   /// removed.
2356   uint64_t translateInputToOutputAddress(uint64_t Address) const;
2357 
2358   /// Take address ranges corresponding to the input binary and translate
2359   /// them to address ranges in the output binary.
2360   DebugAddressRangesVector translateInputToOutputRanges(
2361       const DWARFAddressRangesVector &InputRanges) const;
2362 
2363   /// Similar to translateInputToOutputRanges() but operates on location lists
2364   /// and moves associated data to output location lists.
2365   DebugLocationsVector
2366   translateInputToOutputLocationList(const DebugLocationsVector &InputLL) const;
2367 
2368   /// Return true if the function is an AArch64 linker inserted veneer
2369   bool isAArch64Veneer() const;
2370 
2371   virtual ~BinaryFunction();
2372 
2373   /// Info for fragmented functions.
2374   class FragmentInfo {
2375   private:
2376     uint64_t Address{0};
2377     uint64_t ImageAddress{0};
2378     uint64_t ImageSize{0};
2379     uint64_t FileOffset{0};
2380 
2381   public:
2382     uint64_t getAddress() const { return Address; }
2383     uint64_t getImageAddress() const { return ImageAddress; }
2384     uint64_t getImageSize() const { return ImageSize; }
2385     uint64_t getFileOffset() const { return FileOffset; }
2386 
2387     void setAddress(uint64_t VAddress) { Address = VAddress; }
2388     void setImageAddress(uint64_t Address) { ImageAddress = Address; }
2389     void setImageSize(uint64_t Size) { ImageSize = Size; }
2390     void setFileOffset(uint64_t Offset) { FileOffset = Offset; }
2391   };
2392 
2393   /// Cold fragment of the function.
2394   FragmentInfo ColdFragment;
2395 
2396   FragmentInfo &cold() { return ColdFragment; }
2397 
2398   const FragmentInfo &cold() const { return ColdFragment; }
2399 };
2400 
2401 inline raw_ostream &operator<<(raw_ostream &OS,
2402                                const BinaryFunction &Function) {
2403   OS << Function.getPrintName();
2404   return OS;
2405 }
2406 
2407 } // namespace bolt
2408 
2409 // GraphTraits specializations for function basic block graphs (CFGs)
2410 template <>
2411 struct GraphTraits<bolt::BinaryFunction *>
2412     : public GraphTraits<bolt::BinaryBasicBlock *> {
2413   static NodeRef getEntryNode(bolt::BinaryFunction *F) {
2414     return *F->layout_begin();
2415   }
2416 
2417   using nodes_iterator = pointer_iterator<bolt::BinaryFunction::iterator>;
2418 
2419   static nodes_iterator nodes_begin(bolt::BinaryFunction *F) {
2420     llvm_unreachable("Not implemented");
2421     return nodes_iterator(F->begin());
2422   }
2423   static nodes_iterator nodes_end(bolt::BinaryFunction *F) {
2424     llvm_unreachable("Not implemented");
2425     return nodes_iterator(F->end());
2426   }
2427   static size_t size(bolt::BinaryFunction *F) { return F->size(); }
2428 };
2429 
2430 template <>
2431 struct GraphTraits<const bolt::BinaryFunction *>
2432     : public GraphTraits<const bolt::BinaryBasicBlock *> {
2433   static NodeRef getEntryNode(const bolt::BinaryFunction *F) {
2434     return *F->layout_begin();
2435   }
2436 
2437   using nodes_iterator = pointer_iterator<bolt::BinaryFunction::const_iterator>;
2438 
2439   static nodes_iterator nodes_begin(const bolt::BinaryFunction *F) {
2440     llvm_unreachable("Not implemented");
2441     return nodes_iterator(F->begin());
2442   }
2443   static nodes_iterator nodes_end(const bolt::BinaryFunction *F) {
2444     llvm_unreachable("Not implemented");
2445     return nodes_iterator(F->end());
2446   }
2447   static size_t size(const bolt::BinaryFunction *F) { return F->size(); }
2448 };
2449 
2450 template <>
2451 struct GraphTraits<Inverse<bolt::BinaryFunction *>>
2452     : public GraphTraits<Inverse<bolt::BinaryBasicBlock *>> {
2453   static NodeRef getEntryNode(Inverse<bolt::BinaryFunction *> G) {
2454     return *G.Graph->layout_begin();
2455   }
2456 };
2457 
2458 template <>
2459 struct GraphTraits<Inverse<const bolt::BinaryFunction *>>
2460     : public GraphTraits<Inverse<const bolt::BinaryBasicBlock *>> {
2461   static NodeRef getEntryNode(Inverse<const bolt::BinaryFunction *> G) {
2462     return *G.Graph->layout_begin();
2463   }
2464 };
2465 
2466 } // namespace llvm
2467 
2468 #endif
2469