xref: /llvm-project/bolt/runtime/instr.cpp (revision eaf1b5664b0c4fecf992c7385caad56fdb00d18c)
12f09f445SMaksim Panchenko //===- bolt/runtime/instr.cpp ---------------------------------------------===//
262aa74f8SRafael Auler //
3da752c9cSRafael Auler // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4da752c9cSRafael Auler // See https://llvm.org/LICENSE.txt for license information.
5da752c9cSRafael Auler // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
662aa74f8SRafael Auler //
762aa74f8SRafael Auler //===----------------------------------------------------------------------===//
862aa74f8SRafael Auler //
916a497c6SRafael Auler // BOLT runtime instrumentation library for x86 Linux. Currently, BOLT does
1016a497c6SRafael Auler // not support linking modules with dependencies on one another into the final
1116a497c6SRafael Auler // binary (TODO?), which means this library has to be self-contained in a single
1216a497c6SRafael Auler // module.
1316a497c6SRafael Auler //
1416a497c6SRafael Auler // All extern declarations here need to be defined by BOLT itself. Those will be
1516a497c6SRafael Auler // undefined symbols that BOLT needs to resolve by emitting these symbols with
1616a497c6SRafael Auler // MCStreamer. Currently, Passes/Instrumentation.cpp is the pass responsible
1716a497c6SRafael Auler // for defining the symbols here and these two files have a tight coupling: one
1816a497c6SRafael Auler // working statically when you run BOLT and another during program runtime when
1916a497c6SRafael Auler // you run an instrumented binary. The main goal here is to output an fdata file
2016a497c6SRafael Auler // (BOLT profile) with the instrumentation counters inserted by the static pass.
2116a497c6SRafael Auler // Counters for indirect calls are an exception, as we can't know them
2216a497c6SRafael Auler // statically. These counters are created and managed here. To allow this, we
2316a497c6SRafael Auler // need a minimal framework for allocating memory dynamically. We provide this
2416a497c6SRafael Auler // with the BumpPtrAllocator class (not LLVM's, but our own version of it).
2516a497c6SRafael Auler //
2616a497c6SRafael Auler // Since this code is intended to be inserted into any executable, we decided to
2716a497c6SRafael Auler // make it standalone and do not depend on any external libraries (i.e. language
2816a497c6SRafael Auler // support libraries, such as glibc or stdc++). To allow this, we provide a few
2916a497c6SRafael Auler // light implementations of common OS interacting functionalities using direct
3016a497c6SRafael Auler // syscall wrappers. Our simple allocator doesn't manage deallocations that
3116a497c6SRafael Auler // fragment the memory space, so it's stack based. This is the minimal framework
3216a497c6SRafael Auler // provided here to allow processing instrumented counters and writing fdata.
3316a497c6SRafael Auler //
3416a497c6SRafael Auler // In the C++ idiom used here, we never use or rely on constructors or
3516a497c6SRafael Auler // destructors for global objects. That's because those need support from the
3616a497c6SRafael Auler // linker in initialization/finalization code, and we want to keep our linker
3716a497c6SRafael Auler // very simple. Similarly, we don't create any global objects that are zero
3816a497c6SRafael Auler // initialized, since those would need to go .bss, which our simple linker also
3916a497c6SRafael Auler // don't support (TODO?).
4062aa74f8SRafael Auler //
4162aa74f8SRafael Auler //===----------------------------------------------------------------------===//
4262aa74f8SRafael Auler 
43cb8d701bSVladislav Khmelevsky #if defined (__x86_64__)
449bd71615SXun Li #include "common.h"
4562aa74f8SRafael Auler 
4616a497c6SRafael Auler // Enables a very verbose logging to stderr useful when debugging
47cc4b2fb6SRafael Auler //#define ENABLE_DEBUG
48cc4b2fb6SRafael Auler 
49cc4b2fb6SRafael Auler #ifdef ENABLE_DEBUG
50cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
51cc4b2fb6SRafael Auler   { X; }
52cc4b2fb6SRafael Auler #else
53cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
54cc4b2fb6SRafael Auler   {}
55cc4b2fb6SRafael Auler #endif
56cc4b2fb6SRafael Auler 
57af58da4eSVladislav Khmelevsky #pragma GCC visibility push(hidden)
583b876cc3SAlexander Shaposhnikov 
593b876cc3SAlexander Shaposhnikov extern "C" {
60553f28e9SVladislav Khmelevsky 
61553f28e9SVladislav Khmelevsky #if defined(__APPLE__)
623b876cc3SAlexander Shaposhnikov extern uint64_t* _bolt_instr_locations_getter();
633b876cc3SAlexander Shaposhnikov extern uint32_t _bolt_num_counters_getter();
643b876cc3SAlexander Shaposhnikov 
65a0dd5b05SAlexander Shaposhnikov extern uint8_t* _bolt_instr_tables_getter();
66a0dd5b05SAlexander Shaposhnikov extern uint32_t _bolt_instr_num_funcs_getter();
673b876cc3SAlexander Shaposhnikov 
683b876cc3SAlexander Shaposhnikov #else
69bbd9d610SAlexander Shaposhnikov 
7016a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when
7116a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct
7216a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters
7316a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be
7416a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG.
7562aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[];
7616a497c6SRafael Auler extern uint32_t __bolt_num_counters;
7716a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT,
7816a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a
7916a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs,
8016a497c6SRafael Auler // Location, IntrumentedNode and EntryNode.
8116a497c6SRafael Auler // Number of indirect call site descriptions
8216a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls;
8316a497c6SRafael Auler // Number of indirect call target descriptions
8416a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets;
85cc4b2fb6SRafael Auler // Number of function descriptions
86cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs;
8716a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk)
8816a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time;
8976d346caSVladislav Khmelevsky // Do not clear counters across dumps, rewrite file with the updated values
9076d346caSVladislav Khmelevsky extern bool __bolt_instr_no_counters_clear;
9176d346caSVladislav Khmelevsky // Wait until all forks of instrumented process will finish
9276d346caSVladislav Khmelevsky extern bool __bolt_instr_wait_forks;
93cc4b2fb6SRafael Auler // Filename to dump data to
9462aa74f8SRafael Auler extern char __bolt_instr_filename[];
95519cbbaaSVasily Leonenko // Instumented binary file path
96519cbbaaSVasily Leonenko extern char __bolt_instr_binpath[];
9716a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so
9816a497c6SRafael Auler // different invocations of the same program can be differentiated.
9916a497c6SRafael Auler extern bool __bolt_instr_use_pid;
10016a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass
10116a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these
10216a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to
10316a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We
10416a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT,
10516a497c6SRafael Auler // *not* the other way around.
10616a497c6SRafael Auler // TODO: We need better linking support to make that happen.
107361f3b55SVladislav Khmelevsky extern void (*__bolt_ind_call_counter_func_pointer)();
108361f3b55SVladislav Khmelevsky extern void (*__bolt_ind_tailcall_counter_func_pointer)();
109ad79d517SVasily Leonenko // Function pointers to init/fini trampoline routines in the binary, so we can
110ad79d517SVasily Leonenko // resume regular execution of these functions that we hooked
111553f28e9SVladislav Khmelevsky extern void __bolt_start_trampoline();
112553f28e9SVladislav Khmelevsky extern void __bolt_fini_trampoline();
11362aa74f8SRafael Auler 
114a0dd5b05SAlexander Shaposhnikov #endif
115553f28e9SVladislav Khmelevsky }
116a0dd5b05SAlexander Shaposhnikov 
117cc4b2fb6SRafael Auler namespace {
118cc4b2fb6SRafael Auler 
119cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space
120cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that
12116a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements.
12216a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we
12316a497c6SRafael Auler /// are done processing something.
124cc4b2fb6SRafael Auler class BumpPtrAllocator {
12516a497c6SRafael Auler   /// This is written before each allocation and act as a canary to detect when
12616a497c6SRafael Auler   /// a bug caused our program to cross allocation boundaries.
127cc4b2fb6SRafael Auler   struct EntryMetadata {
128cc4b2fb6SRafael Auler     uint64_t Magic;
129cc4b2fb6SRafael Auler     uint64_t AllocSize;
130cc4b2fb6SRafael Auler   };
1319bd71615SXun Li 
132cc4b2fb6SRafael Auler public:
133faaefff6SAlexander Shaposhnikov   void *allocate(size_t Size) {
13416a497c6SRafael Auler     Lock L(M);
135a0dd5b05SAlexander Shaposhnikov 
136cc4b2fb6SRafael Auler     if (StackBase == nullptr) {
137a0dd5b05SAlexander Shaposhnikov #if defined(__APPLE__)
138a0dd5b05SAlexander Shaposhnikov     int MAP_PRIVATE_MAP_ANONYMOUS = 0x1002;
139a0dd5b05SAlexander Shaposhnikov #else
140a0dd5b05SAlexander Shaposhnikov     int MAP_PRIVATE_MAP_ANONYMOUS = 0x22;
141a0dd5b05SAlexander Shaposhnikov #endif
14216a497c6SRafael Auler       StackBase = reinterpret_cast<uint8_t *>(
14316a497c6SRafael Auler           __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/,
14416a497c6SRafael Auler                  Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/
145a0dd5b05SAlexander Shaposhnikov                         : MAP_PRIVATE_MAP_ANONYMOUS /* MAP_PRIVATE | MAP_ANONYMOUS*/,
14616a497c6SRafael Auler                  -1, 0));
147cc4b2fb6SRafael Auler       StackSize = 0;
148cc4b2fb6SRafael Auler     }
149a0dd5b05SAlexander Shaposhnikov 
150cc4b2fb6SRafael Auler     Size = alignTo(Size + sizeof(EntryMetadata), 16);
151cc4b2fb6SRafael Auler     uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata);
152cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize);
15316a497c6SRafael Auler     M->Magic = Magic;
154cc4b2fb6SRafael Auler     M->AllocSize = Size;
155cc4b2fb6SRafael Auler     StackSize += Size;
15616a497c6SRafael Auler     assert(StackSize < MaxSize, "allocator ran out of memory");
157cc4b2fb6SRafael Auler     return AllocAddress;
158cc4b2fb6SRafael Auler   }
159cc4b2fb6SRafael Auler 
16016a497c6SRafael Auler #ifdef DEBUG
16116a497c6SRafael Auler   /// Element-wise deallocation is only used for debugging to catch memory
16216a497c6SRafael Auler   /// bugs by checking magic bytes. Ordinarily, we reset the allocator once
16316a497c6SRafael Auler   /// we are done with it. Reset is done with clear(). There's no need
16416a497c6SRafael Auler   /// to deallocate each element individually.
165cc4b2fb6SRafael Auler   void deallocate(void *Ptr) {
16616a497c6SRafael Auler     Lock L(M);
167cc4b2fb6SRafael Auler     uint8_t MetadataOffset = sizeof(EntryMetadata);
168cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(
169cc4b2fb6SRafael Auler         reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset);
170cc4b2fb6SRafael Auler     const uint8_t *StackTop = StackBase + StackSize + MetadataOffset;
171cc4b2fb6SRafael Auler     // Validate size
172cc4b2fb6SRafael Auler     if (Ptr != StackTop - M->AllocSize) {
17316a497c6SRafael Auler       // Failed validation, check if it is a pointer returned by operator new []
174cc4b2fb6SRafael Auler       MetadataOffset +=
175cc4b2fb6SRafael Auler           sizeof(uint64_t); // Space for number of elements alloc'ed
176cc4b2fb6SRafael Auler       M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) -
177cc4b2fb6SRafael Auler                                             MetadataOffset);
17816a497c6SRafael Auler       // Ok, it failed both checks if this assertion fails. Stop the program, we
17916a497c6SRafael Auler       // have a memory bug.
180cc4b2fb6SRafael Auler       assert(Ptr == StackTop - M->AllocSize,
181cc4b2fb6SRafael Auler              "must deallocate the last element alloc'ed");
182cc4b2fb6SRafael Auler     }
18316a497c6SRafael Auler     assert(M->Magic == Magic, "allocator magic is corrupt");
184cc4b2fb6SRafael Auler     StackSize -= M->AllocSize;
185cc4b2fb6SRafael Auler   }
18616a497c6SRafael Auler #else
18716a497c6SRafael Auler   void deallocate(void *) {}
18816a497c6SRafael Auler #endif
18916a497c6SRafael Auler 
19016a497c6SRafael Auler   void clear() {
19116a497c6SRafael Auler     Lock L(M);
19216a497c6SRafael Auler     StackSize = 0;
19316a497c6SRafael Auler   }
19416a497c6SRafael Auler 
19516a497c6SRafael Auler   /// Set mmap reservation size (only relevant before first allocation)
1969bd71615SXun Li   void setMaxSize(uint64_t Size) { MaxSize = Size; }
19716a497c6SRafael Auler 
19816a497c6SRafael Auler   /// Set mmap reservation privacy (only relevant before first allocation)
1999bd71615SXun Li   void setShared(bool S) { Shared = S; }
20016a497c6SRafael Auler 
20116a497c6SRafael Auler   void destroy() {
20216a497c6SRafael Auler     if (StackBase == nullptr)
20316a497c6SRafael Auler       return;
20416a497c6SRafael Auler     __munmap(StackBase, MaxSize);
20516a497c6SRafael Auler   }
206cc4b2fb6SRafael Auler 
207cc4b2fb6SRafael Auler private:
20816a497c6SRafael Auler   static constexpr uint64_t Magic = 0x1122334455667788ull;
20916a497c6SRafael Auler   uint64_t MaxSize = 0xa00000;
210cc4b2fb6SRafael Auler   uint8_t *StackBase{nullptr};
211cc4b2fb6SRafael Auler   uint64_t StackSize{0};
21216a497c6SRafael Auler   bool Shared{false};
21316a497c6SRafael Auler   Mutex M;
214cc4b2fb6SRafael Auler };
215cc4b2fb6SRafael Auler 
21616a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by
21716a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine.
21816a497c6SRafael Auler BumpPtrAllocator GlobalAlloc;
219cc4b2fb6SRafael Auler } // anonymous namespace
220cc4b2fb6SRafael Auler 
221cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to
222cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the
223cc4b2fb6SRafael Auler // stack instead of in a data section (global).
224faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); }
225faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A, char C) {
226cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
227ea2182feSMaksim Panchenko   memset(Ptr, C, Sz);
228cc4b2fb6SRafael Auler   return Ptr;
229cc4b2fb6SRafael Auler }
230faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A) {
231cc4b2fb6SRafael Auler   return A.allocate(Sz);
232cc4b2fb6SRafael Auler }
233faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A, char C) {
234cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
235ea2182feSMaksim Panchenko   memset(Ptr, C, Sz);
236cc4b2fb6SRafael Auler   return Ptr;
237cc4b2fb6SRafael Auler }
238cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc.
239cc4b2fb6SRafael Auler // C++ language weirdness
2409bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); }
241cc4b2fb6SRafael Auler 
242cc4b2fb6SRafael Auler namespace {
243cc4b2fb6SRafael Auler 
2449aa134dcSVasily Leonenko // Disable instrumentation optimizations that sacrifice profile accuracy
2459aa134dcSVasily Leonenko extern "C" bool __bolt_instr_conservative;
2469aa134dcSVasily Leonenko 
24716a497c6SRafael Auler /// Basic key-val atom stored in our hash
24816a497c6SRafael Auler struct SimpleHashTableEntryBase {
24916a497c6SRafael Auler   uint64_t Key;
25016a497c6SRafael Auler   uint64_t Val;
25116a497c6SRafael Auler };
25216a497c6SRafael Auler 
25316a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size
25416a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves
25516a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our
25616a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers.
25716a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime).
25816a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO)
25916a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it
26016a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for
26116a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a
26216a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites)
26316a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7,
26416a497c6SRafael Auler           uint32_t IncSize = 7>
26516a497c6SRafael Auler class SimpleHashTable {
26616a497c6SRafael Auler public:
26716a497c6SRafael Auler   using MapEntry = T;
26816a497c6SRafael Auler 
26916a497c6SRafael Auler   /// Increment by 1 the value of \p Key. If it is not in this table, it will be
27016a497c6SRafael Auler   /// added to the table and its value set to 1.
27116a497c6SRafael Auler   void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) {
27216a497c6SRafael Auler     ++get(Key, Alloc).Val;
27316a497c6SRafael Auler   }
27416a497c6SRafael Auler 
27516a497c6SRafael Auler   /// Basic member accessing interface. Here we pass the allocator explicitly to
27616a497c6SRafael Auler   /// avoid storing a pointer to it as part of this table (remember there is one
27716a497c6SRafael Auler   /// hash for each indirect call site, so we wan't to minimize our footprint).
27816a497c6SRafael Auler   MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) {
2799aa134dcSVasily Leonenko     if (!__bolt_instr_conservative) {
2809aa134dcSVasily Leonenko       TryLock L(M);
2819aa134dcSVasily Leonenko       if (!L.isLocked())
2829aa134dcSVasily Leonenko         return NoEntry;
2839aa134dcSVasily Leonenko       return getOrAllocEntry(Key, Alloc);
2849aa134dcSVasily Leonenko     }
28516a497c6SRafael Auler     Lock L(M);
2869aa134dcSVasily Leonenko     return getOrAllocEntry(Key, Alloc);
28716a497c6SRafael Auler   }
28816a497c6SRafael Auler 
28916a497c6SRafael Auler   /// Traverses all elements in the table
29016a497c6SRafael Auler   template <typename... Args>
29116a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) {
292bd301a41SMichał Chojnowski     Lock L(M);
29316a497c6SRafael Auler     if (!TableRoot)
29416a497c6SRafael Auler       return;
29516a497c6SRafael Auler     return forEachElement(Callback, InitialSize, TableRoot, args...);
29616a497c6SRafael Auler   }
29716a497c6SRafael Auler 
29816a497c6SRafael Auler   void resetCounters();
29916a497c6SRafael Auler 
30016a497c6SRafael Auler private:
30116a497c6SRafael Auler   constexpr static uint64_t VacantMarker = 0;
30216a497c6SRafael Auler   constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull;
30316a497c6SRafael Auler 
30416a497c6SRafael Auler   MapEntry *TableRoot{nullptr};
3059aa134dcSVasily Leonenko   MapEntry NoEntry;
30616a497c6SRafael Auler   Mutex M;
30716a497c6SRafael Auler 
30816a497c6SRafael Auler   template <typename... Args>
30916a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...),
31016a497c6SRafael Auler                       uint32_t NumEntries, MapEntry *Entries, Args... args) {
311c7306cc2SAmir Ayupov     for (uint32_t I = 0; I < NumEntries; ++I) {
312c7306cc2SAmir Ayupov       MapEntry &Entry = Entries[I];
31316a497c6SRafael Auler       if (Entry.Key == VacantMarker)
31416a497c6SRafael Auler         continue;
31516a497c6SRafael Auler       if (Entry.Key & FollowUpTableMarker) {
31616a497c6SRafael Auler         forEachElement(Callback, IncSize,
31716a497c6SRafael Auler                        reinterpret_cast<MapEntry *>(Entry.Key &
31816a497c6SRafael Auler                                                     ~FollowUpTableMarker),
31916a497c6SRafael Auler                        args...);
32016a497c6SRafael Auler         continue;
32116a497c6SRafael Auler       }
32216a497c6SRafael Auler       Callback(Entry, args...);
32316a497c6SRafael Auler     }
32416a497c6SRafael Auler   }
32516a497c6SRafael Auler 
32616a497c6SRafael Auler   MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) {
32716a497c6SRafael Auler     TableRoot = new (Alloc, 0) MapEntry[InitialSize];
328c7306cc2SAmir Ayupov     MapEntry &Entry = TableRoot[Key % InitialSize];
32916a497c6SRafael Auler     Entry.Key = Key;
33016a497c6SRafael Auler     return Entry;
33116a497c6SRafael Auler   }
33216a497c6SRafael Auler 
33316a497c6SRafael Auler   MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector,
33416a497c6SRafael Auler                      BumpPtrAllocator &Alloc, int CurLevel) {
33516a497c6SRafael Auler     const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize;
33616a497c6SRafael Auler     uint64_t Remainder = Selector / NumEntries;
33716a497c6SRafael Auler     Selector = Selector % NumEntries;
338c7306cc2SAmir Ayupov     MapEntry &Entry = Entries[Selector];
33916a497c6SRafael Auler 
34016a497c6SRafael Auler     // A hit
34116a497c6SRafael Auler     if (Entry.Key == Key) {
34216a497c6SRafael Auler       return Entry;
34316a497c6SRafael Auler     }
34416a497c6SRafael Auler 
34516a497c6SRafael Auler     // Vacant - add new entry
34616a497c6SRafael Auler     if (Entry.Key == VacantMarker) {
34716a497c6SRafael Auler       Entry.Key = Key;
34816a497c6SRafael Auler       return Entry;
34916a497c6SRafael Auler     }
35016a497c6SRafael Auler 
35116a497c6SRafael Auler     // Defer to the next level
35216a497c6SRafael Auler     if (Entry.Key & FollowUpTableMarker) {
35316a497c6SRafael Auler       return getEntry(
35416a497c6SRafael Auler           reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker),
35516a497c6SRafael Auler           Key, Remainder, Alloc, CurLevel + 1);
35616a497c6SRafael Auler     }
35716a497c6SRafael Auler 
35816a497c6SRafael Auler     // Conflict - create the next level
35916a497c6SRafael Auler     MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize];
36016a497c6SRafael Auler     uint64_t CurEntrySelector = Entry.Key / InitialSize;
36116a497c6SRafael Auler     for (int I = 0; I < CurLevel; ++I)
36216a497c6SRafael Auler       CurEntrySelector /= IncSize;
36316a497c6SRafael Auler     CurEntrySelector = CurEntrySelector % IncSize;
36416a497c6SRafael Auler     NextLevelTbl[CurEntrySelector] = Entry;
36516a497c6SRafael Auler     Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker;
36616a497c6SRafael Auler     return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1);
36716a497c6SRafael Auler   }
3689aa134dcSVasily Leonenko 
3699aa134dcSVasily Leonenko   MapEntry &getOrAllocEntry(uint64_t Key, BumpPtrAllocator &Alloc) {
3709aa134dcSVasily Leonenko     if (TableRoot)
3719aa134dcSVasily Leonenko       return getEntry(TableRoot, Key, Key, Alloc, 0);
3729aa134dcSVasily Leonenko     return firstAllocation(Key, Alloc);
3739aa134dcSVasily Leonenko   }
37416a497c6SRafael Auler };
37516a497c6SRafael Auler 
37616a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) {
37716a497c6SRafael Auler   Entry.Val = 0;
37816a497c6SRafael Auler }
37916a497c6SRafael Auler 
38016a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y>
38116a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() {
38216a497c6SRafael Auler   forEachElement(resetIndCallCounter);
38316a497c6SRafael Auler }
38416a497c6SRafael Auler 
38516a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter.
38616a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>;
38716a497c6SRafael Auler 
38816a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the
38916a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening
39016a497c6SRafael Auler /// during runtime, one table per call site.
39116a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{
39216a497c6SRafael Auler     reinterpret_cast<IndirectCallHashTable *>(1)};
39316a497c6SRafael Auler 
39416a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes
39516a497c6SRafael Auler /// it
39616a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)};
39716a497c6SRafael Auler 
39816a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency
39916a497c6SRafael Auler /// as perceived by the basic block counter (Val).
40016a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase {
40116a497c6SRafael Auler   uint64_t Calls;
40216a497c6SRafael Auler };
40316a497c6SRafael Auler 
40416a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>;
40516a497c6SRafael Auler 
40616a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and
40716a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for
40816a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the
40916a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two
41016a497c6SRafael Auler /// possible scenarios here:
41116a497c6SRafael Auler ///
41216a497c6SRafael Auler ///  * Entry BB has higher frequency than all known calls to this function.
41316a497c6SRafael Auler ///    In this case, we have dynamic library code or any uninstrumented code
41416a497c6SRafael Auler ///    calling this function. We will write the profile for these untracked
41516a497c6SRafael Auler ///    calls as having source "0 [unknown] 0" in the fdata file.
41616a497c6SRafael Auler ///
41716a497c6SRafael Auler ///  * Number of known calls is higher than the frequency of entry BB
41816a497c6SRafael Auler ///    This only happens when there is no counter for the entry BB / callee
41916a497c6SRafael Auler ///    function is not simple (in BOLT terms). We don't do anything special
42016a497c6SRafael Auler ///    here and just ignore those (we still report all calls to the non-simple
42116a497c6SRafael Auler ///    function, though).
42216a497c6SRafael Auler ///
42316a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase {
42416a497c6SRafael Auler public:
42516a497c6SRafael Auler   CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
42616a497c6SRafael Auler 
42716a497c6SRafael Auler   MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); }
42816a497c6SRafael Auler 
42916a497c6SRafael Auler private:
43016a497c6SRafael Auler   // Different than the hash table for indirect call targets, we do store the
43116a497c6SRafael Auler   // allocator here since there is only one call flow hash and space overhead
43216a497c6SRafael Auler   // is negligible.
43316a497c6SRafael Auler   BumpPtrAllocator &Alloc;
43416a497c6SRafael Auler };
43516a497c6SRafael Auler 
43616a497c6SRafael Auler ///
43716a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to
43816a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote()
43916a497c6SRafael Auler ///
44016a497c6SRafael Auler struct Location {
44116a497c6SRafael Auler   uint32_t FunctionName;
44216a497c6SRafael Auler   uint32_t Offset;
44316a497c6SRafael Auler };
44416a497c6SRafael Auler 
44516a497c6SRafael Auler struct CallDescription {
44616a497c6SRafael Auler   Location From;
44716a497c6SRafael Auler   uint32_t FromNode;
44816a497c6SRafael Auler   Location To;
44916a497c6SRafael Auler   uint32_t Counter;
45016a497c6SRafael Auler   uint64_t TargetAddress;
45116a497c6SRafael Auler };
45216a497c6SRafael Auler 
45316a497c6SRafael Auler using IndCallDescription = Location;
45416a497c6SRafael Auler 
45516a497c6SRafael Auler struct IndCallTargetDescription {
45616a497c6SRafael Auler   Location Loc;
45716a497c6SRafael Auler   uint64_t Address;
45816a497c6SRafael Auler };
45916a497c6SRafael Auler 
46016a497c6SRafael Auler struct EdgeDescription {
46116a497c6SRafael Auler   Location From;
46216a497c6SRafael Auler   uint32_t FromNode;
46316a497c6SRafael Auler   Location To;
46416a497c6SRafael Auler   uint32_t ToNode;
46516a497c6SRafael Auler   uint32_t Counter;
46616a497c6SRafael Auler };
46716a497c6SRafael Auler 
46816a497c6SRafael Auler struct InstrumentedNode {
46916a497c6SRafael Auler   uint32_t Node;
47016a497c6SRafael Auler   uint32_t Counter;
47116a497c6SRafael Auler };
47216a497c6SRafael Auler 
47316a497c6SRafael Auler struct EntryNode {
47416a497c6SRafael Auler   uint64_t Node;
47516a497c6SRafael Auler   uint64_t Address;
47616a497c6SRafael Auler };
47716a497c6SRafael Auler 
47816a497c6SRafael Auler struct FunctionDescription {
47916a497c6SRafael Auler   uint32_t NumLeafNodes;
48016a497c6SRafael Auler   const InstrumentedNode *LeafNodes;
48116a497c6SRafael Auler   uint32_t NumEdges;
48216a497c6SRafael Auler   const EdgeDescription *Edges;
48316a497c6SRafael Auler   uint32_t NumCalls;
48416a497c6SRafael Auler   const CallDescription *Calls;
48516a497c6SRafael Auler   uint32_t NumEntryNodes;
48616a497c6SRafael Auler   const EntryNode *EntryNodes;
48716a497c6SRafael Auler 
48816a497c6SRafael Auler   /// Constructor will parse the serialized function metadata written by BOLT
48916a497c6SRafael Auler   FunctionDescription(const uint8_t *FuncDesc);
49016a497c6SRafael Auler 
49116a497c6SRafael Auler   uint64_t getSize() const {
49216a497c6SRafael Auler     return 16 + NumLeafNodes * sizeof(InstrumentedNode) +
49316a497c6SRafael Auler            NumEdges * sizeof(EdgeDescription) +
49416a497c6SRafael Auler            NumCalls * sizeof(CallDescription) +
49516a497c6SRafael Auler            NumEntryNodes * sizeof(EntryNode);
49616a497c6SRafael Auler   }
49716a497c6SRafael Auler };
49816a497c6SRafael Auler 
49916a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk
50016a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the
50116a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization
50216a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements.
50316a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs.
50416a497c6SRafael Auler struct ProfileWriterContext {
50516a497c6SRafael Auler   IndCallDescription *IndCallDescriptions;
50616a497c6SRafael Auler   IndCallTargetDescription *IndCallTargets;
50716a497c6SRafael Auler   uint8_t *FuncDescriptions;
50816a497c6SRafael Auler   char *Strings;  // String table with function names used in this binary
50916a497c6SRafael Auler   int FileDesc;   // File descriptor for the file on disk backing this
51016a497c6SRafael Auler                   // information in memory via mmap
51116a497c6SRafael Auler   void *MMapPtr;  // The mmap ptr
51216a497c6SRafael Auler   int MMapSize;   // The mmap size
51316a497c6SRafael Auler 
51416a497c6SRafael Auler   /// Hash table storing all possible call destinations to detect untracked
51516a497c6SRafael Auler   /// calls and correctly report them as [unknown] in output fdata.
51616a497c6SRafael Auler   CallFlowHashTable *CallFlowTable;
51716a497c6SRafael Auler 
51816a497c6SRafael Auler   /// Lookup the sorted indirect call target vector to fetch function name and
51916a497c6SRafael Auler   /// offset for an arbitrary function pointer.
52016a497c6SRafael Auler   const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const;
52116a497c6SRafael Auler };
52216a497c6SRafael Auler 
52316a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares
52416a497c6SRafael Auler /// at most Size characters.
525cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) {
526821480d2SRafael Auler   while (*Str1 == *Str2) {
527821480d2SRafael Auler     if (*Str1 == '\0' || --Size == 0)
528821480d2SRafael Auler       return 0;
529821480d2SRafael Auler     ++Str1;
530821480d2SRafael Auler     ++Str2;
531821480d2SRafael Auler   }
532821480d2SRafael Auler   return 1;
533821480d2SRafael Auler }
534821480d2SRafael Auler 
53516a497c6SRafael Auler /// Output Location to the fdata file
53616a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf,
537cc4b2fb6SRafael Auler                    const Location Loc, uint32_t BufSize) {
538821480d2SRafael Auler   // fdata location format: Type Name Offset
539821480d2SRafael Auler   // Type 1 - regular symbol
540821480d2SRafael Auler   OutBuf = strCopy(OutBuf, "1 ");
54116a497c6SRafael Auler   const char *Str = Ctx.Strings + Loc.FunctionName;
542cc4b2fb6SRafael Auler   uint32_t Size = 25;
54362aa74f8SRafael Auler   while (*Str) {
54462aa74f8SRafael Auler     *OutBuf++ = *Str++;
545cc4b2fb6SRafael Auler     if (++Size >= BufSize)
546cc4b2fb6SRafael Auler       break;
54762aa74f8SRafael Auler   }
548cc4b2fb6SRafael Auler   assert(!*Str, "buffer overflow, function name too large");
54962aa74f8SRafael Auler   *OutBuf++ = ' ';
550821480d2SRafael Auler   OutBuf = intToStr(OutBuf, Loc.Offset, 16);
55162aa74f8SRafael Auler   *OutBuf++ = ' ';
55262aa74f8SRafael Auler   return OutBuf;
55362aa74f8SRafael Auler }
55462aa74f8SRafael Auler 
55516a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc
55616a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file.
55716a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote()
55816a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) {
55916a497c6SRafael Auler   NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc);
56016a497c6SRafael Auler   DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10));
56116a497c6SRafael Auler   LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4);
56216a497c6SRafael Auler 
56316a497c6SRafael Auler   NumEdges = *reinterpret_cast<const uint32_t *>(
56416a497c6SRafael Auler       FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode));
56516a497c6SRafael Auler   DEBUG(reportNumber("NumEdges = ", NumEdges, 10));
56616a497c6SRafael Auler   Edges = reinterpret_cast<const EdgeDescription *>(
56716a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode));
56816a497c6SRafael Auler 
56916a497c6SRafael Auler   NumCalls = *reinterpret_cast<const uint32_t *>(
57016a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) +
57116a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
57216a497c6SRafael Auler   DEBUG(reportNumber("NumCalls = ", NumCalls, 10));
57316a497c6SRafael Auler   Calls = reinterpret_cast<const CallDescription *>(
57416a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
57516a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
57616a497c6SRafael Auler   NumEntryNodes = *reinterpret_cast<const uint32_t *>(
57716a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
57816a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
57916a497c6SRafael Auler   DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10));
58016a497c6SRafael Auler   EntryNodes = reinterpret_cast<const EntryNode *>(
58116a497c6SRafael Auler       FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) +
58216a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
58316a497c6SRafael Auler }
58416a497c6SRafael Auler 
58516a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes
58616a497c6SRafael Auler /// section
587a0dd5b05SAlexander Shaposhnikov #if defined(HAVE_ELF_H) and !defined(__APPLE__)
5882ffd6e2bSElvina Yakubova 
5892ffd6e2bSElvina Yakubova void *__attribute__((noinline)) __get_pc() {
5902ffd6e2bSElvina Yakubova   return __builtin_extract_return_addr(__builtin_return_address(0));
5912ffd6e2bSElvina Yakubova }
5922ffd6e2bSElvina Yakubova 
5932ffd6e2bSElvina Yakubova /// Get string with address and parse it to hex pair <StartAddress, EndAddress>
5942ffd6e2bSElvina Yakubova bool parseAddressRange(const char *Str, uint64_t &StartAddress,
5952ffd6e2bSElvina Yakubova                        uint64_t &EndAddress) {
5962ffd6e2bSElvina Yakubova   if (!Str)
5972ffd6e2bSElvina Yakubova     return false;
5982ffd6e2bSElvina Yakubova   // Parsed string format: <hex1>-<hex2>
5992ffd6e2bSElvina Yakubova   StartAddress = hexToLong(Str, '-');
6002ffd6e2bSElvina Yakubova   while (*Str && *Str != '-')
6012ffd6e2bSElvina Yakubova     ++Str;
6022ffd6e2bSElvina Yakubova   if (!*Str)
6032ffd6e2bSElvina Yakubova     return false;
6042ffd6e2bSElvina Yakubova   ++Str; // swallow '-'
6052ffd6e2bSElvina Yakubova   EndAddress = hexToLong(Str);
6062ffd6e2bSElvina Yakubova   return true;
6072ffd6e2bSElvina Yakubova }
6082ffd6e2bSElvina Yakubova 
6092ffd6e2bSElvina Yakubova /// Get full path to the real binary by getting current virtual address
6102ffd6e2bSElvina Yakubova /// and searching for the appropriate link in address range in
6112ffd6e2bSElvina Yakubova /// /proc/self/map_files
6122ffd6e2bSElvina Yakubova static char *getBinaryPath() {
6132ffd6e2bSElvina Yakubova   const uint32_t BufSize = 1024;
61446bc197dSMarius Wachtler   const uint32_t NameMax = 4096;
6152ffd6e2bSElvina Yakubova   const char DirPath[] = "/proc/self/map_files/";
6162ffd6e2bSElvina Yakubova   static char TargetPath[NameMax] = {};
6172ffd6e2bSElvina Yakubova   char Buf[BufSize];
6182ffd6e2bSElvina Yakubova 
619519cbbaaSVasily Leonenko   if (__bolt_instr_binpath[0] != '\0')
620519cbbaaSVasily Leonenko     return __bolt_instr_binpath;
621519cbbaaSVasily Leonenko 
6222ffd6e2bSElvina Yakubova   if (TargetPath[0] != '\0')
6232ffd6e2bSElvina Yakubova     return TargetPath;
6242ffd6e2bSElvina Yakubova 
6252ffd6e2bSElvina Yakubova   unsigned long CurAddr = (unsigned long)__get_pc();
6262ffd6e2bSElvina Yakubova   uint64_t FDdir = __open(DirPath,
627821480d2SRafael Auler                           /*flags=*/0 /*O_RDONLY*/,
628821480d2SRafael Auler                           /*mode=*/0666);
6293b00a3a2SMarius Wachtler   assert(static_cast<int64_t>(FDdir) >= 0,
6302ffd6e2bSElvina Yakubova          "failed to open /proc/self/map_files");
6312ffd6e2bSElvina Yakubova 
6322ffd6e2bSElvina Yakubova   while (long Nread = __getdents(FDdir, (struct dirent *)Buf, BufSize)) {
6332ffd6e2bSElvina Yakubova     assert(static_cast<int64_t>(Nread) != -1, "failed to get folder entries");
6342ffd6e2bSElvina Yakubova 
6352ffd6e2bSElvina Yakubova     struct dirent *d;
6362ffd6e2bSElvina Yakubova     for (long Bpos = 0; Bpos < Nread; Bpos += d->d_reclen) {
6372ffd6e2bSElvina Yakubova       d = (struct dirent *)(Buf + Bpos);
6382ffd6e2bSElvina Yakubova 
6392ffd6e2bSElvina Yakubova       uint64_t StartAddress, EndAddress;
6402ffd6e2bSElvina Yakubova       if (!parseAddressRange(d->d_name, StartAddress, EndAddress))
6412ffd6e2bSElvina Yakubova         continue;
6422ffd6e2bSElvina Yakubova       if (CurAddr < StartAddress || CurAddr > EndAddress)
6432ffd6e2bSElvina Yakubova         continue;
6442ffd6e2bSElvina Yakubova       char FindBuf[NameMax];
6452ffd6e2bSElvina Yakubova       char *C = strCopy(FindBuf, DirPath, NameMax);
6462ffd6e2bSElvina Yakubova       C = strCopy(C, d->d_name, NameMax - (C - FindBuf));
6472ffd6e2bSElvina Yakubova       *C = '\0';
6482ffd6e2bSElvina Yakubova       uint32_t Ret = __readlink(FindBuf, TargetPath, sizeof(TargetPath));
6492ffd6e2bSElvina Yakubova       assert(Ret != -1 && Ret != BufSize, "readlink error");
6502ffd6e2bSElvina Yakubova       TargetPath[Ret] = '\0';
6512ffd6e2bSElvina Yakubova       return TargetPath;
6522ffd6e2bSElvina Yakubova     }
6532ffd6e2bSElvina Yakubova   }
6542ffd6e2bSElvina Yakubova   return nullptr;
6552ffd6e2bSElvina Yakubova }
6562ffd6e2bSElvina Yakubova 
6572ffd6e2bSElvina Yakubova ProfileWriterContext readDescriptions() {
6582ffd6e2bSElvina Yakubova   ProfileWriterContext Result;
6592ffd6e2bSElvina Yakubova   char *BinPath = getBinaryPath();
6602ffd6e2bSElvina Yakubova   assert(BinPath && BinPath[0] != '\0', "failed to find binary path");
6612ffd6e2bSElvina Yakubova 
6622ffd6e2bSElvina Yakubova   uint64_t FD = __open(BinPath,
6632ffd6e2bSElvina Yakubova                        /*flags=*/0 /*O_RDONLY*/,
6642ffd6e2bSElvina Yakubova                        /*mode=*/0666);
6653b00a3a2SMarius Wachtler   assert(static_cast<int64_t>(FD) >= 0, "failed to open binary path");
6662ffd6e2bSElvina Yakubova 
667821480d2SRafael Auler   Result.FileDesc = FD;
668821480d2SRafael Auler 
669821480d2SRafael Auler   // mmap our binary to memory
670821480d2SRafael Auler   uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/);
671821480d2SRafael Auler   uint8_t *BinContents = reinterpret_cast<uint8_t *>(
672821480d2SRafael Auler       __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0));
673821480d2SRafael Auler   Result.MMapPtr = BinContents;
674821480d2SRafael Auler   Result.MMapSize = Size;
675821480d2SRafael Auler   Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents);
676821480d2SRafael Auler   Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff);
677821480d2SRafael Auler   Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>(
678821480d2SRafael Auler       BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize);
679821480d2SRafael Auler 
680821480d2SRafael Auler   // Find .bolt.instr.tables with the data we need and set pointers to it
681821480d2SRafael Auler   for (int I = 0; I < Hdr->e_shnum; ++I) {
682821480d2SRafael Auler     char *SecName = reinterpret_cast<char *>(
683821480d2SRafael Auler         BinContents + StringTblHeader->sh_offset + Shdr->sh_name);
684821480d2SRafael Auler     if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) {
685821480d2SRafael Auler       Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff +
686821480d2SRafael Auler                                             (I + 1) * Hdr->e_shentsize);
687821480d2SRafael Auler       continue;
688821480d2SRafael Auler     }
689821480d2SRafael Auler     // Actual contents of the ELF note start after offset 20 decimal:
690821480d2SRafael Auler     // Offset 0: Producer name size (4 bytes)
691821480d2SRafael Auler     // Offset 4: Contents size (4 bytes)
692821480d2SRafael Auler     // Offset 8: Note type (4 bytes)
693821480d2SRafael Auler     // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary)
694821480d2SRafael Auler     // Offset 20: Contents
69516a497c6SRafael Auler     uint32_t IndCallDescSize =
696cc4b2fb6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20);
69716a497c6SRafael Auler     uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>(
69816a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24 + IndCallDescSize);
69916a497c6SRafael Auler     uint32_t FuncDescSize =
70016a497c6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 +
70116a497c6SRafael Auler                                       IndCallDescSize + IndCallTargetDescSize);
70216a497c6SRafael Auler     Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>(
70316a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24);
70416a497c6SRafael Auler     Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
70516a497c6SRafael Auler         BinContents + Shdr->sh_offset + 28 + IndCallDescSize);
70616a497c6SRafael Auler     Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 +
70716a497c6SRafael Auler                               IndCallDescSize + IndCallTargetDescSize;
70816a497c6SRafael Auler     Result.Strings = reinterpret_cast<char *>(
70916a497c6SRafael Auler         BinContents + Shdr->sh_offset + 32 + IndCallDescSize +
71016a497c6SRafael Auler         IndCallTargetDescSize + FuncDescSize);
711821480d2SRafael Auler     return Result;
712821480d2SRafael Auler   }
713821480d2SRafael Auler   const char ErrMsg[] =
714821480d2SRafael Auler       "BOLT instrumentation runtime error: could not find section "
715821480d2SRafael Auler       ".bolt.instr.tables\n";
716821480d2SRafael Auler   reportError(ErrMsg, sizeof(ErrMsg));
717821480d2SRafael Auler   return Result;
718821480d2SRafael Auler }
719a0dd5b05SAlexander Shaposhnikov 
720ba31344fSRafael Auler #else
721a0dd5b05SAlexander Shaposhnikov 
72216a497c6SRafael Auler ProfileWriterContext readDescriptions() {
72316a497c6SRafael Auler   ProfileWriterContext Result;
724a0dd5b05SAlexander Shaposhnikov   uint8_t *Tables = _bolt_instr_tables_getter();
725a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallDescSize = *reinterpret_cast<uint32_t *>(Tables);
726a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallTargetDescSize =
727a0dd5b05SAlexander Shaposhnikov       *reinterpret_cast<uint32_t *>(Tables + 4 + IndCallDescSize);
728a0dd5b05SAlexander Shaposhnikov   uint32_t FuncDescSize = *reinterpret_cast<uint32_t *>(
729a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize + IndCallTargetDescSize);
730a0dd5b05SAlexander Shaposhnikov   Result.IndCallDescriptions =
731a0dd5b05SAlexander Shaposhnikov       reinterpret_cast<IndCallDescription *>(Tables + 4);
732a0dd5b05SAlexander Shaposhnikov   Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
733a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize);
734a0dd5b05SAlexander Shaposhnikov   Result.FuncDescriptions =
735a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize;
736a0dd5b05SAlexander Shaposhnikov   Result.Strings = reinterpret_cast<char *>(
737a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize + FuncDescSize);
738ba31344fSRafael Auler   return Result;
739ba31344fSRafael Auler }
740a0dd5b05SAlexander Shaposhnikov 
741ba31344fSRafael Auler #endif
742821480d2SRafael Auler 
743a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
74416a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane
74516a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) {
746cc4b2fb6SRafael Auler   char StatMsg[BufSize];
747cc4b2fb6SRafael Auler   char *StatPtr = StatMsg;
74816a497c6SRafael Auler   StatPtr =
74916a497c6SRafael Auler       strCopy(StatPtr,
75016a497c6SRafael Auler               "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: ");
751cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr,
75216a497c6SRafael Auler                      Ctx.FuncDescriptions -
75316a497c6SRafael Auler                          reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions),
754cc4b2fb6SRafael Auler                      10);
755cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\nFuncDescSize: ");
756cc4b2fb6SRafael Auler   StatPtr = intToStr(
757cc4b2fb6SRafael Auler       StatPtr,
75816a497c6SRafael Auler       reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10);
75916a497c6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: ");
76016a497c6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10);
761cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: ");
762cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10);
763cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n");
764cc4b2fb6SRafael Auler   __write(2, StatMsg, StatPtr - StatMsg);
765cc4b2fb6SRafael Auler }
766a0dd5b05SAlexander Shaposhnikov #endif
767a0dd5b05SAlexander Shaposhnikov 
768cc4b2fb6SRafael Auler 
769cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store
770cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store
771cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning
772cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in
773cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes.
774cc4b2fb6SRafael Auler struct Edge {
775cc4b2fb6SRafael Auler   uint32_t Node; // Index in nodes array regarding the destination of this edge
776cc4b2fb6SRafael Auler   uint32_t ID;   // Edge index in an array comprising all edges of the graph
777cc4b2fb6SRafael Auler };
778cc4b2fb6SRafael Auler 
779cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node
780cc4b2fb6SRafael Auler struct Node {
781cc4b2fb6SRafael Auler   uint32_t NumInEdges{0};  // Input edge count used to size InEdge
782cc4b2fb6SRafael Auler   uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges
783cc4b2fb6SRafael Auler   Edge *InEdges{nullptr};  // Created and managed by \p Graph
784cc4b2fb6SRafael Auler   Edge *OutEdges{nullptr}; // ditto
785cc4b2fb6SRafael Auler };
786cc4b2fb6SRafael Auler 
787cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and
788cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding
789cc4b2fb6SRafael Auler /// spanning tree nodes.
790cc4b2fb6SRafael Auler struct Graph {
791cc4b2fb6SRafael Auler   uint32_t NumNodes;
792cc4b2fb6SRafael Auler   Node *CFGNodes;
793cc4b2fb6SRafael Auler   Node *SpanningTreeNodes;
79416a497c6SRafael Auler   uint64_t *EdgeFreqs;
79516a497c6SRafael Auler   uint64_t *CallFreqs;
796cc4b2fb6SRafael Auler   BumpPtrAllocator &Alloc;
79716a497c6SRafael Auler   const FunctionDescription &D;
798cc4b2fb6SRafael Auler 
79916a497c6SRafael Auler   /// Reads a list of edges from function description \p D and builds
800cc4b2fb6SRafael Auler   /// the graph from it. Allocates several internal dynamic structures that are
80116a497c6SRafael Auler   /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all
802cc4b2fb6SRafael Auler   /// spanning tree leaf nodes descriptions (their counters). They are the seed
803cc4b2fb6SRafael Auler   /// used to compute the rest of the missing edge counts in a bottom-up
804cc4b2fb6SRafael Auler   /// traversal of the spanning tree.
80516a497c6SRafael Auler   Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
80616a497c6SRafael Auler         const uint64_t *Counters, ProfileWriterContext &Ctx);
807cc4b2fb6SRafael Auler   ~Graph();
808cc4b2fb6SRafael Auler   void dump() const;
80916a497c6SRafael Auler 
81016a497c6SRafael Auler private:
81116a497c6SRafael Auler   void computeEdgeFrequencies(const uint64_t *Counters,
81216a497c6SRafael Auler                               ProfileWriterContext &Ctx);
81316a497c6SRafael Auler   void dumpEdgeFreqs() const;
814cc4b2fb6SRafael Auler };
815cc4b2fb6SRafael Auler 
81616a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
81716a497c6SRafael Auler              const uint64_t *Counters, ProfileWriterContext &Ctx)
81816a497c6SRafael Auler     : Alloc(Alloc), D(D) {
819cc4b2fb6SRafael Auler   DEBUG(reportNumber("G = 0x", (uint64_t)this, 16));
820cc4b2fb6SRafael Auler   // First pass to determine number of nodes
82116a497c6SRafael Auler   int32_t MaxNodes = -1;
82216a497c6SRafael Auler   CallFreqs = nullptr;
82316a497c6SRafael Auler   EdgeFreqs = nullptr;
82416a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
82516a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes)
82616a497c6SRafael Auler       MaxNodes = D.Edges[I].FromNode;
82716a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes)
82816a497c6SRafael Auler       MaxNodes = D.Edges[I].ToNode;
829cc4b2fb6SRafael Auler   }
830a0dd5b05SAlexander Shaposhnikov 
831883bf0e8SAmir Ayupov   for (int I = 0; I < D.NumLeafNodes; ++I)
83216a497c6SRafael Auler     if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes)
83316a497c6SRafael Auler       MaxNodes = D.LeafNodes[I].Node;
834883bf0e8SAmir Ayupov 
835883bf0e8SAmir Ayupov   for (int I = 0; I < D.NumCalls; ++I)
83616a497c6SRafael Auler     if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes)
83716a497c6SRafael Auler       MaxNodes = D.Calls[I].FromNode;
838883bf0e8SAmir Ayupov 
83916a497c6SRafael Auler   // No nodes? Nothing to do
84016a497c6SRafael Auler   if (MaxNodes < 0) {
84116a497c6SRafael Auler     DEBUG(report("No nodes!\n"));
842cc4b2fb6SRafael Auler     CFGNodes = nullptr;
843cc4b2fb6SRafael Auler     SpanningTreeNodes = nullptr;
844cc4b2fb6SRafael Auler     NumNodes = 0;
845cc4b2fb6SRafael Auler     return;
846cc4b2fb6SRafael Auler   }
847cc4b2fb6SRafael Auler   ++MaxNodes;
848cc4b2fb6SRafael Auler   DEBUG(reportNumber("NumNodes = ", MaxNodes, 10));
84916a497c6SRafael Auler   NumNodes = static_cast<uint32_t>(MaxNodes);
850cc4b2fb6SRafael Auler 
851cc4b2fb6SRafael Auler   // Initial allocations
852cc4b2fb6SRafael Auler   CFGNodes = new (Alloc) Node[MaxNodes];
853a0dd5b05SAlexander Shaposhnikov 
854cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16));
855cc4b2fb6SRafael Auler   SpanningTreeNodes = new (Alloc) Node[MaxNodes];
856cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->SpanningTreeNodes = 0x",
857cc4b2fb6SRafael Auler                      (uint64_t)SpanningTreeNodes, 16));
858cc4b2fb6SRafael Auler 
859cc4b2fb6SRafael Auler   // Figure out how much to allocate to each vector (in/out edge sets)
86016a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
86116a497c6SRafael Auler     CFGNodes[D.Edges[I].FromNode].NumOutEdges++;
86216a497c6SRafael Auler     CFGNodes[D.Edges[I].ToNode].NumInEdges++;
86316a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
864cc4b2fb6SRafael Auler       continue;
865cc4b2fb6SRafael Auler 
86616a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++;
86716a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++;
868cc4b2fb6SRafael Auler   }
869cc4b2fb6SRafael Auler 
870cc4b2fb6SRafael Auler   // Allocate in/out edge sets
871cc4b2fb6SRafael Auler   for (int I = 0; I < MaxNodes; ++I) {
872cc4b2fb6SRafael Auler     if (CFGNodes[I].NumInEdges > 0)
873cc4b2fb6SRafael Auler       CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges];
874cc4b2fb6SRafael Auler     if (CFGNodes[I].NumOutEdges > 0)
875cc4b2fb6SRafael Auler       CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges];
876cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges > 0)
877cc4b2fb6SRafael Auler       SpanningTreeNodes[I].InEdges =
878cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges];
879cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumOutEdges > 0)
880cc4b2fb6SRafael Auler       SpanningTreeNodes[I].OutEdges =
881cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges];
882cc4b2fb6SRafael Auler     CFGNodes[I].NumInEdges = 0;
883cc4b2fb6SRafael Auler     CFGNodes[I].NumOutEdges = 0;
884cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumInEdges = 0;
885cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumOutEdges = 0;
886cc4b2fb6SRafael Auler   }
887cc4b2fb6SRafael Auler 
888cc4b2fb6SRafael Auler   // Fill in/out edge sets
88916a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
89016a497c6SRafael Auler     const uint32_t Src = D.Edges[I].FromNode;
89116a497c6SRafael Auler     const uint32_t Dst = D.Edges[I].ToNode;
892cc4b2fb6SRafael Auler     Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++];
893cc4b2fb6SRafael Auler     E->Node = Dst;
894cc4b2fb6SRafael Auler     E->ID = I;
895cc4b2fb6SRafael Auler 
896cc4b2fb6SRafael Auler     E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++];
897cc4b2fb6SRafael Auler     E->Node = Src;
898cc4b2fb6SRafael Auler     E->ID = I;
899cc4b2fb6SRafael Auler 
90016a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
901cc4b2fb6SRafael Auler       continue;
902cc4b2fb6SRafael Auler 
903cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Src]
904cc4b2fb6SRafael Auler              .OutEdges[SpanningTreeNodes[Src].NumOutEdges++];
905cc4b2fb6SRafael Auler     E->Node = Dst;
906cc4b2fb6SRafael Auler     E->ID = I;
907cc4b2fb6SRafael Auler 
908cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Dst]
909cc4b2fb6SRafael Auler              .InEdges[SpanningTreeNodes[Dst].NumInEdges++];
910cc4b2fb6SRafael Auler     E->Node = Src;
911cc4b2fb6SRafael Auler     E->ID = I;
912cc4b2fb6SRafael Auler   }
91316a497c6SRafael Auler 
91416a497c6SRafael Auler   computeEdgeFrequencies(Counters, Ctx);
915cc4b2fb6SRafael Auler }
916cc4b2fb6SRafael Auler 
917cc4b2fb6SRafael Auler Graph::~Graph() {
91816a497c6SRafael Auler   if (CallFreqs)
91916a497c6SRafael Auler     Alloc.deallocate(CallFreqs);
92016a497c6SRafael Auler   if (EdgeFreqs)
92116a497c6SRafael Auler     Alloc.deallocate(EdgeFreqs);
922cc4b2fb6SRafael Auler   for (int I = NumNodes - 1; I >= 0; --I) {
923cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].OutEdges)
924cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].OutEdges);
925cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].InEdges)
926cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].InEdges);
927cc4b2fb6SRafael Auler     if (CFGNodes[I].OutEdges)
928cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].OutEdges);
929cc4b2fb6SRafael Auler     if (CFGNodes[I].InEdges)
930cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].InEdges);
931cc4b2fb6SRafael Auler   }
932cc4b2fb6SRafael Auler   if (SpanningTreeNodes)
933cc4b2fb6SRafael Auler     Alloc.deallocate(SpanningTreeNodes);
934cc4b2fb6SRafael Auler   if (CFGNodes)
935cc4b2fb6SRafael Auler     Alloc.deallocate(CFGNodes);
936cc4b2fb6SRafael Auler }
937cc4b2fb6SRafael Auler 
938cc4b2fb6SRafael Auler void Graph::dump() const {
939cc4b2fb6SRafael Auler   reportNumber("Dumping graph with number of nodes: ", NumNodes, 10);
940cc4b2fb6SRafael Auler   report("  Full graph:\n");
941cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
942cc4b2fb6SRafael Auler     const Node *N = &CFGNodes[I];
943cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
944cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
945cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
946cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
947cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
948cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
949cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
950cc4b2fb6SRafael Auler     report("\n");
951cc4b2fb6SRafael Auler   }
952cc4b2fb6SRafael Auler   report("  Spanning tree:\n");
953cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
954cc4b2fb6SRafael Auler     const Node *N = &SpanningTreeNodes[I];
955cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
956cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
957cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
958cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
959cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
960cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
961cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
962cc4b2fb6SRafael Auler     report("\n");
963cc4b2fb6SRafael Auler   }
964cc4b2fb6SRafael Auler }
965cc4b2fb6SRafael Auler 
96616a497c6SRafael Auler void Graph::dumpEdgeFreqs() const {
96716a497c6SRafael Auler   reportNumber(
96816a497c6SRafael Auler       "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10);
96916a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
97016a497c6SRafael Auler     reportNumber("* Src: ", D.Edges[I].FromNode, 10);
97116a497c6SRafael Auler     reportNumber("  Dst: ", D.Edges[I].ToNode, 10);
972cc4b2fb6SRafael Auler     reportNumber("    Cnt: ", EdgeFreqs[I], 10);
973cc4b2fb6SRafael Auler   }
974cc4b2fb6SRafael Auler }
975cc4b2fb6SRafael Auler 
97616a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of
97716a497c6SRafael Auler /// the function CFG
97816a497c6SRafael Auler struct NodeToCallsMap {
97916a497c6SRafael Auler   struct MapEntry {
98016a497c6SRafael Auler     uint32_t NumCalls;
98116a497c6SRafael Auler     uint32_t *Calls;
98216a497c6SRafael Auler   };
98316a497c6SRafael Auler   MapEntry *Entries;
98416a497c6SRafael Auler   BumpPtrAllocator &Alloc;
98516a497c6SRafael Auler   const uint32_t NumNodes;
986cc4b2fb6SRafael Auler 
98716a497c6SRafael Auler   NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D,
98816a497c6SRafael Auler                  uint32_t NumNodes)
98916a497c6SRafael Auler       : Alloc(Alloc), NumNodes(NumNodes) {
99016a497c6SRafael Auler     Entries = new (Alloc, 0) MapEntry[NumNodes];
99116a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
99216a497c6SRafael Auler       DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10));
99316a497c6SRafael Auler       ++Entries[D.Calls[I].FromNode].NumCalls;
99416a497c6SRafael Auler     }
99516a497c6SRafael Auler     for (int I = 0; I < NumNodes; ++I) {
99616a497c6SRafael Auler       Entries[I].Calls = Entries[I].NumCalls ? new (Alloc)
99716a497c6SRafael Auler                                                    uint32_t[Entries[I].NumCalls]
99816a497c6SRafael Auler                                              : nullptr;
99916a497c6SRafael Auler       Entries[I].NumCalls = 0;
100016a497c6SRafael Auler     }
100116a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
1002c7306cc2SAmir Ayupov       MapEntry &Entry = Entries[D.Calls[I].FromNode];
100316a497c6SRafael Auler       Entry.Calls[Entry.NumCalls++] = I;
100416a497c6SRafael Auler     }
100516a497c6SRafael Auler   }
100616a497c6SRafael Auler 
100716a497c6SRafael Auler   /// Set the frequency of all calls in node \p NodeID to Freq. However, if
100816a497c6SRafael Auler   /// the calls have their own counters and do not depend on the basic block
100916a497c6SRafael Auler   /// counter, this means they have landing pads and throw exceptions. In this
101016a497c6SRafael Auler   /// case, set their frequency with their counters and return the maximum
101116a497c6SRafael Auler   /// value observed in such counters. This will be used as the new frequency
101216a497c6SRafael Auler   /// at basic block entry. This is used to fix the CFG edge frequencies in the
101316a497c6SRafael Auler   /// presence of exceptions.
101416a497c6SRafael Auler   uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs,
101516a497c6SRafael Auler                            const FunctionDescription &D,
101616a497c6SRafael Auler                            const uint64_t *Counters,
101716a497c6SRafael Auler                            ProfileWriterContext &Ctx) const {
1018c7306cc2SAmir Ayupov     const MapEntry &Entry = Entries[NodeID];
101916a497c6SRafael Auler     uint64_t MaxValue = 0ull;
102016a497c6SRafael Auler     for (int I = 0, E = Entry.NumCalls; I != E; ++I) {
1021c7306cc2SAmir Ayupov       const uint32_t CallID = Entry.Calls[I];
102216a497c6SRafael Auler       DEBUG(reportNumber("  Setting freq for call ID: ", CallID, 10));
1023c7306cc2SAmir Ayupov       const CallDescription &CallDesc = D.Calls[CallID];
102416a497c6SRafael Auler       if (CallDesc.Counter == 0xffffffff) {
102516a497c6SRafael Auler         CallFreqs[CallID] = Freq;
102616a497c6SRafael Auler         DEBUG(reportNumber("  with : ", Freq, 10));
102716a497c6SRafael Auler       } else {
1028c7306cc2SAmir Ayupov         const uint64_t CounterVal = Counters[CallDesc.Counter];
102916a497c6SRafael Auler         CallFreqs[CallID] = CounterVal;
103016a497c6SRafael Auler         MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue;
103116a497c6SRafael Auler         DEBUG(reportNumber("  with (private counter) : ", CounterVal, 10));
103216a497c6SRafael Auler       }
103316a497c6SRafael Auler       DEBUG(reportNumber("  Address: 0x", CallDesc.TargetAddress, 16));
103416a497c6SRafael Auler       if (CallFreqs[CallID] > 0)
103516a497c6SRafael Auler         Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls +=
103616a497c6SRafael Auler             CallFreqs[CallID];
103716a497c6SRafael Auler     }
103816a497c6SRafael Auler     return MaxValue;
103916a497c6SRafael Auler   }
104016a497c6SRafael Auler 
104116a497c6SRafael Auler   ~NodeToCallsMap() {
1042883bf0e8SAmir Ayupov     for (int I = NumNodes - 1; I >= 0; --I)
104316a497c6SRafael Auler       if (Entries[I].Calls)
104416a497c6SRafael Auler         Alloc.deallocate(Entries[I].Calls);
104516a497c6SRafael Auler     Alloc.deallocate(Entries);
104616a497c6SRafael Auler   }
104716a497c6SRafael Auler };
104816a497c6SRafael Auler 
104916a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented
105016a497c6SRafael Auler /// by G, as well as another array for each call.
105116a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters,
105216a497c6SRafael Auler                                    ProfileWriterContext &Ctx) {
105316a497c6SRafael Auler   if (NumNodes == 0)
105416a497c6SRafael Auler     return;
105516a497c6SRafael Auler 
105616a497c6SRafael Auler   EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr;
105716a497c6SRafael Auler   CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr;
105816a497c6SRafael Auler 
105916a497c6SRafael Auler   // Setup a lookup for calls present in each node (BB)
106016a497c6SRafael Auler   NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes);
1061cc4b2fb6SRafael Auler 
1062cc4b2fb6SRafael Auler   // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the
1063cc4b2fb6SRafael Auler   // spanning tree don't have explicit counters. We must infer their value using
1064cc4b2fb6SRafael Auler   // a linear combination of other counters (sum of counters of the outgoing
1065cc4b2fb6SRafael Auler   // edges minus sum of counters of the incoming edges).
106616a497c6SRafael Auler   uint32_t *Stack = new (Alloc) uint32_t [NumNodes];
1067cc4b2fb6SRafael Auler   uint32_t StackTop = 0;
1068cc4b2fb6SRafael Auler   enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED };
106916a497c6SRafael Auler   Status *Visited = new (Alloc, 0) Status[NumNodes];
107016a497c6SRafael Auler   uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes];
107116a497c6SRafael Auler   uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes];
1072cc4b2fb6SRafael Auler 
1073cc4b2fb6SRafael Auler   // Setup a fast lookup for frequency of leaf nodes, which have special
1074cc4b2fb6SRafael Auler   // basic block frequency instrumentation (they are not edge profiled).
107516a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
107616a497c6SRafael Auler     LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter];
1077cc4b2fb6SRafael Auler     DEBUG({
107816a497c6SRafael Auler       if (Counters[D.LeafNodes[I].Counter] > 0) {
107916a497c6SRafael Auler         reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10);
108016a497c6SRafael Auler         reportNumber("     Counter: ", Counters[D.LeafNodes[I].Counter], 10);
1081cc4b2fb6SRafael Auler       }
1082cc4b2fb6SRafael Auler     });
108316a497c6SRafael Auler   }
108416a497c6SRafael Auler   for (int I = 0; I < D.NumEntryNodes; ++I) {
108516a497c6SRafael Auler     EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address;
108616a497c6SRafael Auler     DEBUG({
108716a497c6SRafael Auler         reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10);
108816a497c6SRafael Auler         reportNumber("      Address: ", D.EntryNodes[I].Address, 16);
108916a497c6SRafael Auler     });
1090cc4b2fb6SRafael Auler   }
1091cc4b2fb6SRafael Auler   // Add all root nodes to the stack
1092883bf0e8SAmir Ayupov   for (int I = 0; I < NumNodes; ++I)
109316a497c6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges == 0)
1094cc4b2fb6SRafael Auler       Stack[StackTop++] = I;
1095883bf0e8SAmir Ayupov 
1096cc4b2fb6SRafael Auler   // Empty stack?
1097cc4b2fb6SRafael Auler   if (StackTop == 0) {
109816a497c6SRafael Auler     DEBUG(report("Empty stack!\n"));
109916a497c6SRafael Auler     Alloc.deallocate(EntryAddress);
1100cc4b2fb6SRafael Auler     Alloc.deallocate(LeafFrequency);
1101cc4b2fb6SRafael Auler     Alloc.deallocate(Visited);
1102cc4b2fb6SRafael Auler     Alloc.deallocate(Stack);
110316a497c6SRafael Auler     CallMap->~NodeToCallsMap();
110416a497c6SRafael Auler     Alloc.deallocate(CallMap);
110516a497c6SRafael Auler     if (CallFreqs)
110616a497c6SRafael Auler       Alloc.deallocate(CallFreqs);
110716a497c6SRafael Auler     if (EdgeFreqs)
110816a497c6SRafael Auler       Alloc.deallocate(EdgeFreqs);
110916a497c6SRafael Auler     EdgeFreqs = nullptr;
111016a497c6SRafael Auler     CallFreqs = nullptr;
111116a497c6SRafael Auler     return;
1112cc4b2fb6SRafael Auler   }
1113cc4b2fb6SRafael Auler   // Add all known edge counts, will infer the rest
111416a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
111516a497c6SRafael Auler     const uint32_t C = D.Edges[I].Counter;
1116cc4b2fb6SRafael Auler     if (C == 0xffffffff) // inferred counter - we will compute its value
1117cc4b2fb6SRafael Auler       continue;
111816a497c6SRafael Auler     EdgeFreqs[I] = Counters[C];
1119cc4b2fb6SRafael Auler   }
1120cc4b2fb6SRafael Auler 
1121cc4b2fb6SRafael Auler   while (StackTop > 0) {
1122cc4b2fb6SRafael Auler     const uint32_t Cur = Stack[--StackTop];
1123cc4b2fb6SRafael Auler     DEBUG({
1124cc4b2fb6SRafael Auler       if (Visited[Cur] == S_VISITING)
1125cc4b2fb6SRafael Auler         report("(visiting) ");
1126cc4b2fb6SRafael Auler       else
1127cc4b2fb6SRafael Auler         report("(new) ");
1128cc4b2fb6SRafael Auler       reportNumber("Cur: ", Cur, 10);
1129cc4b2fb6SRafael Auler     });
1130cc4b2fb6SRafael Auler 
1131cc4b2fb6SRafael Auler     // This shouldn't happen in a tree
1132cc4b2fb6SRafael Auler     assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack");
1133cc4b2fb6SRafael Auler     if (Visited[Cur] == S_NEW) {
1134cc4b2fb6SRafael Auler       Visited[Cur] = S_VISITING;
1135cc4b2fb6SRafael Auler       Stack[StackTop++] = Cur;
113616a497c6SRafael Auler       assert(StackTop <= NumNodes, "stack grew too large");
113716a497c6SRafael Auler       for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) {
113816a497c6SRafael Auler         const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node;
1139cc4b2fb6SRafael Auler         Stack[StackTop++] = Succ;
114016a497c6SRafael Auler         assert(StackTop <= NumNodes, "stack grew too large");
1141cc4b2fb6SRafael Auler       }
1142cc4b2fb6SRafael Auler       continue;
1143cc4b2fb6SRafael Auler     }
1144cc4b2fb6SRafael Auler     Visited[Cur] = S_VISITED;
1145cc4b2fb6SRafael Auler 
1146cc4b2fb6SRafael Auler     // Establish our node frequency based on outgoing edges, which should all be
1147cc4b2fb6SRafael Auler     // resolved by now.
1148cc4b2fb6SRafael Auler     int64_t CurNodeFreq = LeafFrequency[Cur];
1149cc4b2fb6SRafael Auler     // Not a leaf?
1150cc4b2fb6SRafael Auler     if (!CurNodeFreq) {
115116a497c6SRafael Auler       for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) {
115216a497c6SRafael Auler         const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID;
115316a497c6SRafael Auler         CurNodeFreq += EdgeFreqs[SuccEdge];
1154cc4b2fb6SRafael Auler       }
1155cc4b2fb6SRafael Auler     }
115616a497c6SRafael Auler     if (CurNodeFreq < 0)
115716a497c6SRafael Auler       CurNodeFreq = 0;
115816a497c6SRafael Auler 
115916a497c6SRafael Auler     const uint64_t CallFreq = CallMap->visitAllCallsIn(
116016a497c6SRafael Auler         Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx);
116116a497c6SRafael Auler 
116216a497c6SRafael Auler     // Exception handling affected our output flow? Fix with calls info
116316a497c6SRafael Auler     DEBUG({
116416a497c6SRafael Auler       if (CallFreq > CurNodeFreq)
116516a497c6SRafael Auler         report("Bumping node frequency with call info\n");
116616a497c6SRafael Auler     });
116716a497c6SRafael Auler     CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq;
116816a497c6SRafael Auler 
116916a497c6SRafael Auler     if (CurNodeFreq > 0) {
117016a497c6SRafael Auler       if (uint64_t Addr = EntryAddress[Cur]) {
117116a497c6SRafael Auler         DEBUG(
117216a497c6SRafael Auler             reportNumber("  Setting flow at entry point address 0x", Addr, 16));
117316a497c6SRafael Auler         DEBUG(reportNumber("  with: ", CurNodeFreq, 10));
117416a497c6SRafael Auler         Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq;
117516a497c6SRafael Auler       }
117616a497c6SRafael Auler     }
117716a497c6SRafael Auler 
117816a497c6SRafael Auler     // No parent? Reached a tree root, limit to call frequency updating.
1179883bf0e8SAmir Ayupov     if (SpanningTreeNodes[Cur].NumInEdges == 0)
118016a497c6SRafael Auler       continue;
118116a497c6SRafael Auler 
118216a497c6SRafael Auler     assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent");
118316a497c6SRafael Auler     const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node;
118416a497c6SRafael Auler     const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID;
118516a497c6SRafael Auler 
1186cc4b2fb6SRafael Auler     // Calculate parent edge freq.
118716a497c6SRafael Auler     int64_t ParentEdgeFreq = CurNodeFreq;
118816a497c6SRafael Auler     for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) {
118916a497c6SRafael Auler       const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID;
119016a497c6SRafael Auler       ParentEdgeFreq -= EdgeFreqs[PredEdge];
1191cc4b2fb6SRafael Auler     }
119216a497c6SRafael Auler 
1193cc4b2fb6SRafael Auler     // Sometimes the conservative CFG that BOLT builds will lead to incorrect
1194cc4b2fb6SRafael Auler     // flow computation. For example, in a BB that transitively calls the exit
1195cc4b2fb6SRafael Auler     // syscall, BOLT will add a fall-through successor even though it should not
1196cc4b2fb6SRafael Auler     // have any successors. So this block execution will likely be wrong. We
1197cc4b2fb6SRafael Auler     // tolerate this imperfection since this case should be quite infrequent.
1198cc4b2fb6SRafael Auler     if (ParentEdgeFreq < 0) {
119916a497c6SRafael Auler       DEBUG(dumpEdgeFreqs());
1200cc4b2fb6SRafael Auler       DEBUG(report("WARNING: incorrect flow"));
1201cc4b2fb6SRafael Auler       ParentEdgeFreq = 0;
1202cc4b2fb6SRafael Auler     }
1203cc4b2fb6SRafael Auler     DEBUG(reportNumber("  Setting freq for ParentEdge: ", ParentEdge, 10));
1204cc4b2fb6SRafael Auler     DEBUG(reportNumber("  with ParentEdgeFreq: ", ParentEdgeFreq, 10));
120516a497c6SRafael Auler     EdgeFreqs[ParentEdge] = ParentEdgeFreq;
1206cc4b2fb6SRafael Auler   }
1207cc4b2fb6SRafael Auler 
120816a497c6SRafael Auler   Alloc.deallocate(EntryAddress);
1209cc4b2fb6SRafael Auler   Alloc.deallocate(LeafFrequency);
1210cc4b2fb6SRafael Auler   Alloc.deallocate(Visited);
1211cc4b2fb6SRafael Auler   Alloc.deallocate(Stack);
121216a497c6SRafael Auler   CallMap->~NodeToCallsMap();
121316a497c6SRafael Auler   Alloc.deallocate(CallMap);
121416a497c6SRafael Auler   DEBUG(dumpEdgeFreqs());
1215cc4b2fb6SRafael Auler }
1216cc4b2fb6SRafael Auler 
121716a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses
121816a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for
121916a497c6SRafael Auler /// edges that we do not explictly instrument.
122016a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx,
122116a497c6SRafael Auler                                     const uint8_t *FuncDesc,
122216a497c6SRafael Auler                                     BumpPtrAllocator &Alloc) {
122316a497c6SRafael Auler   const FunctionDescription F(FuncDesc);
122416a497c6SRafael Auler   const uint8_t *next = FuncDesc + F.getSize();
1225cc4b2fb6SRafael Auler 
1226a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1227a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = __bolt_instr_locations;
1228a0dd5b05SAlexander Shaposhnikov #else
1229a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = _bolt_instr_locations_getter();
1230a0dd5b05SAlexander Shaposhnikov #endif
1231a0dd5b05SAlexander Shaposhnikov 
1232cc4b2fb6SRafael Auler   // Skip funcs we know are cold
1233cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG
123416a497c6SRafael Auler   uint64_t CountersFreq = 0;
1235883bf0e8SAmir Ayupov   for (int I = 0; I < F.NumLeafNodes; ++I)
1236a0dd5b05SAlexander Shaposhnikov     CountersFreq += bolt_instr_locations[F.LeafNodes[I].Counter];
1237883bf0e8SAmir Ayupov 
123816a497c6SRafael Auler   if (CountersFreq == 0) {
123916a497c6SRafael Auler     for (int I = 0; I < F.NumEdges; ++I) {
124016a497c6SRafael Auler       const uint32_t C = F.Edges[I].Counter;
124116a497c6SRafael Auler       if (C == 0xffffffff)
124216a497c6SRafael Auler         continue;
1243a0dd5b05SAlexander Shaposhnikov       CountersFreq += bolt_instr_locations[C];
124416a497c6SRafael Auler     }
124516a497c6SRafael Auler     if (CountersFreq == 0) {
124616a497c6SRafael Auler       for (int I = 0; I < F.NumCalls; ++I) {
124716a497c6SRafael Auler         const uint32_t C = F.Calls[I].Counter;
124816a497c6SRafael Auler         if (C == 0xffffffff)
124916a497c6SRafael Auler           continue;
1250a0dd5b05SAlexander Shaposhnikov         CountersFreq += bolt_instr_locations[C];
125116a497c6SRafael Auler       }
125216a497c6SRafael Auler       if (CountersFreq == 0)
1253cc4b2fb6SRafael Auler         return next;
125416a497c6SRafael Auler     }
125516a497c6SRafael Auler   }
1256cc4b2fb6SRafael Auler #endif
1257cc4b2fb6SRafael Auler 
1258a0dd5b05SAlexander Shaposhnikov   Graph *G = new (Alloc) Graph(Alloc, F, bolt_instr_locations, Ctx);
1259cc4b2fb6SRafael Auler   DEBUG(G->dump());
1260a0dd5b05SAlexander Shaposhnikov 
126116a497c6SRafael Auler   if (!G->EdgeFreqs && !G->CallFreqs) {
1262cc4b2fb6SRafael Auler     G->~Graph();
1263cc4b2fb6SRafael Auler     Alloc.deallocate(G);
1264cc4b2fb6SRafael Auler     return next;
1265cc4b2fb6SRafael Auler   }
1266cc4b2fb6SRafael Auler 
126716a497c6SRafael Auler   for (int I = 0; I < F.NumEdges; ++I) {
126816a497c6SRafael Auler     const uint64_t Freq = G->EdgeFreqs[I];
1269cc4b2fb6SRafael Auler     if (Freq == 0)
1270cc4b2fb6SRafael Auler       continue;
127116a497c6SRafael Auler     const EdgeDescription *Desc = &F.Edges[I];
1272cc4b2fb6SRafael Auler     char LineBuf[BufSize];
1273cc4b2fb6SRafael Auler     char *Ptr = LineBuf;
127416a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
127516a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
1276cc4b2fb6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22);
1277cc4b2fb6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
1278cc4b2fb6SRafael Auler     *Ptr++ = '\n';
1279cc4b2fb6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
1280cc4b2fb6SRafael Auler   }
1281cc4b2fb6SRafael Auler 
128216a497c6SRafael Auler   for (int I = 0; I < F.NumCalls; ++I) {
128316a497c6SRafael Auler     const uint64_t Freq = G->CallFreqs[I];
128416a497c6SRafael Auler     if (Freq == 0)
128516a497c6SRafael Auler       continue;
128616a497c6SRafael Auler     char LineBuf[BufSize];
128716a497c6SRafael Auler     char *Ptr = LineBuf;
128816a497c6SRafael Auler     const CallDescription *Desc = &F.Calls[I];
128916a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
129016a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
129116a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
129216a497c6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
129316a497c6SRafael Auler     *Ptr++ = '\n';
129416a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
129516a497c6SRafael Auler   }
129616a497c6SRafael Auler 
1297cc4b2fb6SRafael Auler   G->~Graph();
1298cc4b2fb6SRafael Auler   Alloc.deallocate(G);
1299cc4b2fb6SRafael Auler   return next;
1300cc4b2fb6SRafael Auler }
1301cc4b2fb6SRafael Auler 
1302a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
130316a497c6SRafael Auler const IndCallTargetDescription *
130416a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const {
130516a497c6SRafael Auler   uint32_t B = 0;
130616a497c6SRafael Auler   uint32_t E = __bolt_instr_num_ind_targets;
130716a497c6SRafael Auler   if (E == 0)
130816a497c6SRafael Auler     return nullptr;
130916a497c6SRafael Auler   do {
131016a497c6SRafael Auler     uint32_t I = (E - B) / 2 + B;
131116a497c6SRafael Auler     if (IndCallTargets[I].Address == Target)
131216a497c6SRafael Auler       return &IndCallTargets[I];
131316a497c6SRafael Auler     if (IndCallTargets[I].Address < Target)
131416a497c6SRafael Auler       B = I + 1;
131516a497c6SRafael Auler     else
131616a497c6SRafael Auler       E = I;
131716a497c6SRafael Auler   } while (B < E);
131816a497c6SRafael Auler   return nullptr;
1319cc4b2fb6SRafael Auler }
132062aa74f8SRafael Auler 
132116a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file
132216a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry,
132316a497c6SRafael Auler                          int FD, int CallsiteID,
132416a497c6SRafael Auler                          ProfileWriterContext *Ctx) {
132516a497c6SRafael Auler   if (Entry.Val == 0)
132616a497c6SRafael Auler     return;
132716a497c6SRafael Auler   DEBUG(reportNumber("Target func 0x", Entry.Key, 16));
132816a497c6SRafael Auler   DEBUG(reportNumber("Target freq: ", Entry.Val, 10));
132916a497c6SRafael Auler   const IndCallDescription *CallsiteDesc =
133016a497c6SRafael Auler       &Ctx->IndCallDescriptions[CallsiteID];
133116a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
133216a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
133316a497c6SRafael Auler   if (!TargetDesc) {
133416a497c6SRafael Auler     DEBUG(report("Failed to lookup indirect call target\n"));
1335cc4b2fb6SRafael Auler     char LineBuf[BufSize];
133662aa74f8SRafael Auler     char *Ptr = LineBuf;
133716a497c6SRafael Auler     Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
133816a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40);
133916a497c6SRafael Auler     Ptr = intToStr(Ptr, Entry.Val, 10);
134016a497c6SRafael Auler     *Ptr++ = '\n';
134116a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
134216a497c6SRafael Auler     return;
134316a497c6SRafael Auler   }
134416a497c6SRafael Auler   Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val;
134516a497c6SRafael Auler   char LineBuf[BufSize];
134616a497c6SRafael Auler   char *Ptr = LineBuf;
134716a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
134816a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
1349cc4b2fb6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
135016a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val, 10);
135162aa74f8SRafael Auler   *Ptr++ = '\n';
1352821480d2SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
135362aa74f8SRafael Auler }
1354cc4b2fb6SRafael Auler 
135516a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles.
135616a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) {
135716a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
135816a497c6SRafael Auler     DEBUG(reportNumber("IndCallsite #", I, 10));
135916a497c6SRafael Auler     GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx);
136016a497c6SRafael Auler   }
136116a497c6SRafael Auler }
136216a497c6SRafael Auler 
136316a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are
136416a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source
136516a497c6SRafael Auler /// [unknown] in the profile.
136616a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD,
136716a497c6SRafael Auler                         ProfileWriterContext *Ctx) {
136816a497c6SRafael Auler   DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16));
136916a497c6SRafael Auler   DEBUG(reportNumber("Calls: ", Entry.Calls, 10));
137016a497c6SRafael Auler   DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10));
137116a497c6SRafael Auler   DEBUG({
137216a497c6SRafael Auler     if (Entry.Calls > Entry.Val)
137316a497c6SRafael Auler       report("  More calls than expected!\n");
137416a497c6SRafael Auler   });
137516a497c6SRafael Auler   if (Entry.Val <= Entry.Calls)
137616a497c6SRafael Auler     return;
137716a497c6SRafael Auler   DEBUG(reportNumber(
137816a497c6SRafael Auler       "  Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10));
137916a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
138016a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
138116a497c6SRafael Auler   if (!TargetDesc) {
138216a497c6SRafael Auler     // There is probably something wrong with this callee and this should be
138316a497c6SRafael Auler     // investigated, but I don't want to assert and lose all data collected.
138416a497c6SRafael Auler     DEBUG(report("WARNING: failed to look up call target!\n"));
138516a497c6SRafael Auler     return;
138616a497c6SRafael Auler   }
138716a497c6SRafael Auler   char LineBuf[BufSize];
138816a497c6SRafael Auler   char *Ptr = LineBuf;
138916a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize);
139016a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
139116a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
139216a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10);
139316a497c6SRafael Auler   *Ptr++ = '\n';
139416a497c6SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
139516a497c6SRafael Auler }
139616a497c6SRafael Auler 
139716a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting
139816a497c6SRafael Auler /// program upon failure.
139916a497c6SRafael Auler int openProfile() {
140016a497c6SRafael Auler   // Build the profile name string by appending our PID
140116a497c6SRafael Auler   char Buf[BufSize];
140216a497c6SRafael Auler   char *Ptr = Buf;
140316a497c6SRafael Auler   uint64_t PID = __getpid();
140416a497c6SRafael Auler   Ptr = strCopy(Buf, __bolt_instr_filename, BufSize);
140516a497c6SRafael Auler   if (__bolt_instr_use_pid) {
140616a497c6SRafael Auler     Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1));
140716a497c6SRafael Auler     Ptr = intToStr(Ptr, PID, 10);
140816a497c6SRafael Auler     Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1));
140916a497c6SRafael Auler   }
141016a497c6SRafael Auler   *Ptr++ = '\0';
141116a497c6SRafael Auler   uint64_t FD = __open(Buf,
141216a497c6SRafael Auler                        /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/,
141316a497c6SRafael Auler                        /*mode=*/0666);
141416a497c6SRafael Auler   if (static_cast<int64_t>(FD) < 0) {
141516a497c6SRafael Auler     report("Error while trying to open profile file for writing: ");
141616a497c6SRafael Auler     report(Buf);
141716a497c6SRafael Auler     reportNumber("\nFailed with error number: 0x",
141816a497c6SRafael Auler                  0 - static_cast<int64_t>(FD), 16);
141916a497c6SRafael Auler     __exit(1);
142016a497c6SRafael Auler   }
142116a497c6SRafael Auler   return FD;
142216a497c6SRafael Auler }
1423a0dd5b05SAlexander Shaposhnikov 
1424a0dd5b05SAlexander Shaposhnikov #endif
1425a0dd5b05SAlexander Shaposhnikov 
142616a497c6SRafael Auler } // anonymous namespace
142716a497c6SRafael Auler 
1428a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1429a0dd5b05SAlexander Shaposhnikov 
143016a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your
143116a497c6SRafael Auler /// program independently of prior phases.
143216a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by
143316a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb:
143416a497c6SRafael Auler ///
143516a497c6SRafael Auler ///   gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \
143616a497c6SRafael Auler ///     -ex 'set confirm off' -ex quit
143716a497c6SRafael Auler ///
143816a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file
143916a497c6SRafael Auler /// name.
144016a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() {
1441ea2182feSMaksim Panchenko   memset(reinterpret_cast<char *>(__bolt_instr_locations), 0,
144216a497c6SRafael Auler          __bolt_num_counters * 8);
1443883bf0e8SAmir Ayupov   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I)
144416a497c6SRafael Auler     GlobalIndCallCounters[I].resetCounters();
144516a497c6SRafael Auler }
144616a497c6SRafael Auler 
144716a497c6SRafael Auler /// This is the entry point for profile writing.
144816a497c6SRafael Auler /// There are three ways of getting here:
144916a497c6SRafael Auler ///
145016a497c6SRafael Auler ///  * Program execution ended, finalization methods are running and BOLT
145116a497c6SRafael Auler ///    hooked into FINI from your binary dynamic section;
145216a497c6SRafael Auler ///  * You used the sleep timer option and during initialization we forked
145316a497c6SRafael Auler ///    a separete process that will call this function periodically;
145416a497c6SRafael Auler ///  * BOLT prints this function address so you can attach a debugger and
145516a497c6SRafael Auler ///    call this function directly to get your profile written to disk
145616a497c6SRafael Auler ///    on demand.
145716a497c6SRafael Auler ///
1458ad79d517SVasily Leonenko extern "C" void __attribute((force_align_arg_pointer))
1459ad79d517SVasily Leonenko __bolt_instr_data_dump() {
146016a497c6SRafael Auler   // Already dumping
146116a497c6SRafael Auler   if (!GlobalWriteProfileMutex->acquire())
146216a497c6SRafael Auler     return;
146316a497c6SRafael Auler 
146416a497c6SRafael Auler   BumpPtrAllocator HashAlloc;
146516a497c6SRafael Auler   HashAlloc.setMaxSize(0x6400000);
146616a497c6SRafael Auler   ProfileWriterContext Ctx = readDescriptions();
146716a497c6SRafael Auler   Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc);
146816a497c6SRafael Auler 
146916a497c6SRafael Auler   DEBUG(printStats(Ctx));
147016a497c6SRafael Auler 
147116a497c6SRafael Auler   int FD = openProfile();
147216a497c6SRafael Auler 
1473cc4b2fb6SRafael Auler   BumpPtrAllocator Alloc;
1474*eaf1b566SJakub Beránek   Alloc.setMaxSize(0x6400000);
147516a497c6SRafael Auler   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1476cc4b2fb6SRafael Auler   for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) {
147716a497c6SRafael Auler     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
147816a497c6SRafael Auler     Alloc.clear();
1479cc4b2fb6SRafael Auler     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1480cc4b2fb6SRafael Auler   }
148116a497c6SRafael Auler   assert(FuncDesc == (void *)Ctx.Strings,
1482cc4b2fb6SRafael Auler          "FuncDesc ptr must be equal to stringtable");
1483cc4b2fb6SRafael Auler 
148416a497c6SRafael Auler   writeIndirectCallProfile(FD, Ctx);
148516a497c6SRafael Auler   Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx);
148616a497c6SRafael Auler 
1487dcdd37fdSVladislav Khmelevsky   __fsync(FD);
1488821480d2SRafael Auler   __close(FD);
148916a497c6SRafael Auler   __munmap(Ctx.MMapPtr, Ctx.MMapSize);
149016a497c6SRafael Auler   __close(Ctx.FileDesc);
149116a497c6SRafael Auler   HashAlloc.destroy();
149216a497c6SRafael Auler   GlobalWriteProfileMutex->release();
149316a497c6SRafael Auler   DEBUG(report("Finished writing profile.\n"));
149416a497c6SRafael Auler }
149516a497c6SRafael Auler 
149616a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data
149716a497c6SRafael Auler /// at user-specified intervals
149816a497c6SRafael Auler void watchProcess() {
149916a497c6SRafael Auler   timespec ts, rem;
150016a497c6SRafael Auler   uint64_t Ellapsed = 0ull;
150176d346caSVladislav Khmelevsky   uint64_t ppid;
150276d346caSVladislav Khmelevsky   if (__bolt_instr_wait_forks) {
150376d346caSVladislav Khmelevsky     // Store parent pgid
150476d346caSVladislav Khmelevsky     ppid = -__getpgid(0);
150576d346caSVladislav Khmelevsky     // And leave parent process group
150676d346caSVladislav Khmelevsky     __setpgid(0, 0);
150776d346caSVladislav Khmelevsky   } else {
150876d346caSVladislav Khmelevsky     // Store parent pid
150976d346caSVladislav Khmelevsky     ppid = __getppid();
151076d346caSVladislav Khmelevsky     if (ppid == 1) {
151176d346caSVladislav Khmelevsky       // Parent already dead
1512dcdd37fdSVladislav Khmelevsky       __bolt_instr_data_dump();
151376d346caSVladislav Khmelevsky       goto out;
151476d346caSVladislav Khmelevsky     }
151576d346caSVladislav Khmelevsky   }
151676d346caSVladislav Khmelevsky 
151716a497c6SRafael Auler   ts.tv_sec = 1;
151816a497c6SRafael Auler   ts.tv_nsec = 0;
151916a497c6SRafael Auler   while (1) {
152016a497c6SRafael Auler     __nanosleep(&ts, &rem);
152176d346caSVladislav Khmelevsky     // This means our parent process or all its forks are dead,
152276d346caSVladislav Khmelevsky     // so no need for us to keep dumping.
152376d346caSVladislav Khmelevsky     if (__kill(ppid, 0) < 0) {
152476d346caSVladislav Khmelevsky       if (__bolt_instr_no_counters_clear)
152576d346caSVladislav Khmelevsky         __bolt_instr_data_dump();
152616a497c6SRafael Auler       break;
152716a497c6SRafael Auler     }
152876d346caSVladislav Khmelevsky 
152916a497c6SRafael Auler     if (++Ellapsed < __bolt_instr_sleep_time)
153016a497c6SRafael Auler       continue;
153176d346caSVladislav Khmelevsky 
153216a497c6SRafael Auler     Ellapsed = 0;
153316a497c6SRafael Auler     __bolt_instr_data_dump();
153476d346caSVladislav Khmelevsky     if (__bolt_instr_no_counters_clear == false)
153516a497c6SRafael Auler       __bolt_instr_clear_counters();
153616a497c6SRafael Auler   }
153776d346caSVladislav Khmelevsky 
153876d346caSVladislav Khmelevsky out:;
153916a497c6SRafael Auler   DEBUG(report("My parent process is dead, bye!\n"));
154016a497c6SRafael Auler   __exit(0);
154116a497c6SRafael Auler }
154216a497c6SRafael Auler 
154316a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call();
154416a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall();
154516a497c6SRafael Auler 
154616a497c6SRafael Auler /// Initialization code
1547ad79d517SVasily Leonenko extern "C" void __attribute((force_align_arg_pointer)) __bolt_instr_setup() {
154816a497c6SRafael Auler   const uint64_t CountersStart =
154916a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]);
155016a497c6SRafael Auler   const uint64_t CountersEnd = alignTo(
155116a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]),
155216a497c6SRafael Auler       0x1000);
155316a497c6SRafael Auler   DEBUG(reportNumber("replace mmap start: ", CountersStart, 16));
155416a497c6SRafael Auler   DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16));
155516a497c6SRafael Auler   assert (CountersEnd > CountersStart, "no counters");
155616a497c6SRafael Auler   // Maps our counters to be shared instead of private, so we keep counting for
155716a497c6SRafael Auler   // forked processes
155816a497c6SRafael Auler   __mmap(CountersStart, CountersEnd - CountersStart,
155916a497c6SRafael Auler          0x3 /*PROT_READ|PROT_WRITE*/,
156016a497c6SRafael Auler          0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0);
156116a497c6SRafael Auler 
1562361f3b55SVladislav Khmelevsky   __bolt_ind_call_counter_func_pointer = __bolt_instr_indirect_call;
1563361f3b55SVladislav Khmelevsky   __bolt_ind_tailcall_counter_func_pointer = __bolt_instr_indirect_tailcall;
156416a497c6SRafael Auler   // Conservatively reserve 100MiB shared pages
156516a497c6SRafael Auler   GlobalAlloc.setMaxSize(0x6400000);
156616a497c6SRafael Auler   GlobalAlloc.setShared(true);
156716a497c6SRafael Auler   GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex();
156816a497c6SRafael Auler   if (__bolt_instr_num_ind_calls > 0)
156916a497c6SRafael Auler     GlobalIndCallCounters =
157016a497c6SRafael Auler         new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls];
157116a497c6SRafael Auler 
157216a497c6SRafael Auler   if (__bolt_instr_sleep_time != 0) {
157376d346caSVladislav Khmelevsky     // Separate instrumented process to the own process group
157476d346caSVladislav Khmelevsky     if (__bolt_instr_wait_forks)
157576d346caSVladislav Khmelevsky       __setpgid(0, 0);
157676d346caSVladislav Khmelevsky 
1577c7306cc2SAmir Ayupov     if (long PID = __fork())
157816a497c6SRafael Auler       return;
157916a497c6SRafael Auler     watchProcess();
158016a497c6SRafael Auler   }
158116a497c6SRafael Auler }
158216a497c6SRafael Auler 
1583361f3b55SVladislav Khmelevsky extern "C" __attribute((force_align_arg_pointer)) void
1584361f3b55SVladislav Khmelevsky instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) {
158516a497c6SRafael Auler   GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc);
158616a497c6SRafael Auler }
158716a497c6SRafael Auler 
158816a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site
158916a497c6SRafael Auler /// as well as the target address for the call
159016a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call()
159116a497c6SRafael Auler {
159216a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1593361f3b55SVladislav Khmelevsky                        "mov 0xa0(%%rsp), %%rdi\n"
1594361f3b55SVladislav Khmelevsky                        "mov 0x98(%%rsp), %%rsi\n"
159516a497c6SRafael Auler                        "call instrumentIndirectCall\n"
159616a497c6SRafael Auler                        RESTORE_ALL
1597361f3b55SVladislav Khmelevsky                        "ret\n"
159816a497c6SRafael Auler                        :::);
159916a497c6SRafael Auler }
160016a497c6SRafael Auler 
160116a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall()
160216a497c6SRafael Auler {
160316a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1604361f3b55SVladislav Khmelevsky                        "mov 0x98(%%rsp), %%rdi\n"
1605361f3b55SVladislav Khmelevsky                        "mov 0x90(%%rsp), %%rsi\n"
160616a497c6SRafael Auler                        "call instrumentIndirectCall\n"
160716a497c6SRafael Auler                        RESTORE_ALL
1608361f3b55SVladislav Khmelevsky                        "ret\n"
160916a497c6SRafael Auler                        :::);
161016a497c6SRafael Auler }
161116a497c6SRafael Auler 
161216a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state.
161316a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start()
161416a497c6SRafael Auler {
161516a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
161616a497c6SRafael Auler                        "call __bolt_instr_setup\n"
161716a497c6SRafael Auler                        RESTORE_ALL
1618ad79d517SVasily Leonenko                        "jmp __bolt_start_trampoline\n"
161916a497c6SRafael Auler                        :::);
162016a497c6SRafael Auler }
162116a497c6SRafael Auler 
162216a497c6SRafael Auler /// This is hooking into ELF's DT_FINI
162316a497c6SRafael Auler extern "C" void __bolt_instr_fini() {
1624553f28e9SVladislav Khmelevsky   __bolt_fini_trampoline();
162516a497c6SRafael Auler   if (__bolt_instr_sleep_time == 0)
162616a497c6SRafael Auler     __bolt_instr_data_dump();
162716a497c6SRafael Auler   DEBUG(report("Finished.\n"));
162862aa74f8SRafael Auler }
1629bbd9d610SAlexander Shaposhnikov 
16303b876cc3SAlexander Shaposhnikov #endif
16313b876cc3SAlexander Shaposhnikov 
16323b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
1633bbd9d610SAlexander Shaposhnikov 
1634a0dd5b05SAlexander Shaposhnikov extern "C" void __bolt_instr_data_dump() {
1635a0dd5b05SAlexander Shaposhnikov   ProfileWriterContext Ctx = readDescriptions();
1636a0dd5b05SAlexander Shaposhnikov 
1637a0dd5b05SAlexander Shaposhnikov   int FD = 2;
1638a0dd5b05SAlexander Shaposhnikov   BumpPtrAllocator Alloc;
1639a0dd5b05SAlexander Shaposhnikov   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1640a0dd5b05SAlexander Shaposhnikov   uint32_t bolt_instr_num_funcs = _bolt_instr_num_funcs_getter();
1641a0dd5b05SAlexander Shaposhnikov 
1642a0dd5b05SAlexander Shaposhnikov   for (int I = 0, E = bolt_instr_num_funcs; I < E; ++I) {
1643a0dd5b05SAlexander Shaposhnikov     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
1644a0dd5b05SAlexander Shaposhnikov     Alloc.clear();
1645a0dd5b05SAlexander Shaposhnikov     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1646a0dd5b05SAlexander Shaposhnikov   }
1647a0dd5b05SAlexander Shaposhnikov   assert(FuncDesc == (void *)Ctx.Strings,
1648a0dd5b05SAlexander Shaposhnikov          "FuncDesc ptr must be equal to stringtable");
1649a0dd5b05SAlexander Shaposhnikov }
1650a0dd5b05SAlexander Shaposhnikov 
1651bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains
1652bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup.
16533b876cc3SAlexander Shaposhnikov extern "C"
16543b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__setup")))
16553b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
16563b876cc3SAlexander Shaposhnikov void _bolt_instr_setup() {
1657a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(SAVE_ALL :::);
16583b876cc3SAlexander Shaposhnikov 
1659a0dd5b05SAlexander Shaposhnikov   report("Hello!\n");
16603b876cc3SAlexander Shaposhnikov 
1661a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(RESTORE_ALL :::);
16621cf23e5eSAlexander Shaposhnikov }
1663bbd9d610SAlexander Shaposhnikov 
16643b876cc3SAlexander Shaposhnikov extern "C"
16653b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__fini")))
16663b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
16673b876cc3SAlexander Shaposhnikov void _bolt_instr_fini() {
1668a0dd5b05SAlexander Shaposhnikov   report("Bye!\n");
1669a0dd5b05SAlexander Shaposhnikov   __bolt_instr_data_dump();
1670e067f2adSAlexander Shaposhnikov }
1671e067f2adSAlexander Shaposhnikov 
1672bbd9d610SAlexander Shaposhnikov #endif
1673cb8d701bSVladislav Khmelevsky #endif
1674