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   BinaryFunction &operator=(const BinaryFunction &) = delete;
671   BinaryFunction(const BinaryFunction &) = delete;
672 
673   friend class MachORewriteInstance;
674   friend class RewriteInstance;
675   friend class BinaryContext;
676   friend class DataReader;
677   friend class DataAggregator;
678 
679   static std::string buildCodeSectionName(StringRef Name,
680                                           const BinaryContext &BC);
681   static std::string buildColdCodeSectionName(StringRef Name,
682                                               const BinaryContext &BC);
683 
684   /// Creation should be handled by RewriteInstance or BinaryContext
685   BinaryFunction(const std::string &Name, BinarySection &Section,
686                  uint64_t Address, uint64_t Size, BinaryContext &BC)
687       : OriginSection(&Section), Address(Address), Size(Size), BC(BC),
688         CodeSectionName(buildCodeSectionName(Name, BC)),
689         ColdCodeSectionName(buildColdCodeSectionName(Name, BC)),
690         FunctionNumber(++Count) {
691     Symbols.push_back(BC.Ctx->getOrCreateSymbol(Name));
692   }
693 
694   /// This constructor is used to create an injected function
695   BinaryFunction(const std::string &Name, BinaryContext &BC, bool IsSimple)
696       : Address(0), Size(0), BC(BC), IsSimple(IsSimple),
697         CodeSectionName(buildCodeSectionName(Name, BC)),
698         ColdCodeSectionName(buildColdCodeSectionName(Name, BC)),
699         FunctionNumber(++Count) {
700     Symbols.push_back(BC.Ctx->getOrCreateSymbol(Name));
701     IsInjected = true;
702   }
703 
704   /// Create a basic block at a given \p Offset in the function and append it
705   /// to the end of list of blocks. Used during CFG construction only.
706   BinaryBasicBlock *addBasicBlockAt(uint64_t Offset, MCSymbol *Label) {
707     assert(CurrentState == State::Disassembled &&
708            "Cannot add block with an offset in non-disassembled state.");
709     assert(!getBasicBlockAtOffset(Offset) &&
710            "Basic block already exists at the offset.");
711 
712     BasicBlocks.emplace_back(createBasicBlock(Label).release());
713     BinaryBasicBlock *BB = BasicBlocks.back();
714 
715     BB->setIndex(BasicBlocks.size() - 1);
716     BB->setOffset(Offset);
717 
718     BasicBlockOffsets.emplace_back(Offset, BB);
719     assert(llvm::is_sorted(BasicBlockOffsets, CompareBasicBlockOffsets()) &&
720            llvm::is_sorted(blocks()));
721 
722     return BB;
723   }
724 
725   /// Clear state of the function that could not be disassembled or if its
726   /// disassembled state was later invalidated.
727   void clearDisasmState();
728 
729   /// Release memory allocated for CFG and instructions.
730   /// We still keep basic blocks for address translation/mapping purposes.
731   void releaseCFG() {
732     for (BinaryBasicBlock *BB : BasicBlocks)
733       BB->releaseCFG();
734     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
735       BB->releaseCFG();
736 
737     clearList(CallSites);
738     clearList(ColdCallSites);
739     clearList(LSDATypeTable);
740     clearList(LSDATypeAddressTable);
741 
742     clearList(LabelToBB);
743 
744     if (!isMultiEntry())
745       clearList(Labels);
746 
747     clearList(FrameInstructions);
748     clearList(FrameRestoreEquivalents);
749   }
750 
751 public:
752   BinaryFunction(BinaryFunction &&) = default;
753 
754   using iterator = pointee_iterator<BasicBlockListType::iterator>;
755   using const_iterator = pointee_iterator<BasicBlockListType::const_iterator>;
756   using reverse_iterator =
757       pointee_iterator<BasicBlockListType::reverse_iterator>;
758   using const_reverse_iterator =
759       pointee_iterator<BasicBlockListType::const_reverse_iterator>;
760 
761   typedef BasicBlockOrderType::iterator order_iterator;
762   typedef BasicBlockOrderType::const_iterator const_order_iterator;
763   typedef BasicBlockOrderType::reverse_iterator reverse_order_iterator;
764   typedef BasicBlockOrderType::const_reverse_iterator
765       const_reverse_order_iterator;
766 
767   // CFG iterators.
768   iterator                 begin()       { return BasicBlocks.begin(); }
769   const_iterator           begin() const { return BasicBlocks.begin(); }
770   iterator                 end  ()       { return BasicBlocks.end();   }
771   const_iterator           end  () const { return BasicBlocks.end();   }
772 
773   reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
774   const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
775   reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
776   const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
777 
778   size_t                    size() const { return BasicBlocks.size();}
779   bool                     empty() const { return BasicBlocks.empty(); }
780   const BinaryBasicBlock &front() const  { return *BasicBlocks.front(); }
781         BinaryBasicBlock &front()        { return *BasicBlocks.front(); }
782   const BinaryBasicBlock & back() const  { return *BasicBlocks.back(); }
783         BinaryBasicBlock & back()        { return *BasicBlocks.back(); }
784   inline iterator_range<iterator> blocks() {
785     return iterator_range<iterator>(begin(), end());
786   }
787   inline iterator_range<const_iterator> blocks() const {
788     return iterator_range<const_iterator>(begin(), end());
789   }
790 
791   // Iterators by pointer.
792   BasicBlockListType::iterator pbegin()  { return BasicBlocks.begin(); }
793   BasicBlockListType::iterator pend()    { return BasicBlocks.end(); }
794 
795   order_iterator       layout_begin()    { return BasicBlocksLayout.begin(); }
796   const_order_iterator layout_begin()    const
797                                          { return BasicBlocksLayout.begin(); }
798   order_iterator       layout_end()      { return BasicBlocksLayout.end(); }
799   const_order_iterator layout_end()      const
800                                          { return BasicBlocksLayout.end(); }
801   reverse_order_iterator       layout_rbegin()
802                                          { return BasicBlocksLayout.rbegin(); }
803   const_reverse_order_iterator layout_rbegin() const
804                                          { return BasicBlocksLayout.rbegin(); }
805   reverse_order_iterator       layout_rend()
806                                          { return BasicBlocksLayout.rend(); }
807   const_reverse_order_iterator layout_rend()   const
808                                          { return BasicBlocksLayout.rend(); }
809   size_t   layout_size()  const { return BasicBlocksLayout.size(); }
810   bool     layout_empty() const { return BasicBlocksLayout.empty(); }
811   const BinaryBasicBlock *layout_front() const
812                                          { return BasicBlocksLayout.front(); }
813         BinaryBasicBlock *layout_front() { return BasicBlocksLayout.front(); }
814   const BinaryBasicBlock *layout_back()  const
815                                          { return BasicBlocksLayout.back(); }
816         BinaryBasicBlock *layout_back()  { return BasicBlocksLayout.back(); }
817 
818   inline iterator_range<order_iterator> layout() {
819     return iterator_range<order_iterator>(BasicBlocksLayout.begin(),
820                                           BasicBlocksLayout.end());
821   }
822 
823   inline iterator_range<const_order_iterator> layout() const {
824     return iterator_range<const_order_iterator>(BasicBlocksLayout.begin(),
825                                                 BasicBlocksLayout.end());
826   }
827 
828   inline iterator_range<reverse_order_iterator> rlayout() {
829     return iterator_range<reverse_order_iterator>(BasicBlocksLayout.rbegin(),
830                                                   BasicBlocksLayout.rend());
831   }
832 
833   inline iterator_range<const_reverse_order_iterator> rlayout() const {
834     return iterator_range<const_reverse_order_iterator>(
835         BasicBlocksLayout.rbegin(), BasicBlocksLayout.rend());
836   }
837 
838   cfi_iterator        cie_begin()       { return CIEFrameInstructions.begin(); }
839   const_cfi_iterator  cie_begin() const { return CIEFrameInstructions.begin(); }
840   cfi_iterator        cie_end()         { return CIEFrameInstructions.end(); }
841   const_cfi_iterator  cie_end()   const { return CIEFrameInstructions.end(); }
842   bool                cie_empty() const { return CIEFrameInstructions.empty(); }
843 
844   inline iterator_range<cfi_iterator> cie() {
845     return iterator_range<cfi_iterator>(cie_begin(), cie_end());
846   }
847   inline iterator_range<const_cfi_iterator> cie() const {
848     return iterator_range<const_cfi_iterator>(cie_begin(), cie_end());
849   }
850 
851   /// Iterate over all jump tables associated with this function.
852   iterator_range<std::map<uint64_t, JumpTable *>::const_iterator>
853   jumpTables() const {
854     return make_range(JumpTables.begin(), JumpTables.end());
855   }
856 
857   /// Return relocation associated with a given \p Offset in the function,
858   /// or nullptr if no such relocation exists.
859   const Relocation *getRelocationAt(uint64_t Offset) const {
860     assert(CurrentState == State::Empty &&
861            "Relocations unavailable in the current function state.");
862     auto RI = Relocations.find(Offset);
863     return (RI == Relocations.end()) ? nullptr : &RI->second;
864   }
865 
866   /// Return the first relocation in the function that starts at an address in
867   /// the [StartOffset, EndOffset) range. Return nullptr if no such relocation
868   /// exists.
869   const Relocation *getRelocationInRange(uint64_t StartOffset,
870                                          uint64_t EndOffset) const {
871     assert(CurrentState == State::Empty &&
872            "Relocations unavailable in the current function state.");
873     auto RI = Relocations.lower_bound(StartOffset);
874     if (RI != Relocations.end() && RI->first < EndOffset)
875       return &RI->second;
876 
877     return nullptr;
878   }
879 
880   /// Returns the raw binary encoding of this function.
881   ErrorOr<ArrayRef<uint8_t>> getData() const;
882 
883   BinaryFunction &updateState(BinaryFunction::State State) {
884     CurrentState = State;
885     return *this;
886   }
887 
888   /// Update layout of basic blocks used for output.
889   void updateBasicBlockLayout(BasicBlockOrderType &NewLayout) {
890     assert(NewLayout.size() == BasicBlocks.size() && "Layout size mismatch.");
891 
892     BasicBlocksPreviousLayout = BasicBlocksLayout;
893     if (NewLayout != BasicBlocksLayout) {
894       ModifiedLayout = true;
895       BasicBlocksLayout.clear();
896       BasicBlocksLayout.swap(NewLayout);
897     }
898   }
899 
900   /// Recompute landing pad information for the function and all its blocks.
901   void recomputeLandingPads();
902 
903   /// Return current basic block layout.
904   const BasicBlockOrderType &getLayout() const { return BasicBlocksLayout; }
905 
906   /// Return a list of basic blocks sorted using DFS and update layout indices
907   /// using the same order. Does not modify the current layout.
908   BasicBlockOrderType dfs() const;
909 
910   /// Find the loops in the CFG of the function and store information about
911   /// them.
912   void calculateLoopInfo();
913 
914   /// Calculate missed macro-fusion opportunities and update BinaryContext
915   /// stats.
916   void calculateMacroOpFusionStats();
917 
918   /// Returns if loop detection has been run for this function.
919   bool hasLoopInfo() const { return BLI != nullptr; }
920 
921   const BinaryLoopInfo &getLoopInfo() { return *BLI.get(); }
922 
923   bool isLoopFree() {
924     if (!hasLoopInfo())
925       calculateLoopInfo();
926     return BLI->empty();
927   }
928 
929   /// Print loop information about the function.
930   void printLoopInfo(raw_ostream &OS) const;
931 
932   /// View CFG in graphviz program
933   void viewGraph() const;
934 
935   /// Dump CFG in graphviz format
936   void dumpGraph(raw_ostream &OS) const;
937 
938   /// Dump CFG in graphviz format to file.
939   void dumpGraphToFile(std::string Filename) const;
940 
941   /// Dump CFG in graphviz format to a file with a filename that is derived
942   /// from the function name and Annotation strings.  Useful for dumping the
943   /// CFG after an optimization pass.
944   void dumpGraphForPass(std::string Annotation = "") const;
945 
946   /// Return BinaryContext for the function.
947   const BinaryContext &getBinaryContext() const { return BC; }
948 
949   /// Return BinaryContext for the function.
950   BinaryContext &getBinaryContext() { return BC; }
951 
952   /// Attempt to validate CFG invariants.
953   bool validateCFG() const;
954 
955   BinaryBasicBlock *getBasicBlockForLabel(const MCSymbol *Label) {
956     auto I = LabelToBB.find(Label);
957     return I == LabelToBB.end() ? nullptr : I->second;
958   }
959 
960   const BinaryBasicBlock *getBasicBlockForLabel(const MCSymbol *Label) const {
961     auto I = LabelToBB.find(Label);
962     return I == LabelToBB.end() ? nullptr : I->second;
963   }
964 
965   /// Returns the basic block after the given basic block in the layout or
966   /// nullptr the last basic block is given.
967   const BinaryBasicBlock *getBasicBlockAfter(const BinaryBasicBlock *BB,
968                                              bool IgnoreSplits = true) const {
969     return const_cast<BinaryFunction *>(this)->getBasicBlockAfter(BB,
970                                                                   IgnoreSplits);
971   }
972 
973   BinaryBasicBlock *getBasicBlockAfter(const BinaryBasicBlock *BB,
974                                        bool IgnoreSplits = true) {
975     for (auto I = layout_begin(), E = layout_end(); I != E; ++I) {
976       auto Next = std::next(I);
977       if (*I == BB && Next != E) {
978         return (IgnoreSplits || (*I)->isCold() == (*Next)->isCold()) ? *Next
979                                                                      : nullptr;
980       }
981     }
982     return nullptr;
983   }
984 
985   /// Retrieve the landing pad BB associated with invoke instruction \p Invoke
986   /// that is in \p BB. Return nullptr if none exists
987   BinaryBasicBlock *getLandingPadBBFor(const BinaryBasicBlock &BB,
988                                        const MCInst &InvokeInst) const {
989     assert(BC.MIB->isInvoke(InvokeInst) && "must be invoke instruction");
990     const Optional<MCPlus::MCLandingPad> LP = BC.MIB->getEHInfo(InvokeInst);
991     if (LP && LP->first) {
992       BinaryBasicBlock *LBB = BB.getLandingPad(LP->first);
993       assert(LBB && "Landing pad should be defined");
994       return LBB;
995     }
996     return nullptr;
997   }
998 
999   /// Return instruction at a given offset in the function. Valid before
1000   /// CFG is constructed or while instruction offsets are available in CFG.
1001   MCInst *getInstructionAtOffset(uint64_t Offset);
1002 
1003   const MCInst *getInstructionAtOffset(uint64_t Offset) const {
1004     return const_cast<BinaryFunction *>(this)->getInstructionAtOffset(Offset);
1005   }
1006 
1007   /// Return offset for the first instruction. If there is data at the
1008   /// beginning of a function then offset of the first instruction could
1009   /// be different from 0
1010   uint64_t getFirstInstructionOffset() const {
1011     if (Instructions.empty())
1012       return 0;
1013     return Instructions.begin()->first;
1014   }
1015 
1016   /// Return jump table that covers a given \p Address in memory.
1017   JumpTable *getJumpTableContainingAddress(uint64_t Address) {
1018     auto JTI = JumpTables.upper_bound(Address);
1019     if (JTI == JumpTables.begin())
1020       return nullptr;
1021     --JTI;
1022     if (JTI->first + JTI->second->getSize() > Address)
1023       return JTI->second;
1024     if (JTI->second->getSize() == 0 && JTI->first == Address)
1025       return JTI->second;
1026     return nullptr;
1027   }
1028 
1029   const JumpTable *getJumpTableContainingAddress(uint64_t Address) const {
1030     return const_cast<BinaryFunction *>(this)->getJumpTableContainingAddress(
1031         Address);
1032   }
1033 
1034   /// Return the name of the function if the function has just one name.
1035   /// If the function has multiple names - return one followed
1036   /// by "(*#<numnames>)".
1037   ///
1038   /// We should use getPrintName() for diagnostics and use
1039   /// hasName() to match function name against a given string.
1040   ///
1041   /// NOTE: for disambiguating names of local symbols we use the following
1042   ///       naming schemes:
1043   ///           primary:     <function>/<id>
1044   ///           alternative: <function>/<file>/<id2>
1045   std::string getPrintName() const {
1046     const size_t NumNames = Symbols.size() + Aliases.size();
1047     return NumNames == 1
1048                ? getOneName().str()
1049                : (getOneName().str() + "(*" + std::to_string(NumNames) + ")");
1050   }
1051 
1052   /// The function may have many names. For that reason, we avoid having
1053   /// getName() method as most of the time the user needs a different
1054   /// interface, such as forEachName(), hasName(), hasNameRegex(), etc.
1055   /// In some cases though, we need just a name uniquely identifying
1056   /// the function, and that's what this method is for.
1057   StringRef getOneName() const { return Symbols[0]->getName(); }
1058 
1059   /// Return the name of the function as getPrintName(), but also trying
1060   /// to demangle it.
1061   std::string getDemangledName() const;
1062 
1063   /// Call \p Callback for every name of this function as long as the Callback
1064   /// returns false. Stop if Callback returns true or all names have been used.
1065   /// Return the name for which the Callback returned true if any.
1066   template <typename FType>
1067   Optional<StringRef> forEachName(FType Callback) const {
1068     for (MCSymbol *Symbol : Symbols)
1069       if (Callback(Symbol->getName()))
1070         return Symbol->getName();
1071 
1072     for (const std::string &Name : Aliases)
1073       if (Callback(StringRef(Name)))
1074         return StringRef(Name);
1075 
1076     return NoneType();
1077   }
1078 
1079   /// Check if (possibly one out of many) function name matches the given
1080   /// string. Use this member function instead of direct name comparison.
1081   bool hasName(const std::string &FunctionName) const {
1082     auto Res =
1083         forEachName([&](StringRef Name) { return Name == FunctionName; });
1084     return Res.hasValue();
1085   }
1086 
1087   /// Check if any of function names matches the given regex.
1088   Optional<StringRef> hasNameRegex(const StringRef NameRegex) const;
1089 
1090   /// Check if any of restored function names matches the given regex.
1091   /// Restored name means stripping BOLT-added suffixes like "/1",
1092   Optional<StringRef> hasRestoredNameRegex(const StringRef NameRegex) const;
1093 
1094   /// Return a vector of all possible names for the function.
1095   const std::vector<StringRef> getNames() const {
1096     std::vector<StringRef> AllNames;
1097     forEachName([&AllNames](StringRef Name) {
1098       AllNames.push_back(Name);
1099       return false;
1100     });
1101 
1102     return AllNames;
1103   }
1104 
1105   /// Return a state the function is in (see BinaryFunction::State definition
1106   /// for description).
1107   State getState() const { return CurrentState; }
1108 
1109   /// Return true if function has a control flow graph available.
1110   bool hasCFG() const {
1111     return getState() == State::CFG || getState() == State::CFG_Finalized ||
1112            getState() == State::EmittedCFG;
1113   }
1114 
1115   /// Return true if the function state implies that it includes instructions.
1116   bool hasInstructions() const {
1117     return getState() == State::Disassembled || hasCFG();
1118   }
1119 
1120   bool isEmitted() const {
1121     return getState() == State::EmittedCFG || getState() == State::Emitted;
1122   }
1123 
1124   /// Return the section in the input binary this function originated from or
1125   /// nullptr if the function did not originate from the file.
1126   BinarySection *getOriginSection() const { return OriginSection; }
1127 
1128   void setOriginSection(BinarySection *Section) { OriginSection = Section; }
1129 
1130   /// Return true if the function did not originate from the primary input file.
1131   bool isInjected() const { return IsInjected; }
1132 
1133   /// Return original address of the function (or offset from base for PIC).
1134   uint64_t getAddress() const { return Address; }
1135 
1136   uint64_t getOutputAddress() const { return OutputAddress; }
1137 
1138   uint64_t getOutputSize() const { return OutputSize; }
1139 
1140   /// Does this function have a valid streaming order index?
1141   bool hasValidIndex() const { return Index != -1U; }
1142 
1143   /// Get the streaming order index for this function.
1144   uint32_t getIndex() const { return Index; }
1145 
1146   /// Set the streaming order index for this function.
1147   void setIndex(uint32_t Idx) {
1148     assert(!hasValidIndex());
1149     Index = Idx;
1150   }
1151 
1152   /// Return offset of the function body in the binary file.
1153   uint64_t getFileOffset() const { return FileOffset; }
1154 
1155   /// Return (original) byte size of the function.
1156   uint64_t getSize() const { return Size; }
1157 
1158   /// Return the maximum size the body of the function could have.
1159   uint64_t getMaxSize() const { return MaxSize; }
1160 
1161   /// Return the number of emitted instructions for this function.
1162   uint32_t getNumNonPseudos() const {
1163     uint32_t N = 0;
1164     for (BinaryBasicBlock *const &BB : layout())
1165       N += BB->getNumNonPseudos();
1166     return N;
1167   }
1168 
1169   /// Return MC symbol associated with the function.
1170   /// All references to the function should use this symbol.
1171   MCSymbol *getSymbol() { return Symbols[0]; }
1172 
1173   /// Return MC symbol associated with the function (const version).
1174   /// All references to the function should use this symbol.
1175   const MCSymbol *getSymbol() const { return Symbols[0]; }
1176 
1177   /// Return a list of symbols associated with the main entry of the function.
1178   SymbolListTy &getSymbols() { return Symbols; }
1179   const SymbolListTy &getSymbols() const { return Symbols; }
1180 
1181   /// If a local symbol \p BBLabel corresponds to a basic block that is a
1182   /// secondary entry point into the function, then return a global symbol
1183   /// that represents the secondary entry point. Otherwise return nullptr.
1184   MCSymbol *getSecondaryEntryPointSymbol(const MCSymbol *BBLabel) const {
1185     auto I = SecondaryEntryPoints.find(BBLabel);
1186     if (I == SecondaryEntryPoints.end())
1187       return nullptr;
1188 
1189     return I->second;
1190   }
1191 
1192   /// If the basic block serves as a secondary entry point to the function,
1193   /// return a global symbol representing the entry. Otherwise return nullptr.
1194   MCSymbol *getSecondaryEntryPointSymbol(const BinaryBasicBlock &BB) const {
1195     return getSecondaryEntryPointSymbol(BB.getLabel());
1196   }
1197 
1198   /// Return true if the basic block is an entry point into the function
1199   /// (either primary or secondary).
1200   bool isEntryPoint(const BinaryBasicBlock &BB) const {
1201     if (&BB == BasicBlocks.front())
1202       return true;
1203     return getSecondaryEntryPointSymbol(BB);
1204   }
1205 
1206   /// Return MC symbol corresponding to an enumerated entry for multiple-entry
1207   /// functions.
1208   MCSymbol *getSymbolForEntryID(uint64_t EntryNum);
1209   const MCSymbol *getSymbolForEntryID(uint64_t EntryNum) const {
1210     return const_cast<BinaryFunction *>(this)->getSymbolForEntryID(EntryNum);
1211   }
1212 
1213   using EntryPointCallbackTy = function_ref<bool(uint64_t, const MCSymbol *)>;
1214 
1215   /// Invoke \p Callback function for every entry point in the function starting
1216   /// with the main entry and using entries in the ascending address order.
1217   /// Stop calling the function after false is returned by the callback.
1218   ///
1219   /// Pass an offset of the entry point in the input binary and a corresponding
1220   /// global symbol to the callback function.
1221   ///
1222   /// Return true of all callbacks returned true, false otherwise.
1223   bool forEachEntryPoint(EntryPointCallbackTy Callback) const;
1224 
1225   MCSymbol *getColdSymbol() {
1226     if (ColdSymbol)
1227       return ColdSymbol;
1228 
1229     ColdSymbol = BC.Ctx->getOrCreateSymbol(
1230         NameResolver::append(getSymbol()->getName(), ".cold.0"));
1231 
1232     return ColdSymbol;
1233   }
1234 
1235   /// Return MC symbol associated with the end of the function.
1236   MCSymbol *getFunctionEndLabel() const {
1237     assert(BC.Ctx && "cannot be called with empty context");
1238     if (!FunctionEndLabel) {
1239       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1240       FunctionEndLabel = BC.Ctx->createNamedTempSymbol("func_end");
1241     }
1242     return FunctionEndLabel;
1243   }
1244 
1245   /// Return MC symbol associated with the end of the cold part of the function.
1246   MCSymbol *getFunctionColdEndLabel() const {
1247     if (!FunctionColdEndLabel) {
1248       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1249       FunctionColdEndLabel = BC.Ctx->createNamedTempSymbol("func_cold_end");
1250     }
1251     return FunctionColdEndLabel;
1252   }
1253 
1254   /// Return a label used to identify where the constant island was emitted
1255   /// (AArch only). This is used to update the symbol table accordingly,
1256   /// emitting data marker symbols as required by the ABI.
1257   MCSymbol *getFunctionConstantIslandLabel() const {
1258     assert(Islands && "function expected to have constant islands");
1259 
1260     if (!Islands->FunctionConstantIslandLabel) {
1261       Islands->FunctionConstantIslandLabel =
1262           BC.Ctx->createNamedTempSymbol("func_const_island");
1263     }
1264     return Islands->FunctionConstantIslandLabel;
1265   }
1266 
1267   MCSymbol *getFunctionColdConstantIslandLabel() const {
1268     assert(Islands && "function expected to have constant islands");
1269 
1270     if (!Islands->FunctionColdConstantIslandLabel) {
1271       Islands->FunctionColdConstantIslandLabel =
1272           BC.Ctx->createNamedTempSymbol("func_cold_const_island");
1273     }
1274     return Islands->FunctionColdConstantIslandLabel;
1275   }
1276 
1277   /// Return true if this is a function representing a PLT entry.
1278   bool isPLTFunction() const { return PLTSymbol != nullptr; }
1279 
1280   /// Return PLT function reference symbol for PLT functions and nullptr for
1281   /// non-PLT functions.
1282   const MCSymbol *getPLTSymbol() const { return PLTSymbol; }
1283 
1284   /// Set function PLT reference symbol for PLT functions.
1285   void setPLTSymbol(const MCSymbol *Symbol) {
1286     assert(Size == 0 && "function size should be 0 for PLT functions");
1287     PLTSymbol = Symbol;
1288     IsPseudo = true;
1289   }
1290 
1291   /// Update output values of the function based on the final \p Layout.
1292   void updateOutputValues(const MCAsmLayout &Layout);
1293 
1294   /// Return mapping of input to output addresses. Most users should call
1295   /// translateInputToOutputAddress() for address translation.
1296   InputOffsetToAddressMapTy &getInputOffsetToAddressMap() {
1297     assert(isEmitted() && "cannot use address mapping before code emission");
1298     return InputOffsetToAddressMap;
1299   }
1300 
1301   void addRelocationAArch64(uint64_t Offset, MCSymbol *Symbol, uint64_t RelType,
1302                             uint64_t Addend, uint64_t Value, bool IsCI) {
1303     std::map<uint64_t, Relocation> &Rels =
1304         (IsCI) ? Islands->Relocations : Relocations;
1305     switch (RelType) {
1306     case ELF::R_AARCH64_ABS64:
1307     case ELF::R_AARCH64_ABS32:
1308     case ELF::R_AARCH64_ABS16:
1309     case ELF::R_AARCH64_ADD_ABS_LO12_NC:
1310     case ELF::R_AARCH64_ADR_GOT_PAGE:
1311     case ELF::R_AARCH64_ADR_PREL_LO21:
1312     case ELF::R_AARCH64_ADR_PREL_PG_HI21:
1313     case ELF::R_AARCH64_ADR_PREL_PG_HI21_NC:
1314     case ELF::R_AARCH64_LD64_GOT_LO12_NC:
1315     case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
1316     case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
1317     case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
1318     case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
1319     case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
1320     case ELF::R_AARCH64_TLSDESC_ADD_LO12:
1321     case ELF::R_AARCH64_TLSDESC_ADR_PAGE21:
1322     case ELF::R_AARCH64_TLSDESC_ADR_PREL21:
1323     case ELF::R_AARCH64_TLSDESC_LD64_LO12:
1324     case ELF::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
1325     case ELF::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1326     case ELF::R_AARCH64_MOVW_UABS_G0:
1327     case ELF::R_AARCH64_MOVW_UABS_G0_NC:
1328     case ELF::R_AARCH64_MOVW_UABS_G1:
1329     case ELF::R_AARCH64_MOVW_UABS_G1_NC:
1330     case ELF::R_AARCH64_MOVW_UABS_G2:
1331     case ELF::R_AARCH64_MOVW_UABS_G2_NC:
1332     case ELF::R_AARCH64_MOVW_UABS_G3:
1333     case ELF::R_AARCH64_PREL16:
1334     case ELF::R_AARCH64_PREL32:
1335     case ELF::R_AARCH64_PREL64:
1336       Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
1337       return;
1338     case ELF::R_AARCH64_CALL26:
1339     case ELF::R_AARCH64_JUMP26:
1340     case ELF::R_AARCH64_TSTBR14:
1341     case ELF::R_AARCH64_CONDBR19:
1342     case ELF::R_AARCH64_TLSDESC_CALL:
1343     case ELF::R_AARCH64_TLSLE_ADD_TPREL_HI12:
1344     case ELF::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
1345       return;
1346     default:
1347       llvm_unreachable("Unexpected AArch64 relocation type in code");
1348     }
1349   }
1350 
1351   void addRelocationX86(uint64_t Offset, MCSymbol *Symbol, uint64_t RelType,
1352                         uint64_t Addend, uint64_t Value) {
1353     switch (RelType) {
1354     case ELF::R_X86_64_8:
1355     case ELF::R_X86_64_16:
1356     case ELF::R_X86_64_32:
1357     case ELF::R_X86_64_32S:
1358     case ELF::R_X86_64_64:
1359     case ELF::R_X86_64_PC8:
1360     case ELF::R_X86_64_PC32:
1361     case ELF::R_X86_64_PC64:
1362     case ELF::R_X86_64_GOTPCRELX:
1363     case ELF::R_X86_64_REX_GOTPCRELX:
1364       Relocations[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
1365       return;
1366     case ELF::R_X86_64_PLT32:
1367     case ELF::R_X86_64_GOTPCREL:
1368     case ELF::R_X86_64_TPOFF32:
1369     case ELF::R_X86_64_GOTTPOFF:
1370       return;
1371     default:
1372       llvm_unreachable("Unexpected x86 relocation type in code");
1373     }
1374   }
1375 
1376   /// Register relocation type \p RelType at a given \p Address in the function
1377   /// against \p Symbol.
1378   /// Assert if the \p Address is not inside this function.
1379   void addRelocation(uint64_t Address, MCSymbol *Symbol, uint64_t RelType,
1380                      uint64_t Addend, uint64_t Value) {
1381     assert(Address >= getAddress() && Address < getAddress() + getMaxSize() &&
1382            "address is outside of the function");
1383     uint64_t Offset = Address - getAddress();
1384     if (BC.isAArch64()) {
1385       return addRelocationAArch64(Offset, Symbol, RelType, Addend, Value,
1386                                   isInConstantIsland(Address));
1387     }
1388 
1389     return addRelocationX86(Offset, Symbol, RelType, Addend, Value);
1390   }
1391 
1392   /// Return the name of the section this function originated from.
1393   Optional<StringRef> getOriginSectionName() const {
1394     if (!OriginSection)
1395       return NoneType();
1396     return OriginSection->getName();
1397   }
1398 
1399   /// Return internal section name for this function.
1400   StringRef getCodeSectionName() const { return StringRef(CodeSectionName); }
1401 
1402   /// Assign a code section name to the function.
1403   void setCodeSectionName(StringRef Name) {
1404     CodeSectionName = std::string(Name);
1405   }
1406 
1407   /// Get output code section.
1408   ErrorOr<BinarySection &> getCodeSection() const {
1409     return BC.getUniqueSectionByName(getCodeSectionName());
1410   }
1411 
1412   /// Return cold code section name for the function.
1413   StringRef getColdCodeSectionName() const {
1414     return StringRef(ColdCodeSectionName);
1415   }
1416 
1417   /// Assign a section name for the cold part of the function.
1418   void setColdCodeSectionName(StringRef Name) {
1419     ColdCodeSectionName = std::string(Name);
1420   }
1421 
1422   /// Get output code section for cold code of this function.
1423   ErrorOr<BinarySection &> getColdCodeSection() const {
1424     return BC.getUniqueSectionByName(getColdCodeSectionName());
1425   }
1426 
1427   /// Return true iif the function will halt execution on entry.
1428   bool trapsOnEntry() const { return TrapsOnEntry; }
1429 
1430   /// Make the function always trap on entry. Other than the trap instruction,
1431   /// the function body will be empty.
1432   void setTrapOnEntry();
1433 
1434   /// Return true if the function could be correctly processed.
1435   bool isSimple() const { return IsSimple; }
1436 
1437   /// Return true if the function should be ignored for optimization purposes.
1438   bool isIgnored() const { return IsIgnored; }
1439 
1440   /// Return true if the function should not be disassembled, emitted, or
1441   /// otherwise processed.
1442   bool isPseudo() const { return IsPseudo; }
1443 
1444   /// Return true if the function contains a jump table with entries pointing
1445   /// to split fragments.
1446   bool hasSplitJumpTable() const { return HasSplitJumpTable; }
1447 
1448   /// Return true if all CFG edges have local successors.
1449   bool hasCanonicalCFG() const { return HasCanonicalCFG; }
1450 
1451   /// Return true if the original function code has all necessary relocations
1452   /// to track addresses of functions emitted to new locations.
1453   bool hasExternalRefRelocations() const { return HasExternalRefRelocations; }
1454 
1455   /// Return true if the function has instruction(s) with unknown control flow.
1456   bool hasUnknownControlFlow() const { return HasUnknownControlFlow; }
1457 
1458   /// Return true if the function body is non-contiguous.
1459   bool isSplit() const {
1460     return isSimple() && layout_size() &&
1461            layout_front()->isCold() != layout_back()->isCold();
1462   }
1463 
1464   bool shouldPreserveNops() const { return PreserveNops; }
1465 
1466   /// Return true if the function has exception handling tables.
1467   bool hasEHRanges() const { return HasEHRanges; }
1468 
1469   /// Return true if the function uses DW_CFA_GNU_args_size CFIs.
1470   bool usesGnuArgsSize() const { return UsesGnuArgsSize; }
1471 
1472   /// Return true if the function has more than one entry point.
1473   bool isMultiEntry() const { return !SecondaryEntryPoints.empty(); }
1474 
1475   /// Return true if the function might have a profile available externally,
1476   /// but not yet populated into the function.
1477   bool hasProfileAvailable() const { return HasProfileAvailable; }
1478 
1479   bool hasMemoryProfile() const { return HasMemoryProfile; }
1480 
1481   /// Return true if the body of the function was merged into another function.
1482   bool isFolded() const { return FoldedIntoFunction != nullptr; }
1483 
1484   /// If this function was folded, return the function it was folded into.
1485   BinaryFunction *getFoldedIntoFunction() const { return FoldedIntoFunction; }
1486 
1487   /// Return true if the function uses jump tables.
1488   bool hasJumpTables() const { return !JumpTables.empty(); }
1489 
1490   /// Return true if the function has SDT marker
1491   bool hasSDTMarker() const { return HasSDTMarker; }
1492 
1493   /// Return true if the function has Pseudo Probe
1494   bool hasPseudoProbe() const { return HasPseudoProbe; }
1495 
1496   /// Return true if the original entry point was patched.
1497   bool isPatched() const { return IsPatched; }
1498 
1499   const JumpTable *getJumpTable(const MCInst &Inst) const {
1500     const uint64_t Address = BC.MIB->getJumpTable(Inst);
1501     return getJumpTableContainingAddress(Address);
1502   }
1503 
1504   JumpTable *getJumpTable(const MCInst &Inst) {
1505     const uint64_t Address = BC.MIB->getJumpTable(Inst);
1506     return getJumpTableContainingAddress(Address);
1507   }
1508 
1509   const MCSymbol *getPersonalityFunction() const { return PersonalityFunction; }
1510 
1511   uint8_t getPersonalityEncoding() const { return PersonalityEncoding; }
1512 
1513   const CallSitesType &getCallSites() const { return CallSites; }
1514 
1515   const CallSitesType &getColdCallSites() const { return ColdCallSites; }
1516 
1517   const ArrayRef<uint8_t> getLSDAActionTable() const { return LSDAActionTable; }
1518 
1519   const LSDATypeTableTy &getLSDATypeTable() const { return LSDATypeTable; }
1520 
1521   const LSDATypeTableTy &getLSDATypeAddressTable() const {
1522     return LSDATypeAddressTable;
1523   }
1524 
1525   const ArrayRef<uint8_t> getLSDATypeIndexTable() const {
1526     return LSDATypeIndexTable;
1527   }
1528 
1529   const LabelsMapType &getLabels() const { return Labels; }
1530 
1531   IslandInfo &getIslandInfo() {
1532     assert(Islands && "function expected to have constant islands");
1533     return *Islands;
1534   }
1535 
1536   const IslandInfo &getIslandInfo() const {
1537     assert(Islands && "function expected to have constant islands");
1538     return *Islands;
1539   }
1540 
1541   /// Return true if the function has CFI instructions
1542   bool hasCFI() const {
1543     return !FrameInstructions.empty() || !CIEFrameInstructions.empty();
1544   }
1545 
1546   /// Return unique number associated with the function.
1547   uint64_t getFunctionNumber() const { return FunctionNumber; }
1548 
1549   /// Return true if the given address \p PC is inside the function body.
1550   bool containsAddress(uint64_t PC, bool UseMaxSize = false) const {
1551     if (UseMaxSize)
1552       return Address <= PC && PC < Address + MaxSize;
1553     return Address <= PC && PC < Address + Size;
1554   }
1555 
1556   /// Create a basic block in the function. The new block is *NOT* inserted
1557   /// into the CFG. The caller must use insertBasicBlocks() to add any new
1558   /// blocks to the CFG.
1559   std::unique_ptr<BinaryBasicBlock>
1560   createBasicBlock(MCSymbol *Label = nullptr) {
1561     if (!Label) {
1562       std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
1563       Label = BC.Ctx->createNamedTempSymbol("BB");
1564     }
1565     auto BB =
1566         std::unique_ptr<BinaryBasicBlock>(new BinaryBasicBlock(this, Label));
1567 
1568     LabelToBB[Label] = BB.get();
1569 
1570     return BB;
1571   }
1572 
1573   /// Create a new basic block with an optional \p Label and add it to the list
1574   /// of basic blocks of this function.
1575   BinaryBasicBlock *addBasicBlock(MCSymbol *Label = nullptr) {
1576     assert(CurrentState == State::CFG && "Can only add blocks in CFG state");
1577 
1578     BasicBlocks.emplace_back(createBasicBlock(Label).release());
1579     BinaryBasicBlock *BB = BasicBlocks.back();
1580 
1581     BB->setIndex(BasicBlocks.size() - 1);
1582     BB->setLayoutIndex(layout_size());
1583     BasicBlocksLayout.emplace_back(BB);
1584 
1585     return BB;
1586   }
1587 
1588   /// Add basic block \BB as an entry point to the function. Return global
1589   /// symbol associated with the entry.
1590   MCSymbol *addEntryPoint(const BinaryBasicBlock &BB);
1591 
1592   /// Mark all blocks that are unreachable from a root (entry point
1593   /// or landing pad) as invalid.
1594   void markUnreachableBlocks();
1595 
1596   /// Rebuilds BBs layout, ignoring dead BBs. Returns the number of removed
1597   /// BBs and the removed number of bytes of code.
1598   std::pair<unsigned, uint64_t> eraseInvalidBBs();
1599 
1600   /// Get the relative order between two basic blocks in the original
1601   /// layout.  The result is > 0 if B occurs before A and < 0 if B
1602   /// occurs after A.  If A and B are the same block, the result is 0.
1603   signed getOriginalLayoutRelativeOrder(const BinaryBasicBlock *A,
1604                                         const BinaryBasicBlock *B) const {
1605     return getIndex(A) - getIndex(B);
1606   }
1607 
1608   /// Insert the BBs contained in NewBBs into the basic blocks for this
1609   /// function. Update the associated state of all blocks as needed, i.e.
1610   /// BB offsets and BB indices. The new BBs are inserted after Start.
1611   /// This operation could affect fallthrough branches for Start.
1612   ///
1613   void
1614   insertBasicBlocks(BinaryBasicBlock *Start,
1615                     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
1616                     const bool UpdateLayout = true,
1617                     const bool UpdateCFIState = true,
1618                     const bool RecomputeLandingPads = true);
1619 
1620   iterator insertBasicBlocks(
1621       iterator StartBB, std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
1622       const bool UpdateLayout = true, const bool UpdateCFIState = true,
1623       const bool RecomputeLandingPads = true);
1624 
1625   /// Update the basic block layout for this function.  The BBs from
1626   /// [Start->Index, Start->Index + NumNewBlocks) are inserted into the
1627   /// layout after the BB indicated by Start.
1628   void updateLayout(BinaryBasicBlock *Start, const unsigned NumNewBlocks);
1629 
1630   /// Make sure basic blocks' indices match the current layout.
1631   void updateLayoutIndices() const {
1632     unsigned Index = 0;
1633     for (BinaryBasicBlock *BB : layout())
1634       BB->setLayoutIndex(Index++);
1635   }
1636 
1637   /// Recompute the CFI state for NumNewBlocks following Start after inserting
1638   /// new blocks into the CFG.  This must be called after updateLayout.
1639   void updateCFIState(BinaryBasicBlock *Start, const unsigned NumNewBlocks);
1640 
1641   /// Return true if we detected ambiguous jump tables in this function, which
1642   /// happen when one JT is used in more than one indirect jumps. This precludes
1643   /// us from splitting edges for this JT unless we duplicate the JT (see
1644   /// disambiguateJumpTables).
1645   bool checkForAmbiguousJumpTables();
1646 
1647   /// Detect when two distinct indirect jumps are using the same jump table and
1648   /// duplicate it, allocating a separate JT for each indirect branch. This is
1649   /// necessary for code transformations on the CFG that change an edge induced
1650   /// by an indirect branch, e.g.: instrumentation or shrink wrapping. However,
1651   /// this is only possible if we are not updating jump tables in place, but are
1652   /// writing it to a new location (moving them).
1653   void disambiguateJumpTables(MCPlusBuilder::AllocatorIdTy AllocId);
1654 
1655   /// Change \p OrigDest to \p NewDest in the jump table used at the end of
1656   /// \p BB. Returns false if \p OrigDest couldn't be find as a valid target
1657   /// and no replacement took place.
1658   bool replaceJumpTableEntryIn(BinaryBasicBlock *BB, BinaryBasicBlock *OldDest,
1659                                BinaryBasicBlock *NewDest);
1660 
1661   /// Split the CFG edge <From, To> by inserting an intermediate basic block.
1662   /// Returns a pointer to this new intermediate basic block. BB "From" will be
1663   /// updated to jump to the intermediate block, which in turn will have an
1664   /// unconditional branch to BB "To".
1665   /// User needs to manually call fixBranches(). This function only creates the
1666   /// correct CFG edges.
1667   BinaryBasicBlock *splitEdge(BinaryBasicBlock *From, BinaryBasicBlock *To);
1668 
1669   /// We may have built an overly conservative CFG for functions with calls
1670   /// to functions that the compiler knows will never return. In this case,
1671   /// clear all successors from these blocks.
1672   void deleteConservativeEdges();
1673 
1674   /// Determine direction of the branch based on the current layout.
1675   /// Callee is responsible of updating basic block indices prior to using
1676   /// this function (e.g. by calling BinaryFunction::updateLayoutIndices()).
1677   static bool isForwardBranch(const BinaryBasicBlock *From,
1678                               const BinaryBasicBlock *To) {
1679     assert(From->getFunction() == To->getFunction() &&
1680            "basic blocks should be in the same function");
1681     return To->getLayoutIndex() > From->getLayoutIndex();
1682   }
1683 
1684   /// Determine direction of the call to callee symbol relative to the start
1685   /// of this function.
1686   /// Note: this doesn't take function splitting into account.
1687   bool isForwardCall(const MCSymbol *CalleeSymbol) const;
1688 
1689   /// Dump function information to debug output. If \p PrintInstructions
1690   /// is true - include instruction disassembly.
1691   void dump(bool PrintInstructions = true) const;
1692 
1693   /// Print function information to the \p OS stream.
1694   void print(raw_ostream &OS, std::string Annotation = "",
1695              bool PrintInstructions = true) const;
1696 
1697   /// Print all relocations between \p Offset and \p Offset + \p Size in
1698   /// this function.
1699   void printRelocations(raw_ostream &OS, uint64_t Offset, uint64_t Size) const;
1700 
1701   /// Return true if function has a profile, even if the profile does not
1702   /// match CFG 100%.
1703   bool hasProfile() const { return ExecutionCount != COUNT_NO_PROFILE; }
1704 
1705   /// Return true if function profile is present and accurate.
1706   bool hasValidProfile() const {
1707     return ExecutionCount != COUNT_NO_PROFILE && ProfileMatchRatio == 1.0f;
1708   }
1709 
1710   /// Mark this function as having a valid profile.
1711   void markProfiled(uint16_t Flags) {
1712     if (ExecutionCount == COUNT_NO_PROFILE)
1713       ExecutionCount = 0;
1714     ProfileFlags = Flags;
1715     ProfileMatchRatio = 1.0f;
1716   }
1717 
1718   /// Return flags describing a profile for this function.
1719   uint16_t getProfileFlags() const { return ProfileFlags; }
1720 
1721   void addCFIInstruction(uint64_t Offset, MCCFIInstruction &&Inst) {
1722     assert(!Instructions.empty());
1723 
1724     // Fix CFI instructions skipping NOPs. We need to fix this because changing
1725     // CFI state after a NOP, besides being wrong and inaccurate,  makes it
1726     // harder for us to recover this information, since we can create empty BBs
1727     // with NOPs and then reorder it away.
1728     // We fix this by moving the CFI instruction just before any NOPs.
1729     auto I = Instructions.lower_bound(Offset);
1730     if (Offset == getSize()) {
1731       assert(I == Instructions.end() && "unexpected iterator value");
1732       // Sometimes compiler issues restore_state after all instructions
1733       // in the function (even after nop).
1734       --I;
1735       Offset = I->first;
1736     }
1737     assert(I->first == Offset && "CFI pointing to unknown instruction");
1738     if (I == Instructions.begin()) {
1739       CIEFrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst));
1740       return;
1741     }
1742 
1743     --I;
1744     while (I != Instructions.begin() && BC.MIB->isNoop(I->second)) {
1745       Offset = I->first;
1746       --I;
1747     }
1748     OffsetToCFI.emplace(Offset, FrameInstructions.size());
1749     FrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst));
1750     return;
1751   }
1752 
1753   BinaryBasicBlock::iterator addCFIInstruction(BinaryBasicBlock *BB,
1754                                                BinaryBasicBlock::iterator Pos,
1755                                                MCCFIInstruction &&Inst) {
1756     size_t Idx = FrameInstructions.size();
1757     FrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst));
1758     return addCFIPseudo(BB, Pos, Idx);
1759   }
1760 
1761   /// Insert a CFI pseudo instruction in a basic block. This pseudo instruction
1762   /// is a placeholder that refers to a real MCCFIInstruction object kept by
1763   /// this function that will be emitted at that position.
1764   BinaryBasicBlock::iterator addCFIPseudo(BinaryBasicBlock *BB,
1765                                           BinaryBasicBlock::iterator Pos,
1766                                           uint32_t Offset) {
1767     MCInst CFIPseudo;
1768     BC.MIB->createCFI(CFIPseudo, Offset);
1769     return BB->insertPseudoInstr(Pos, CFIPseudo);
1770   }
1771 
1772   /// Retrieve the MCCFIInstruction object associated with a CFI pseudo.
1773   const MCCFIInstruction *getCFIFor(const MCInst &Instr) const {
1774     if (!BC.MIB->isCFI(Instr))
1775       return nullptr;
1776     uint32_t Offset = Instr.getOperand(0).getImm();
1777     assert(Offset < FrameInstructions.size() && "Invalid CFI offset");
1778     return &FrameInstructions[Offset];
1779   }
1780 
1781   void setCFIFor(const MCInst &Instr, MCCFIInstruction &&CFIInst) {
1782     assert(BC.MIB->isCFI(Instr) &&
1783            "attempting to change CFI in a non-CFI inst");
1784     uint32_t Offset = Instr.getOperand(0).getImm();
1785     assert(Offset < FrameInstructions.size() && "Invalid CFI offset");
1786     FrameInstructions[Offset] = std::move(CFIInst);
1787   }
1788 
1789   void mutateCFIRegisterFor(const MCInst &Instr, MCPhysReg NewReg);
1790 
1791   const MCCFIInstruction *mutateCFIOffsetFor(const MCInst &Instr,
1792                                              int64_t NewOffset);
1793 
1794   BinaryFunction &setFileOffset(uint64_t Offset) {
1795     FileOffset = Offset;
1796     return *this;
1797   }
1798 
1799   BinaryFunction &setSize(uint64_t S) {
1800     Size = S;
1801     return *this;
1802   }
1803 
1804   BinaryFunction &setMaxSize(uint64_t Size) {
1805     MaxSize = Size;
1806     return *this;
1807   }
1808 
1809   BinaryFunction &setOutputAddress(uint64_t Address) {
1810     OutputAddress = Address;
1811     return *this;
1812   }
1813 
1814   BinaryFunction &setOutputSize(uint64_t Size) {
1815     OutputSize = Size;
1816     return *this;
1817   }
1818 
1819   BinaryFunction &setSimple(bool Simple) {
1820     IsSimple = Simple;
1821     return *this;
1822   }
1823 
1824   void setPseudo(bool Pseudo) { IsPseudo = Pseudo; }
1825 
1826   BinaryFunction &setUsesGnuArgsSize(bool Uses = true) {
1827     UsesGnuArgsSize = Uses;
1828     return *this;
1829   }
1830 
1831   BinaryFunction &setHasProfileAvailable(bool V = true) {
1832     HasProfileAvailable = V;
1833     return *this;
1834   }
1835 
1836   /// Mark function that should not be emitted.
1837   void setIgnored();
1838 
1839   void setIsPatched(bool V) { IsPatched = V; }
1840 
1841   void setHasSplitJumpTable(bool V) { HasSplitJumpTable = V; }
1842 
1843   void setHasCanonicalCFG(bool V) { HasCanonicalCFG = V; }
1844 
1845   void setFolded(BinaryFunction *BF) { FoldedIntoFunction = BF; }
1846 
1847   BinaryFunction &setPersonalityFunction(uint64_t Addr) {
1848     assert(!PersonalityFunction && "can't set personality function twice");
1849     PersonalityFunction = BC.getOrCreateGlobalSymbol(Addr, "FUNCat");
1850     return *this;
1851   }
1852 
1853   BinaryFunction &setPersonalityEncoding(uint8_t Encoding) {
1854     PersonalityEncoding = Encoding;
1855     return *this;
1856   }
1857 
1858   BinaryFunction &setAlignment(uint16_t Align) {
1859     Alignment = Align;
1860     return *this;
1861   }
1862 
1863   uint16_t getAlignment() const { return Alignment; }
1864 
1865   BinaryFunction &setMaxAlignmentBytes(uint16_t MaxAlignBytes) {
1866     MaxAlignmentBytes = MaxAlignBytes;
1867     return *this;
1868   }
1869 
1870   uint16_t getMaxAlignmentBytes() const { return MaxAlignmentBytes; }
1871 
1872   BinaryFunction &setMaxColdAlignmentBytes(uint16_t MaxAlignBytes) {
1873     MaxColdAlignmentBytes = MaxAlignBytes;
1874     return *this;
1875   }
1876 
1877   uint16_t getMaxColdAlignmentBytes() const { return MaxColdAlignmentBytes; }
1878 
1879   BinaryFunction &setImageAddress(uint64_t Address) {
1880     ImageAddress = Address;
1881     return *this;
1882   }
1883 
1884   /// Return the address of this function' image in memory.
1885   uint64_t getImageAddress() const { return ImageAddress; }
1886 
1887   BinaryFunction &setImageSize(uint64_t Size) {
1888     ImageSize = Size;
1889     return *this;
1890   }
1891 
1892   /// Return the size of this function' image in memory.
1893   uint64_t getImageSize() const { return ImageSize; }
1894 
1895   /// Return true if the function is a secondary fragment of another function.
1896   bool isFragment() const { return IsFragment; }
1897 
1898   /// Returns if the given function is a parent fragment of this function.
1899   bool isParentFragment(BinaryFunction *Parent) const {
1900     return ParentFragments.count(Parent);
1901   }
1902 
1903   /// Set the profile data for the number of times the function was called.
1904   BinaryFunction &setExecutionCount(uint64_t Count) {
1905     ExecutionCount = Count;
1906     return *this;
1907   }
1908 
1909   /// Adjust execution count for the function by a given \p Count. The value
1910   /// \p Count will be subtracted from the current function count.
1911   ///
1912   /// The function will proportionally adjust execution count for all
1913   /// basic blocks and edges in the control flow graph.
1914   void adjustExecutionCount(uint64_t Count);
1915 
1916   /// Set LSDA address for the function.
1917   BinaryFunction &setLSDAAddress(uint64_t Address) {
1918     LSDAAddress = Address;
1919     return *this;
1920   }
1921 
1922   /// Set LSDA symbol for the function.
1923   BinaryFunction &setLSDASymbol(MCSymbol *Symbol) {
1924     LSDASymbol = Symbol;
1925     return *this;
1926   }
1927 
1928   /// Return the profile information about the number of times
1929   /// the function was executed.
1930   ///
1931   /// Return COUNT_NO_PROFILE if there's no profile info.
1932   uint64_t getExecutionCount() const { return ExecutionCount; }
1933 
1934   /// Return the raw profile information about the number of branch
1935   /// executions corresponding to this function.
1936   uint64_t getRawBranchCount() const { return RawBranchCount; }
1937 
1938   /// Return the execution count for functions with known profile.
1939   /// Return 0 if the function has no profile.
1940   uint64_t getKnownExecutionCount() const {
1941     return ExecutionCount == COUNT_NO_PROFILE ? 0 : ExecutionCount;
1942   }
1943 
1944   /// Return original LSDA address for the function or NULL.
1945   uint64_t getLSDAAddress() const { return LSDAAddress; }
1946 
1947   /// Return symbol pointing to function's LSDA.
1948   MCSymbol *getLSDASymbol() {
1949     if (LSDASymbol)
1950       return LSDASymbol;
1951     if (CallSites.empty())
1952       return nullptr;
1953 
1954     LSDASymbol = BC.Ctx->getOrCreateSymbol(
1955         Twine("GCC_except_table") + Twine::utohexstr(getFunctionNumber()));
1956 
1957     return LSDASymbol;
1958   }
1959 
1960   /// Return symbol pointing to function's LSDA for the cold part.
1961   MCSymbol *getColdLSDASymbol() {
1962     if (ColdLSDASymbol)
1963       return ColdLSDASymbol;
1964     if (ColdCallSites.empty())
1965       return nullptr;
1966 
1967     ColdLSDASymbol = BC.Ctx->getOrCreateSymbol(
1968         Twine("GCC_cold_except_table") + Twine::utohexstr(getFunctionNumber()));
1969 
1970     return ColdLSDASymbol;
1971   }
1972 
1973   void setOutputDataAddress(uint64_t Address) { OutputDataOffset = Address; }
1974 
1975   uint64_t getOutputDataAddress() const { return OutputDataOffset; }
1976 
1977   void setOutputColdDataAddress(uint64_t Address) {
1978     OutputColdDataOffset = Address;
1979   }
1980 
1981   uint64_t getOutputColdDataAddress() const { return OutputColdDataOffset; }
1982 
1983   /// If \p Address represents an access to a constant island managed by this
1984   /// function, return a symbol so code can safely refer to it. Otherwise,
1985   /// return nullptr. First return value is the symbol for reference in the
1986   /// hot code area while the second return value is the symbol for reference
1987   /// in the cold code area, as when the function is split the islands are
1988   /// duplicated.
1989   MCSymbol *getOrCreateIslandAccess(uint64_t Address) {
1990     if (!Islands)
1991       return nullptr;
1992 
1993     MCSymbol *Symbol;
1994     if (!isInConstantIsland(Address))
1995       return nullptr;
1996 
1997     // Register our island at global namespace
1998     Symbol = BC.getOrCreateGlobalSymbol(Address, "ISLANDat");
1999 
2000     // Internal bookkeeping
2001     const uint64_t Offset = Address - getAddress();
2002     assert((!Islands->Offsets.count(Offset) ||
2003             Islands->Offsets[Offset] == Symbol) &&
2004            "Inconsistent island symbol management");
2005     if (!Islands->Offsets.count(Offset)) {
2006       Islands->Offsets[Offset] = Symbol;
2007       Islands->Symbols.insert(Symbol);
2008     }
2009     return Symbol;
2010   }
2011 
2012   /// Called by an external function which wishes to emit references to constant
2013   /// island symbols of this function. We create a proxy for it, so we emit
2014   /// separate symbols when emitting our constant island on behalf of this other
2015   /// function.
2016   MCSymbol *getOrCreateProxyIslandAccess(uint64_t Address,
2017                                          BinaryFunction &Referrer) {
2018     MCSymbol *Symbol = getOrCreateIslandAccess(Address);
2019     if (!Symbol)
2020       return nullptr;
2021 
2022     MCSymbol *Proxy;
2023     if (!Islands->Proxies[&Referrer].count(Symbol)) {
2024       Proxy = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".proxy.for." +
2025                                         Referrer.getPrintName());
2026       Islands->Proxies[&Referrer][Symbol] = Proxy;
2027       Islands->Proxies[&Referrer][Proxy] = Symbol;
2028     }
2029     Proxy = Islands->Proxies[&Referrer][Symbol];
2030     return Proxy;
2031   }
2032 
2033   /// Make this function depend on \p BF because we have a reference to its
2034   /// constant island. When emitting this function,  we will also emit
2035   //  \p BF's constants. This only happens in custom AArch64 assembly code.
2036   void createIslandDependency(MCSymbol *Island, BinaryFunction *BF) {
2037     if (!Islands)
2038       Islands = std::make_unique<IslandInfo>();
2039 
2040     Islands->Dependency.insert(BF);
2041     Islands->ProxySymbols[Island] = BF;
2042   }
2043 
2044   /// Detects whether \p Address is inside a data region in this function
2045   /// (constant islands).
2046   bool isInConstantIsland(uint64_t Address) const {
2047     if (!Islands)
2048       return false;
2049 
2050     if (Address < getAddress())
2051       return false;
2052 
2053     uint64_t Offset = Address - getAddress();
2054 
2055     if (Offset >= getMaxSize())
2056       return false;
2057 
2058     auto DataIter = Islands->DataOffsets.upper_bound(Offset);
2059     if (DataIter == Islands->DataOffsets.begin())
2060       return false;
2061     DataIter = std::prev(DataIter);
2062 
2063     auto CodeIter = Islands->CodeOffsets.upper_bound(Offset);
2064     if (CodeIter == Islands->CodeOffsets.begin())
2065       return true;
2066 
2067     return *std::prev(CodeIter) <= *DataIter;
2068   }
2069 
2070   uint16_t getConstantIslandAlignment() const {
2071     return Islands ? Islands->getAlignment() : 1;
2072   }
2073 
2074   uint64_t
2075   estimateConstantIslandSize(const BinaryFunction *OnBehalfOf = nullptr) const {
2076     if (!Islands)
2077       return 0;
2078 
2079     uint64_t Size = 0;
2080     for (auto DataIter = Islands->DataOffsets.begin();
2081          DataIter != Islands->DataOffsets.end(); ++DataIter) {
2082       auto NextData = std::next(DataIter);
2083       auto CodeIter = Islands->CodeOffsets.lower_bound(*DataIter);
2084       if (CodeIter == Islands->CodeOffsets.end() &&
2085           NextData == Islands->DataOffsets.end()) {
2086         Size += getMaxSize() - *DataIter;
2087         continue;
2088       }
2089 
2090       uint64_t NextMarker;
2091       if (CodeIter == Islands->CodeOffsets.end())
2092         NextMarker = *NextData;
2093       else if (NextData == Islands->DataOffsets.end())
2094         NextMarker = *CodeIter;
2095       else
2096         NextMarker = (*CodeIter > *NextData) ? *NextData : *CodeIter;
2097 
2098       Size += NextMarker - *DataIter;
2099     }
2100 
2101     if (!OnBehalfOf) {
2102       for (BinaryFunction *ExternalFunc : Islands->Dependency) {
2103         Size = alignTo(Size, ExternalFunc->getConstantIslandAlignment());
2104         Size += ExternalFunc->estimateConstantIslandSize(this);
2105       }
2106     }
2107 
2108     return Size;
2109   }
2110 
2111   bool hasIslandsInfo() const { return !!Islands; }
2112 
2113   bool hasConstantIsland() const {
2114     return Islands && !Islands->DataOffsets.empty();
2115   }
2116 
2117   /// Return true iff the symbol could be seen inside this function otherwise
2118   /// it is probably another function.
2119   bool isSymbolValidInScope(const SymbolRef &Symbol, uint64_t SymbolSize) const;
2120 
2121   /// Disassemble function from raw data.
2122   /// If successful, this function will populate the list of instructions
2123   /// for this function together with offsets from the function start
2124   /// in the input. It will also populate Labels with destinations for
2125   /// local branches, and TakenBranches with [from, to] info.
2126   ///
2127   /// The Function should be properly initialized before this function
2128   /// is called. I.e. function address and size should be set.
2129   ///
2130   /// Returns true on successful disassembly, and updates the current
2131   /// state to State:Disassembled.
2132   ///
2133   /// Returns false if disassembly failed.
2134   bool disassemble();
2135 
2136   /// Scan function for references to other functions. In relocation mode,
2137   /// add relocations for external references.
2138   ///
2139   /// Return true on success.
2140   bool scanExternalRefs();
2141 
2142   /// Return the size of a data object located at \p Offset in the function.
2143   /// Return 0 if there is no data object at the \p Offset.
2144   size_t getSizeOfDataInCodeAt(uint64_t Offset) const;
2145 
2146   /// Verify that starting at \p Offset function contents are filled with
2147   /// zero-value bytes.
2148   bool isZeroPaddingAt(uint64_t Offset) const;
2149 
2150   /// Check that entry points have an associated instruction at their
2151   /// offsets after disassembly.
2152   void postProcessEntryPoints();
2153 
2154   /// Post-processing for jump tables after disassembly. Since their
2155   /// boundaries are not known until all call sites are seen, we need this
2156   /// extra pass to perform any final adjustments.
2157   void postProcessJumpTables();
2158 
2159   /// Builds a list of basic blocks with successor and predecessor info.
2160   ///
2161   /// The function should in Disassembled state prior to call.
2162   ///
2163   /// Returns true on success and update the current function state to
2164   /// State::CFG. Returns false if CFG cannot be built.
2165   bool buildCFG(MCPlusBuilder::AllocatorIdTy);
2166 
2167   /// Perform post-processing of the CFG.
2168   void postProcessCFG();
2169 
2170   /// Verify that any assumptions we've made about indirect branches were
2171   /// correct and also make any necessary changes to unknown indirect branches.
2172   ///
2173   /// Catch-22: we need to know indirect branch targets to build CFG, and
2174   /// in order to determine the value for indirect branches we need to know CFG.
2175   ///
2176   /// As such, the process of decoding indirect branches is broken into 2 steps:
2177   /// first we make our best guess about a branch without knowing the CFG,
2178   /// and later after we have the CFG for the function, we verify our earlier
2179   /// assumptions and also do our best at processing unknown indirect branches.
2180   ///
2181   /// Return true upon successful processing, or false if the control flow
2182   /// cannot be statically evaluated for any given indirect branch.
2183   bool postProcessIndirectBranches(MCPlusBuilder::AllocatorIdTy AllocId);
2184 
2185   /// Return all call site profile info for this function.
2186   IndirectCallSiteProfile &getAllCallSites() { return AllCallSites; }
2187 
2188   const IndirectCallSiteProfile &getAllCallSites() const {
2189     return AllCallSites;
2190   }
2191 
2192   /// Walks the list of basic blocks filling in missing information about
2193   /// edge frequency for fall-throughs.
2194   ///
2195   /// Assumes the CFG has been built and edge frequency for taken branches
2196   /// has been filled with LBR data.
2197   void inferFallThroughCounts();
2198 
2199   /// Clear execution profile of the function.
2200   void clearProfile();
2201 
2202   /// Converts conditional tail calls to unconditional tail calls. We do this to
2203   /// handle conditional tail calls correctly and to give a chance to the
2204   /// simplify conditional tail call pass to decide whether to re-optimize them
2205   /// using profile information.
2206   void removeConditionalTailCalls();
2207 
2208   // Convert COUNT_NO_PROFILE to 0
2209   void removeTagsFromProfile();
2210 
2211   /// Computes a function hotness score: the sum of the products of BB frequency
2212   /// and size.
2213   uint64_t getFunctionScore() const;
2214 
2215   /// Return true if the layout has been changed by basic block reordering,
2216   /// false otherwise.
2217   bool hasLayoutChanged() const;
2218 
2219   /// Get the edit distance of the new layout with respect to the previous
2220   /// layout after basic block reordering.
2221   uint64_t getEditDistance() const;
2222 
2223   /// Get the number of instructions within this function.
2224   uint64_t getInstructionCount() const;
2225 
2226   const CFIInstrMapType &getFDEProgram() const { return FrameInstructions; }
2227 
2228   void moveRememberRestorePair(BinaryBasicBlock *BB);
2229 
2230   bool replayCFIInstrs(int32_t FromState, int32_t ToState,
2231                        BinaryBasicBlock *InBB,
2232                        BinaryBasicBlock::iterator InsertIt);
2233 
2234   /// unwindCFIState is used to unwind from a higher to a lower state number
2235   /// without using remember-restore instructions. We do that by keeping track
2236   /// of what values have been changed from state A to B and emitting
2237   /// instructions that undo this change.
2238   SmallVector<int32_t, 4> unwindCFIState(int32_t FromState, int32_t ToState,
2239                                          BinaryBasicBlock *InBB,
2240                                          BinaryBasicBlock::iterator &InsertIt);
2241 
2242   /// After reordering, this function checks the state of CFI and fixes it if it
2243   /// is corrupted. If it is unable to fix it, it returns false.
2244   bool finalizeCFIState();
2245 
2246   /// Return true if this function needs an address-transaltion table after
2247   /// its code emission.
2248   bool requiresAddressTranslation() const;
2249 
2250   /// Adjust branch instructions to match the CFG.
2251   ///
2252   /// As it comes to internal branches, the CFG represents "the ultimate source
2253   /// of truth". Transformations on functions and blocks have to update the CFG
2254   /// and fixBranches() would make sure the correct branch instructions are
2255   /// inserted at the end of basic blocks.
2256   ///
2257   /// We do require a conditional branch at the end of the basic block if
2258   /// the block has 2 successors as CFG currently lacks the conditional
2259   /// code support (it will probably stay that way). We only use this
2260   /// branch instruction for its conditional code, the destination is
2261   /// determined by CFG - first successor representing true/taken branch,
2262   /// while the second successor - false/fall-through branch.
2263   ///
2264   /// When we reverse the branch condition, the CFG is updated accordingly.
2265   void fixBranches();
2266 
2267   /// Mark function as finalized. No further optimizations are permitted.
2268   void setFinalized() { CurrentState = State::CFG_Finalized; }
2269 
2270   void setEmitted(bool KeepCFG = false) {
2271     CurrentState = State::EmittedCFG;
2272     if (!KeepCFG) {
2273       releaseCFG();
2274       CurrentState = State::Emitted;
2275     }
2276   }
2277 
2278   /// Process LSDA information for the function.
2279   void parseLSDA(ArrayRef<uint8_t> LSDAData, uint64_t LSDAAddress);
2280 
2281   /// Update exception handling ranges for the function.
2282   void updateEHRanges();
2283 
2284   /// Traverse cold basic blocks and replace references to constants in islands
2285   /// with a proxy symbol for the duplicated constant island that is going to be
2286   /// emitted in the cold region.
2287   void duplicateConstantIslands();
2288 
2289   /// Merge profile data of this function into those of the given
2290   /// function. The functions should have been proven identical with
2291   /// isIdenticalWith.
2292   void mergeProfileDataInto(BinaryFunction &BF) const;
2293 
2294   /// Returns the last computed hash value of the function.
2295   size_t getHash() const { return Hash; }
2296 
2297   using OperandHashFuncTy =
2298       function_ref<typename std::string(const MCOperand &)>;
2299 
2300   /// Compute the hash value of the function based on its contents.
2301   ///
2302   /// If \p UseDFS is set, process basic blocks in DFS order. Otherwise, use
2303   /// the existing layout order.
2304   ///
2305   /// By default, instruction operands are ignored while calculating the hash.
2306   /// The caller can change this via passing \p OperandHashFunc function.
2307   /// The return result of this function will be mixed with internal hash.
2308   size_t computeHash(
2309       bool UseDFS = false,
2310       OperandHashFuncTy OperandHashFunc = [](const MCOperand &) {
2311         return std::string();
2312       }) const;
2313 
2314   void setDWARFUnit(DWARFUnit *Unit) { DwarfUnit = Unit; }
2315 
2316   /// Return DWARF compile unit for this function.
2317   DWARFUnit *getDWARFUnit() const { return DwarfUnit; }
2318 
2319   /// Return line info table for this function.
2320   const DWARFDebugLine::LineTable *getDWARFLineTable() const {
2321     return getDWARFUnit() ? BC.DwCtx->getLineTableForUnit(getDWARFUnit())
2322                           : nullptr;
2323   }
2324 
2325   /// Finalize profile for the function.
2326   void postProcessProfile();
2327 
2328   /// Returns an estimate of the function's hot part after splitting.
2329   /// This is a very rough estimate, as with C++ exceptions there are
2330   /// blocks we don't move, and it makes no attempt at estimating the size
2331   /// of the added/removed branch instructions.
2332   /// Note that this size is optimistic and the actual size may increase
2333   /// after relaxation.
2334   size_t estimateHotSize(const bool UseSplitSize = true) const {
2335     size_t Estimate = 0;
2336     if (UseSplitSize && isSplit()) {
2337       for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2338         if (!BB->isCold())
2339           Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2340     } else {
2341       for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2342         if (BB->getKnownExecutionCount() != 0)
2343           Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2344     }
2345     return Estimate;
2346   }
2347 
2348   size_t estimateColdSize() const {
2349     if (!isSplit())
2350       return estimateSize();
2351     size_t Estimate = 0;
2352     for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2353       if (BB->isCold())
2354         Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2355     return Estimate;
2356   }
2357 
2358   size_t estimateSize() const {
2359     size_t Estimate = 0;
2360     for (const BinaryBasicBlock *BB : BasicBlocksLayout)
2361       Estimate += BC.computeCodeSize(BB->begin(), BB->end());
2362     return Estimate;
2363   }
2364 
2365   /// Return output address ranges for a function.
2366   DebugAddressRangesVector getOutputAddressRanges() const;
2367 
2368   /// Given an address corresponding to an instruction in the input binary,
2369   /// return an address of this instruction in output binary.
2370   ///
2371   /// Return 0 if no matching address could be found or the instruction was
2372   /// removed.
2373   uint64_t translateInputToOutputAddress(uint64_t Address) const;
2374 
2375   /// Take address ranges corresponding to the input binary and translate
2376   /// them to address ranges in the output binary.
2377   DebugAddressRangesVector translateInputToOutputRanges(
2378       const DWARFAddressRangesVector &InputRanges) const;
2379 
2380   /// Similar to translateInputToOutputRanges() but operates on location lists
2381   /// and moves associated data to output location lists.
2382   DebugLocationsVector
2383   translateInputToOutputLocationList(const DebugLocationsVector &InputLL) const;
2384 
2385   /// Return true if the function is an AArch64 linker inserted veneer
2386   bool isAArch64Veneer() const;
2387 
2388   virtual ~BinaryFunction();
2389 
2390   /// Info for fragmented functions.
2391   class FragmentInfo {
2392   private:
2393     uint64_t Address{0};
2394     uint64_t ImageAddress{0};
2395     uint64_t ImageSize{0};
2396     uint64_t FileOffset{0};
2397 
2398   public:
2399     uint64_t getAddress() const { return Address; }
2400     uint64_t getImageAddress() const { return ImageAddress; }
2401     uint64_t getImageSize() const { return ImageSize; }
2402     uint64_t getFileOffset() const { return FileOffset; }
2403 
2404     void setAddress(uint64_t VAddress) { Address = VAddress; }
2405     void setImageAddress(uint64_t Address) { ImageAddress = Address; }
2406     void setImageSize(uint64_t Size) { ImageSize = Size; }
2407     void setFileOffset(uint64_t Offset) { FileOffset = Offset; }
2408   };
2409 
2410   /// Cold fragment of the function.
2411   FragmentInfo ColdFragment;
2412 
2413   FragmentInfo &cold() { return ColdFragment; }
2414 
2415   const FragmentInfo &cold() const { return ColdFragment; }
2416 };
2417 
2418 inline raw_ostream &operator<<(raw_ostream &OS,
2419                                const BinaryFunction &Function) {
2420   OS << Function.getPrintName();
2421   return OS;
2422 }
2423 
2424 } // namespace bolt
2425 
2426 // GraphTraits specializations for function basic block graphs (CFGs)
2427 template <>
2428 struct GraphTraits<bolt::BinaryFunction *>
2429     : public GraphTraits<bolt::BinaryBasicBlock *> {
2430   static NodeRef getEntryNode(bolt::BinaryFunction *F) {
2431     return *F->layout_begin();
2432   }
2433 
2434   using nodes_iterator = pointer_iterator<bolt::BinaryFunction::iterator>;
2435 
2436   static nodes_iterator nodes_begin(bolt::BinaryFunction *F) {
2437     llvm_unreachable("Not implemented");
2438     return nodes_iterator(F->begin());
2439   }
2440   static nodes_iterator nodes_end(bolt::BinaryFunction *F) {
2441     llvm_unreachable("Not implemented");
2442     return nodes_iterator(F->end());
2443   }
2444   static size_t size(bolt::BinaryFunction *F) { return F->size(); }
2445 };
2446 
2447 template <>
2448 struct GraphTraits<const bolt::BinaryFunction *>
2449     : public GraphTraits<const bolt::BinaryBasicBlock *> {
2450   static NodeRef getEntryNode(const bolt::BinaryFunction *F) {
2451     return *F->layout_begin();
2452   }
2453 
2454   using nodes_iterator = pointer_iterator<bolt::BinaryFunction::const_iterator>;
2455 
2456   static nodes_iterator nodes_begin(const bolt::BinaryFunction *F) {
2457     llvm_unreachable("Not implemented");
2458     return nodes_iterator(F->begin());
2459   }
2460   static nodes_iterator nodes_end(const bolt::BinaryFunction *F) {
2461     llvm_unreachable("Not implemented");
2462     return nodes_iterator(F->end());
2463   }
2464   static size_t size(const bolt::BinaryFunction *F) { return F->size(); }
2465 };
2466 
2467 template <>
2468 struct GraphTraits<Inverse<bolt::BinaryFunction *>>
2469     : public GraphTraits<Inverse<bolt::BinaryBasicBlock *>> {
2470   static NodeRef getEntryNode(Inverse<bolt::BinaryFunction *> G) {
2471     return *G.Graph->layout_begin();
2472   }
2473 };
2474 
2475 template <>
2476 struct GraphTraits<Inverse<const bolt::BinaryFunction *>>
2477     : public GraphTraits<Inverse<const bolt::BinaryBasicBlock *>> {
2478   static NodeRef getEntryNode(Inverse<const bolt::BinaryFunction *> G) {
2479     return *G.Graph->layout_begin();
2480   }
2481 };
2482 
2483 } // namespace llvm
2484 
2485 #endif
2486