162aa74f8SRafael Auler //===-- instr.cpp -----------------------------------------------*- C++ -*-===// 262aa74f8SRafael Auler // 362aa74f8SRafael Auler // The LLVM Compiler Infrastructure 462aa74f8SRafael Auler // 562aa74f8SRafael Auler // This file is distributed under the University of Illinois Open Source 662aa74f8SRafael Auler // License. See LICENSE.TXT for details. 762aa74f8SRafael Auler // This file contains code that is linked to the final binary with a function 862aa74f8SRafael Auler // that is called at program exit to dump instrumented data collected during 962aa74f8SRafael Auler // execution. 1062aa74f8SRafael Auler // 1162aa74f8SRafael Auler //===----------------------------------------------------------------------===// 1262aa74f8SRafael Auler // 1316a497c6SRafael Auler // BOLT runtime instrumentation library for x86 Linux. Currently, BOLT does 1416a497c6SRafael Auler // not support linking modules with dependencies on one another into the final 1516a497c6SRafael Auler // binary (TODO?), which means this library has to be self-contained in a single 1616a497c6SRafael Auler // module. 1716a497c6SRafael Auler // 1816a497c6SRafael Auler // All extern declarations here need to be defined by BOLT itself. Those will be 1916a497c6SRafael Auler // undefined symbols that BOLT needs to resolve by emitting these symbols with 2016a497c6SRafael Auler // MCStreamer. Currently, Passes/Instrumentation.cpp is the pass responsible 2116a497c6SRafael Auler // for defining the symbols here and these two files have a tight coupling: one 2216a497c6SRafael Auler // working statically when you run BOLT and another during program runtime when 2316a497c6SRafael Auler // you run an instrumented binary. The main goal here is to output an fdata file 2416a497c6SRafael Auler // (BOLT profile) with the instrumentation counters inserted by the static pass. 2516a497c6SRafael Auler // Counters for indirect calls are an exception, as we can't know them 2616a497c6SRafael Auler // statically. These counters are created and managed here. To allow this, we 2716a497c6SRafael Auler // need a minimal framework for allocating memory dynamically. We provide this 2816a497c6SRafael Auler // with the BumpPtrAllocator class (not LLVM's, but our own version of it). 2916a497c6SRafael Auler // 3016a497c6SRafael Auler // Since this code is intended to be inserted into any executable, we decided to 3116a497c6SRafael Auler // make it standalone and do not depend on any external libraries (i.e. language 3216a497c6SRafael Auler // support libraries, such as glibc or stdc++). To allow this, we provide a few 3316a497c6SRafael Auler // light implementations of common OS interacting functionalities using direct 3416a497c6SRafael Auler // syscall wrappers. Our simple allocator doesn't manage deallocations that 3516a497c6SRafael Auler // fragment the memory space, so it's stack based. This is the minimal framework 3616a497c6SRafael Auler // provided here to allow processing instrumented counters and writing fdata. 3716a497c6SRafael Auler // 3816a497c6SRafael Auler // In the C++ idiom used here, we never use or rely on constructors or 3916a497c6SRafael Auler // destructors for global objects. That's because those need support from the 4016a497c6SRafael Auler // linker in initialization/finalization code, and we want to keep our linker 4116a497c6SRafael Auler // very simple. Similarly, we don't create any global objects that are zero 4216a497c6SRafael Auler // initialized, since those would need to go .bss, which our simple linker also 4316a497c6SRafael Auler // don't support (TODO?). 4462aa74f8SRafael Auler // 4562aa74f8SRafael Auler //===----------------------------------------------------------------------===// 4662aa74f8SRafael Auler 479bd71615SXun Li #include "common.h" 4862aa74f8SRafael Auler 4916a497c6SRafael Auler // Enables a very verbose logging to stderr useful when debugging 50cc4b2fb6SRafael Auler //#define ENABLE_DEBUG 51cc4b2fb6SRafael Auler 52cc4b2fb6SRafael Auler #ifdef ENABLE_DEBUG 53cc4b2fb6SRafael Auler #define DEBUG(X) \ 54cc4b2fb6SRafael Auler { X; } 55cc4b2fb6SRafael Auler #else 56cc4b2fb6SRafael Auler #define DEBUG(X) \ 57cc4b2fb6SRafael Auler {} 58cc4b2fb6SRafael Auler #endif 59cc4b2fb6SRafael Auler 60bbd9d610SAlexander Shaposhnikov #if !defined(__APPLE__) 61bbd9d610SAlexander Shaposhnikov 6216a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when 6316a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct 6416a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters 6516a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be 6616a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG. 6762aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[]; 6816a497c6SRafael Auler extern uint32_t __bolt_num_counters; 6916a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT, 7016a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a 7116a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs, 7216a497c6SRafael Auler // Location, IntrumentedNode and EntryNode. 7316a497c6SRafael Auler // Number of indirect call site descriptions 7416a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls; 7516a497c6SRafael Auler // Number of indirect call target descriptions 7616a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets; 77cc4b2fb6SRafael Auler // Number of function descriptions 78cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs; 7916a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk) 8016a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time; 81cc4b2fb6SRafael Auler // Filename to dump data to 8262aa74f8SRafael Auler extern char __bolt_instr_filename[]; 8316a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so 8416a497c6SRafael Auler // different invocations of the same program can be differentiated. 8516a497c6SRafael Auler extern bool __bolt_instr_use_pid; 8616a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass 8716a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these 8816a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to 8916a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We 9016a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT, 9116a497c6SRafael Auler // *not* the other way around. 9216a497c6SRafael Auler // TODO: We need better linking support to make that happen. 9316a497c6SRafael Auler extern void (*__bolt_trampoline_ind_call)(); 9416a497c6SRafael Auler extern void (*__bolt_trampoline_ind_tailcall)(); 9516a497c6SRafael Auler // Function pointers to init/fini routines in the binary, so we can resume 9616a497c6SRafael Auler // regular execution of these functions that we hooked 9716a497c6SRafael Auler extern void (*__bolt_instr_init_ptr)(); 9816a497c6SRafael Auler extern void (*__bolt_instr_fini_ptr)(); 9962aa74f8SRafael Auler 100cc4b2fb6SRafael Auler namespace { 101cc4b2fb6SRafael Auler 102cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space 103cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that 10416a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements. 10516a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we 10616a497c6SRafael Auler /// are done processing something. 107cc4b2fb6SRafael Auler class BumpPtrAllocator { 10816a497c6SRafael Auler /// This is written before each allocation and act as a canary to detect when 10916a497c6SRafael Auler /// a bug caused our program to cross allocation boundaries. 110cc4b2fb6SRafael Auler struct EntryMetadata { 111cc4b2fb6SRafael Auler uint64_t Magic; 112cc4b2fb6SRafael Auler uint64_t AllocSize; 113cc4b2fb6SRafael Auler }; 1149bd71615SXun Li 115cc4b2fb6SRafael Auler public: 116cc4b2fb6SRafael Auler void *allocate(uintptr_t Size) { 11716a497c6SRafael Auler Lock L(M); 118cc4b2fb6SRafael Auler if (StackBase == nullptr) { 11916a497c6SRafael Auler StackBase = reinterpret_cast<uint8_t *>( 12016a497c6SRafael Auler __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/, 12116a497c6SRafael Auler Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/ 12216a497c6SRafael Auler : 0x22 /* MAP_PRIVATE | MAP_ANONYMOUS*/, 12316a497c6SRafael Auler -1, 0)); 124cc4b2fb6SRafael Auler StackSize = 0; 125cc4b2fb6SRafael Auler } 126cc4b2fb6SRafael Auler Size = alignTo(Size + sizeof(EntryMetadata), 16); 127cc4b2fb6SRafael Auler uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata); 128cc4b2fb6SRafael Auler auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize); 12916a497c6SRafael Auler M->Magic = Magic; 130cc4b2fb6SRafael Auler M->AllocSize = Size; 131cc4b2fb6SRafael Auler StackSize += Size; 13216a497c6SRafael Auler assert(StackSize < MaxSize, "allocator ran out of memory"); 133cc4b2fb6SRafael Auler return AllocAddress; 134cc4b2fb6SRafael Auler } 135cc4b2fb6SRafael Auler 13616a497c6SRafael Auler #ifdef DEBUG 13716a497c6SRafael Auler /// Element-wise deallocation is only used for debugging to catch memory 13816a497c6SRafael Auler /// bugs by checking magic bytes. Ordinarily, we reset the allocator once 13916a497c6SRafael Auler /// we are done with it. Reset is done with clear(). There's no need 14016a497c6SRafael Auler /// to deallocate each element individually. 141cc4b2fb6SRafael Auler void deallocate(void *Ptr) { 14216a497c6SRafael Auler Lock L(M); 143cc4b2fb6SRafael Auler uint8_t MetadataOffset = sizeof(EntryMetadata); 144cc4b2fb6SRafael Auler auto *M = reinterpret_cast<EntryMetadata *>( 145cc4b2fb6SRafael Auler reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset); 146cc4b2fb6SRafael Auler const uint8_t *StackTop = StackBase + StackSize + MetadataOffset; 147cc4b2fb6SRafael Auler // Validate size 148cc4b2fb6SRafael Auler if (Ptr != StackTop - M->AllocSize) { 14916a497c6SRafael Auler // Failed validation, check if it is a pointer returned by operator new [] 150cc4b2fb6SRafael Auler MetadataOffset += 151cc4b2fb6SRafael Auler sizeof(uint64_t); // Space for number of elements alloc'ed 152cc4b2fb6SRafael Auler M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) - 153cc4b2fb6SRafael Auler MetadataOffset); 15416a497c6SRafael Auler // Ok, it failed both checks if this assertion fails. Stop the program, we 15516a497c6SRafael Auler // have a memory bug. 156cc4b2fb6SRafael Auler assert(Ptr == StackTop - M->AllocSize, 157cc4b2fb6SRafael Auler "must deallocate the last element alloc'ed"); 158cc4b2fb6SRafael Auler } 15916a497c6SRafael Auler assert(M->Magic == Magic, "allocator magic is corrupt"); 160cc4b2fb6SRafael Auler StackSize -= M->AllocSize; 161cc4b2fb6SRafael Auler } 16216a497c6SRafael Auler #else 16316a497c6SRafael Auler void deallocate(void *) {} 16416a497c6SRafael Auler #endif 16516a497c6SRafael Auler 16616a497c6SRafael Auler void clear() { 16716a497c6SRafael Auler Lock L(M); 16816a497c6SRafael Auler StackSize = 0; 16916a497c6SRafael Auler } 17016a497c6SRafael Auler 17116a497c6SRafael Auler /// Set mmap reservation size (only relevant before first allocation) 1729bd71615SXun Li void setMaxSize(uint64_t Size) { MaxSize = Size; } 17316a497c6SRafael Auler 17416a497c6SRafael Auler /// Set mmap reservation privacy (only relevant before first allocation) 1759bd71615SXun Li void setShared(bool S) { Shared = S; } 17616a497c6SRafael Auler 17716a497c6SRafael Auler void destroy() { 17816a497c6SRafael Auler if (StackBase == nullptr) 17916a497c6SRafael Auler return; 18016a497c6SRafael Auler __munmap(StackBase, MaxSize); 18116a497c6SRafael Auler } 182cc4b2fb6SRafael Auler 183cc4b2fb6SRafael Auler private: 18416a497c6SRafael Auler static constexpr uint64_t Magic = 0x1122334455667788ull; 18516a497c6SRafael Auler uint64_t MaxSize = 0xa00000; 186cc4b2fb6SRafael Auler uint8_t *StackBase{nullptr}; 187cc4b2fb6SRafael Auler uint64_t StackSize{0}; 18816a497c6SRafael Auler bool Shared{false}; 18916a497c6SRafael Auler Mutex M; 190cc4b2fb6SRafael Auler }; 191cc4b2fb6SRafael Auler 19216a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by 19316a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine. 19416a497c6SRafael Auler BumpPtrAllocator GlobalAlloc; 195cc4b2fb6SRafael Auler } // anonymous namespace 196cc4b2fb6SRafael Auler 197cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to 198cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the 199cc4b2fb6SRafael Auler // stack instead of in a data section (global). 2009bd71615SXun Li void *operator new(uintptr_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); } 201cc4b2fb6SRafael Auler void *operator new(uintptr_t Sz, BumpPtrAllocator &A, char C) { 202cc4b2fb6SRafael Auler auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz)); 203cc4b2fb6SRafael Auler memSet(Ptr, C, Sz); 204cc4b2fb6SRafael Auler return Ptr; 205cc4b2fb6SRafael Auler } 206cc4b2fb6SRafael Auler void *operator new[](uintptr_t Sz, BumpPtrAllocator &A) { 207cc4b2fb6SRafael Auler return A.allocate(Sz); 208cc4b2fb6SRafael Auler } 209cc4b2fb6SRafael Auler void *operator new[](uintptr_t Sz, BumpPtrAllocator &A, char C) { 210cc4b2fb6SRafael Auler auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz)); 211cc4b2fb6SRafael Auler memSet(Ptr, C, Sz); 212cc4b2fb6SRafael Auler return Ptr; 213cc4b2fb6SRafael Auler } 214cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc. 215cc4b2fb6SRafael Auler // C++ language weirdness 2169bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); } 217cc4b2fb6SRafael Auler 218cc4b2fb6SRafael Auler namespace { 219cc4b2fb6SRafael Auler 22016a497c6SRafael Auler /// Basic key-val atom stored in our hash 22116a497c6SRafael Auler struct SimpleHashTableEntryBase { 22216a497c6SRafael Auler uint64_t Key; 22316a497c6SRafael Auler uint64_t Val; 22416a497c6SRafael Auler }; 22516a497c6SRafael Auler 22616a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size 22716a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves 22816a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our 22916a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers. 23016a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime). 23116a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO) 23216a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it 23316a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for 23416a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a 23516a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites) 23616a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7, 23716a497c6SRafael Auler uint32_t IncSize = 7> 23816a497c6SRafael Auler class SimpleHashTable { 23916a497c6SRafael Auler public: 24016a497c6SRafael Auler using MapEntry = T; 24116a497c6SRafael Auler 24216a497c6SRafael Auler /// Increment by 1 the value of \p Key. If it is not in this table, it will be 24316a497c6SRafael Auler /// added to the table and its value set to 1. 24416a497c6SRafael Auler void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) { 24516a497c6SRafael Auler ++get(Key, Alloc).Val; 24616a497c6SRafael Auler } 24716a497c6SRafael Auler 24816a497c6SRafael Auler /// Basic member accessing interface. Here we pass the allocator explicitly to 24916a497c6SRafael Auler /// avoid storing a pointer to it as part of this table (remember there is one 25016a497c6SRafael Auler /// hash for each indirect call site, so we wan't to minimize our footprint). 25116a497c6SRafael Auler MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) { 25216a497c6SRafael Auler Lock L(M); 25316a497c6SRafael Auler if (TableRoot) 25416a497c6SRafael Auler return getEntry(TableRoot, Key, Key, Alloc, 0); 25516a497c6SRafael Auler return firstAllocation(Key, Alloc); 25616a497c6SRafael Auler } 25716a497c6SRafael Auler 25816a497c6SRafael Auler /// Traverses all elements in the table 25916a497c6SRafael Auler template <typename... Args> 26016a497c6SRafael Auler void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) { 26116a497c6SRafael Auler if (!TableRoot) 26216a497c6SRafael Auler return; 26316a497c6SRafael Auler return forEachElement(Callback, InitialSize, TableRoot, args...); 26416a497c6SRafael Auler } 26516a497c6SRafael Auler 26616a497c6SRafael Auler void resetCounters(); 26716a497c6SRafael Auler 26816a497c6SRafael Auler private: 26916a497c6SRafael Auler constexpr static uint64_t VacantMarker = 0; 27016a497c6SRafael Auler constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull; 27116a497c6SRafael Auler 27216a497c6SRafael Auler MapEntry *TableRoot{nullptr}; 27316a497c6SRafael Auler Mutex M; 27416a497c6SRafael Auler 27516a497c6SRafael Auler template <typename... Args> 27616a497c6SRafael Auler void forEachElement(void (*Callback)(MapEntry &, Args...), 27716a497c6SRafael Auler uint32_t NumEntries, MapEntry *Entries, Args... args) { 27816a497c6SRafael Auler for (int I = 0; I < NumEntries; ++I) { 27916a497c6SRafael Auler auto &Entry = Entries[I]; 28016a497c6SRafael Auler if (Entry.Key == VacantMarker) 28116a497c6SRafael Auler continue; 28216a497c6SRafael Auler if (Entry.Key & FollowUpTableMarker) { 28316a497c6SRafael Auler forEachElement(Callback, IncSize, 28416a497c6SRafael Auler reinterpret_cast<MapEntry *>(Entry.Key & 28516a497c6SRafael Auler ~FollowUpTableMarker), 28616a497c6SRafael Auler args...); 28716a497c6SRafael Auler continue; 28816a497c6SRafael Auler } 28916a497c6SRafael Auler Callback(Entry, args...); 29016a497c6SRafael Auler } 29116a497c6SRafael Auler } 29216a497c6SRafael Auler 29316a497c6SRafael Auler MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) { 29416a497c6SRafael Auler TableRoot = new (Alloc, 0) MapEntry[InitialSize]; 29516a497c6SRafael Auler auto &Entry = TableRoot[Key % InitialSize]; 29616a497c6SRafael Auler Entry.Key = Key; 29716a497c6SRafael Auler return Entry; 29816a497c6SRafael Auler } 29916a497c6SRafael Auler 30016a497c6SRafael Auler MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector, 30116a497c6SRafael Auler BumpPtrAllocator &Alloc, int CurLevel) { 30216a497c6SRafael Auler const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize; 30316a497c6SRafael Auler uint64_t Remainder = Selector / NumEntries; 30416a497c6SRafael Auler Selector = Selector % NumEntries; 30516a497c6SRafael Auler auto &Entry = Entries[Selector]; 30616a497c6SRafael Auler 30716a497c6SRafael Auler // A hit 30816a497c6SRafael Auler if (Entry.Key == Key) { 30916a497c6SRafael Auler return Entry; 31016a497c6SRafael Auler } 31116a497c6SRafael Auler 31216a497c6SRafael Auler // Vacant - add new entry 31316a497c6SRafael Auler if (Entry.Key == VacantMarker) { 31416a497c6SRafael Auler Entry.Key = Key; 31516a497c6SRafael Auler return Entry; 31616a497c6SRafael Auler } 31716a497c6SRafael Auler 31816a497c6SRafael Auler // Defer to the next level 31916a497c6SRafael Auler if (Entry.Key & FollowUpTableMarker) { 32016a497c6SRafael Auler return getEntry( 32116a497c6SRafael Auler reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker), 32216a497c6SRafael Auler Key, Remainder, Alloc, CurLevel + 1); 32316a497c6SRafael Auler } 32416a497c6SRafael Auler 32516a497c6SRafael Auler // Conflict - create the next level 32616a497c6SRafael Auler MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize]; 32716a497c6SRafael Auler uint64_t CurEntrySelector = Entry.Key / InitialSize; 32816a497c6SRafael Auler for (int I = 0; I < CurLevel; ++I) 32916a497c6SRafael Auler CurEntrySelector /= IncSize; 33016a497c6SRafael Auler CurEntrySelector = CurEntrySelector % IncSize; 33116a497c6SRafael Auler NextLevelTbl[CurEntrySelector] = Entry; 33216a497c6SRafael Auler Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker; 33316a497c6SRafael Auler return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1); 33416a497c6SRafael Auler } 33516a497c6SRafael Auler }; 33616a497c6SRafael Auler 33716a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) { 33816a497c6SRafael Auler Entry.Val = 0; 33916a497c6SRafael Auler } 34016a497c6SRafael Auler 34116a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y> 34216a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() { 34316a497c6SRafael Auler Lock L(M); 34416a497c6SRafael Auler forEachElement(resetIndCallCounter); 34516a497c6SRafael Auler } 34616a497c6SRafael Auler 34716a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter. 34816a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>; 34916a497c6SRafael Auler 35016a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the 35116a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening 35216a497c6SRafael Auler /// during runtime, one table per call site. 35316a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{ 35416a497c6SRafael Auler reinterpret_cast<IndirectCallHashTable *>(1)}; 35516a497c6SRafael Auler 35616a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes 35716a497c6SRafael Auler /// it 35816a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)}; 35916a497c6SRafael Auler 36016a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency 36116a497c6SRafael Auler /// as perceived by the basic block counter (Val). 36216a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase { 36316a497c6SRafael Auler uint64_t Calls; 36416a497c6SRafael Auler }; 36516a497c6SRafael Auler 36616a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>; 36716a497c6SRafael Auler 36816a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and 36916a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for 37016a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the 37116a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two 37216a497c6SRafael Auler /// possible scenarios here: 37316a497c6SRafael Auler /// 37416a497c6SRafael Auler /// * Entry BB has higher frequency than all known calls to this function. 37516a497c6SRafael Auler /// In this case, we have dynamic library code or any uninstrumented code 37616a497c6SRafael Auler /// calling this function. We will write the profile for these untracked 37716a497c6SRafael Auler /// calls as having source "0 [unknown] 0" in the fdata file. 37816a497c6SRafael Auler /// 37916a497c6SRafael Auler /// * Number of known calls is higher than the frequency of entry BB 38016a497c6SRafael Auler /// This only happens when there is no counter for the entry BB / callee 38116a497c6SRafael Auler /// function is not simple (in BOLT terms). We don't do anything special 38216a497c6SRafael Auler /// here and just ignore those (we still report all calls to the non-simple 38316a497c6SRafael Auler /// function, though). 38416a497c6SRafael Auler /// 38516a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase { 38616a497c6SRafael Auler public: 38716a497c6SRafael Auler CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {} 38816a497c6SRafael Auler 38916a497c6SRafael Auler MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); } 39016a497c6SRafael Auler 39116a497c6SRafael Auler private: 39216a497c6SRafael Auler // Different than the hash table for indirect call targets, we do store the 39316a497c6SRafael Auler // allocator here since there is only one call flow hash and space overhead 39416a497c6SRafael Auler // is negligible. 39516a497c6SRafael Auler BumpPtrAllocator &Alloc; 39616a497c6SRafael Auler }; 39716a497c6SRafael Auler 39816a497c6SRafael Auler /// 39916a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to 40016a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote() 40116a497c6SRafael Auler /// 40216a497c6SRafael Auler struct Location { 40316a497c6SRafael Auler uint32_t FunctionName; 40416a497c6SRafael Auler uint32_t Offset; 40516a497c6SRafael Auler }; 40616a497c6SRafael Auler 40716a497c6SRafael Auler struct CallDescription { 40816a497c6SRafael Auler Location From; 40916a497c6SRafael Auler uint32_t FromNode; 41016a497c6SRafael Auler Location To; 41116a497c6SRafael Auler uint32_t Counter; 41216a497c6SRafael Auler uint64_t TargetAddress; 41316a497c6SRafael Auler }; 41416a497c6SRafael Auler 41516a497c6SRafael Auler using IndCallDescription = Location; 41616a497c6SRafael Auler 41716a497c6SRafael Auler struct IndCallTargetDescription { 41816a497c6SRafael Auler Location Loc; 41916a497c6SRafael Auler uint64_t Address; 42016a497c6SRafael Auler }; 42116a497c6SRafael Auler 42216a497c6SRafael Auler struct EdgeDescription { 42316a497c6SRafael Auler Location From; 42416a497c6SRafael Auler uint32_t FromNode; 42516a497c6SRafael Auler Location To; 42616a497c6SRafael Auler uint32_t ToNode; 42716a497c6SRafael Auler uint32_t Counter; 42816a497c6SRafael Auler }; 42916a497c6SRafael Auler 43016a497c6SRafael Auler struct InstrumentedNode { 43116a497c6SRafael Auler uint32_t Node; 43216a497c6SRafael Auler uint32_t Counter; 43316a497c6SRafael Auler }; 43416a497c6SRafael Auler 43516a497c6SRafael Auler struct EntryNode { 43616a497c6SRafael Auler uint64_t Node; 43716a497c6SRafael Auler uint64_t Address; 43816a497c6SRafael Auler }; 43916a497c6SRafael Auler 44016a497c6SRafael Auler struct FunctionDescription { 44116a497c6SRafael Auler uint32_t NumLeafNodes; 44216a497c6SRafael Auler const InstrumentedNode *LeafNodes; 44316a497c6SRafael Auler uint32_t NumEdges; 44416a497c6SRafael Auler const EdgeDescription *Edges; 44516a497c6SRafael Auler uint32_t NumCalls; 44616a497c6SRafael Auler const CallDescription *Calls; 44716a497c6SRafael Auler uint32_t NumEntryNodes; 44816a497c6SRafael Auler const EntryNode *EntryNodes; 44916a497c6SRafael Auler 45016a497c6SRafael Auler /// Constructor will parse the serialized function metadata written by BOLT 45116a497c6SRafael Auler FunctionDescription(const uint8_t *FuncDesc); 45216a497c6SRafael Auler 45316a497c6SRafael Auler uint64_t getSize() const { 45416a497c6SRafael Auler return 16 + NumLeafNodes * sizeof(InstrumentedNode) + 45516a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + 45616a497c6SRafael Auler NumCalls * sizeof(CallDescription) + 45716a497c6SRafael Auler NumEntryNodes * sizeof(EntryNode); 45816a497c6SRafael Auler } 45916a497c6SRafael Auler }; 46016a497c6SRafael Auler 46116a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk 46216a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the 46316a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization 46416a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements. 46516a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs. 46616a497c6SRafael Auler struct ProfileWriterContext { 46716a497c6SRafael Auler IndCallDescription *IndCallDescriptions; 46816a497c6SRafael Auler IndCallTargetDescription *IndCallTargets; 46916a497c6SRafael Auler uint8_t *FuncDescriptions; 47016a497c6SRafael Auler char *Strings; // String table with function names used in this binary 47116a497c6SRafael Auler int FileDesc; // File descriptor for the file on disk backing this 47216a497c6SRafael Auler // information in memory via mmap 47316a497c6SRafael Auler void *MMapPtr; // The mmap ptr 47416a497c6SRafael Auler int MMapSize; // The mmap size 47516a497c6SRafael Auler 47616a497c6SRafael Auler /// Hash table storing all possible call destinations to detect untracked 47716a497c6SRafael Auler /// calls and correctly report them as [unknown] in output fdata. 47816a497c6SRafael Auler CallFlowHashTable *CallFlowTable; 47916a497c6SRafael Auler 48016a497c6SRafael Auler /// Lookup the sorted indirect call target vector to fetch function name and 48116a497c6SRafael Auler /// offset for an arbitrary function pointer. 48216a497c6SRafael Auler const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const; 48316a497c6SRafael Auler }; 48416a497c6SRafael Auler 48516a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares 48616a497c6SRafael Auler /// at most Size characters. 487cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) { 488821480d2SRafael Auler while (*Str1 == *Str2) { 489821480d2SRafael Auler if (*Str1 == '\0' || --Size == 0) 490821480d2SRafael Auler return 0; 491821480d2SRafael Auler ++Str1; 492821480d2SRafael Auler ++Str2; 493821480d2SRafael Auler } 494821480d2SRafael Auler return 1; 495821480d2SRafael Auler } 496821480d2SRafael Auler 49716a497c6SRafael Auler /// Output Location to the fdata file 49816a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf, 499cc4b2fb6SRafael Auler const Location Loc, uint32_t BufSize) { 500821480d2SRafael Auler // fdata location format: Type Name Offset 501821480d2SRafael Auler // Type 1 - regular symbol 502821480d2SRafael Auler OutBuf = strCopy(OutBuf, "1 "); 50316a497c6SRafael Auler const char *Str = Ctx.Strings + Loc.FunctionName; 504cc4b2fb6SRafael Auler uint32_t Size = 25; 50562aa74f8SRafael Auler while (*Str) { 50662aa74f8SRafael Auler *OutBuf++ = *Str++; 507cc4b2fb6SRafael Auler if (++Size >= BufSize) 508cc4b2fb6SRafael Auler break; 50962aa74f8SRafael Auler } 510cc4b2fb6SRafael Auler assert(!*Str, "buffer overflow, function name too large"); 51162aa74f8SRafael Auler *OutBuf++ = ' '; 512821480d2SRafael Auler OutBuf = intToStr(OutBuf, Loc.Offset, 16); 51362aa74f8SRafael Auler *OutBuf++ = ' '; 51462aa74f8SRafael Auler return OutBuf; 51562aa74f8SRafael Auler } 51662aa74f8SRafael Auler 51716a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc 51816a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file. 51916a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote() 52016a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) { 52116a497c6SRafael Auler NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc); 52216a497c6SRafael Auler DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10)); 52316a497c6SRafael Auler LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4); 52416a497c6SRafael Auler 52516a497c6SRafael Auler NumEdges = *reinterpret_cast<const uint32_t *>( 52616a497c6SRafael Auler FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode)); 52716a497c6SRafael Auler DEBUG(reportNumber("NumEdges = ", NumEdges, 10)); 52816a497c6SRafael Auler Edges = reinterpret_cast<const EdgeDescription *>( 52916a497c6SRafael Auler FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode)); 53016a497c6SRafael Auler 53116a497c6SRafael Auler NumCalls = *reinterpret_cast<const uint32_t *>( 53216a497c6SRafael Auler FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) + 53316a497c6SRafael Auler NumEdges * sizeof(EdgeDescription)); 53416a497c6SRafael Auler DEBUG(reportNumber("NumCalls = ", NumCalls, 10)); 53516a497c6SRafael Auler Calls = reinterpret_cast<const CallDescription *>( 53616a497c6SRafael Auler FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) + 53716a497c6SRafael Auler NumEdges * sizeof(EdgeDescription)); 53816a497c6SRafael Auler NumEntryNodes = *reinterpret_cast<const uint32_t *>( 53916a497c6SRafael Auler FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) + 54016a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription)); 54116a497c6SRafael Auler DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10)); 54216a497c6SRafael Auler EntryNodes = reinterpret_cast<const EntryNode *>( 54316a497c6SRafael Auler FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) + 54416a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription)); 54516a497c6SRafael Auler } 54616a497c6SRafael Auler 54716a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes 54816a497c6SRafael Auler /// section 549ba31344fSRafael Auler #ifdef HAVE_ELF_H 55016a497c6SRafael Auler ProfileWriterContext readDescriptions() { 55116a497c6SRafael Auler ProfileWriterContext Result; 552821480d2SRafael Auler uint64_t FD = __open("/proc/self/exe", 553821480d2SRafael Auler /*flags=*/0 /*O_RDONLY*/, 554821480d2SRafael Auler /*mode=*/0666); 555cc4b2fb6SRafael Auler assert(static_cast<int64_t>(FD) > 0, "Failed to open /proc/self/exe"); 556821480d2SRafael Auler Result.FileDesc = FD; 557821480d2SRafael Auler 558821480d2SRafael Auler // mmap our binary to memory 559821480d2SRafael Auler uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/); 560821480d2SRafael Auler uint8_t *BinContents = reinterpret_cast<uint8_t *>( 561821480d2SRafael Auler __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0)); 562821480d2SRafael Auler Result.MMapPtr = BinContents; 563821480d2SRafael Auler Result.MMapSize = Size; 564821480d2SRafael Auler Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents); 565821480d2SRafael Auler Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff); 566821480d2SRafael Auler Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>( 567821480d2SRafael Auler BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize); 568821480d2SRafael Auler 569821480d2SRafael Auler // Find .bolt.instr.tables with the data we need and set pointers to it 570821480d2SRafael Auler for (int I = 0; I < Hdr->e_shnum; ++I) { 571821480d2SRafael Auler char *SecName = reinterpret_cast<char *>( 572821480d2SRafael Auler BinContents + StringTblHeader->sh_offset + Shdr->sh_name); 573821480d2SRafael Auler if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) { 574821480d2SRafael Auler Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff + 575821480d2SRafael Auler (I + 1) * Hdr->e_shentsize); 576821480d2SRafael Auler continue; 577821480d2SRafael Auler } 578821480d2SRafael Auler // Actual contents of the ELF note start after offset 20 decimal: 579821480d2SRafael Auler // Offset 0: Producer name size (4 bytes) 580821480d2SRafael Auler // Offset 4: Contents size (4 bytes) 581821480d2SRafael Auler // Offset 8: Note type (4 bytes) 582821480d2SRafael Auler // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary) 583821480d2SRafael Auler // Offset 20: Contents 58416a497c6SRafael Auler uint32_t IndCallDescSize = 585cc4b2fb6SRafael Auler *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20); 58616a497c6SRafael Auler uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>( 58716a497c6SRafael Auler BinContents + Shdr->sh_offset + 24 + IndCallDescSize); 58816a497c6SRafael Auler uint32_t FuncDescSize = 58916a497c6SRafael Auler *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 + 59016a497c6SRafael Auler IndCallDescSize + IndCallTargetDescSize); 59116a497c6SRafael Auler Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>( 59216a497c6SRafael Auler BinContents + Shdr->sh_offset + 24); 59316a497c6SRafael Auler Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>( 59416a497c6SRafael Auler BinContents + Shdr->sh_offset + 28 + IndCallDescSize); 59516a497c6SRafael Auler Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 + 59616a497c6SRafael Auler IndCallDescSize + IndCallTargetDescSize; 59716a497c6SRafael Auler Result.Strings = reinterpret_cast<char *>( 59816a497c6SRafael Auler BinContents + Shdr->sh_offset + 32 + IndCallDescSize + 59916a497c6SRafael Auler IndCallTargetDescSize + FuncDescSize); 600821480d2SRafael Auler return Result; 601821480d2SRafael Auler } 602821480d2SRafael Auler const char ErrMsg[] = 603821480d2SRafael Auler "BOLT instrumentation runtime error: could not find section " 604821480d2SRafael Auler ".bolt.instr.tables\n"; 605821480d2SRafael Auler reportError(ErrMsg, sizeof(ErrMsg)); 606821480d2SRafael Auler return Result; 607821480d2SRafael Auler } 608ba31344fSRafael Auler #else 60916a497c6SRafael Auler ProfileWriterContext readDescriptions() { 61016a497c6SRafael Auler ProfileWriterContext Result; 611ba31344fSRafael Auler const char ErrMsg[] = 612ba31344fSRafael Auler "BOLT instrumentation runtime error: unsupported binary format.\n"; 613ba31344fSRafael Auler reportError(ErrMsg, sizeof(ErrMsg)); 614ba31344fSRafael Auler return Result; 615ba31344fSRafael Auler } 616ba31344fSRafael Auler #endif 617821480d2SRafael Auler 61816a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane 61916a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) { 620cc4b2fb6SRafael Auler char StatMsg[BufSize]; 621cc4b2fb6SRafael Auler char *StatPtr = StatMsg; 62216a497c6SRafael Auler StatPtr = 62316a497c6SRafael Auler strCopy(StatPtr, 62416a497c6SRafael Auler "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: "); 625cc4b2fb6SRafael Auler StatPtr = intToStr(StatPtr, 62616a497c6SRafael Auler Ctx.FuncDescriptions - 62716a497c6SRafael Auler reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions), 628cc4b2fb6SRafael Auler 10); 629cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\nFuncDescSize: "); 630cc4b2fb6SRafael Auler StatPtr = intToStr( 631cc4b2fb6SRafael Auler StatPtr, 63216a497c6SRafael Auler reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10); 63316a497c6SRafael Auler StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: "); 63416a497c6SRafael Auler StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10); 635cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: "); 636cc4b2fb6SRafael Auler StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10); 637cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\n"); 638cc4b2fb6SRafael Auler __write(2, StatMsg, StatPtr - StatMsg); 639cc4b2fb6SRafael Auler } 640cc4b2fb6SRafael Auler 641cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store 642cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store 643cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning 644cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in 645cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes. 646cc4b2fb6SRafael Auler struct Edge { 647cc4b2fb6SRafael Auler uint32_t Node; // Index in nodes array regarding the destination of this edge 648cc4b2fb6SRafael Auler uint32_t ID; // Edge index in an array comprising all edges of the graph 649cc4b2fb6SRafael Auler }; 650cc4b2fb6SRafael Auler 651cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node 652cc4b2fb6SRafael Auler struct Node { 653cc4b2fb6SRafael Auler uint32_t NumInEdges{0}; // Input edge count used to size InEdge 654cc4b2fb6SRafael Auler uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges 655cc4b2fb6SRafael Auler Edge *InEdges{nullptr}; // Created and managed by \p Graph 656cc4b2fb6SRafael Auler Edge *OutEdges{nullptr}; // ditto 657cc4b2fb6SRafael Auler }; 658cc4b2fb6SRafael Auler 659cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and 660cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding 661cc4b2fb6SRafael Auler /// spanning tree nodes. 662cc4b2fb6SRafael Auler struct Graph { 663cc4b2fb6SRafael Auler uint32_t NumNodes; 664cc4b2fb6SRafael Auler Node *CFGNodes; 665cc4b2fb6SRafael Auler Node *SpanningTreeNodes; 66616a497c6SRafael Auler uint64_t *EdgeFreqs; 66716a497c6SRafael Auler uint64_t *CallFreqs; 668cc4b2fb6SRafael Auler BumpPtrAllocator &Alloc; 66916a497c6SRafael Auler const FunctionDescription &D; 670cc4b2fb6SRafael Auler 67116a497c6SRafael Auler /// Reads a list of edges from function description \p D and builds 672cc4b2fb6SRafael Auler /// the graph from it. Allocates several internal dynamic structures that are 67316a497c6SRafael Auler /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all 674cc4b2fb6SRafael Auler /// spanning tree leaf nodes descriptions (their counters). They are the seed 675cc4b2fb6SRafael Auler /// used to compute the rest of the missing edge counts in a bottom-up 676cc4b2fb6SRafael Auler /// traversal of the spanning tree. 67716a497c6SRafael Auler Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D, 67816a497c6SRafael Auler const uint64_t *Counters, ProfileWriterContext &Ctx); 679cc4b2fb6SRafael Auler ~Graph(); 680cc4b2fb6SRafael Auler void dump() const; 68116a497c6SRafael Auler 68216a497c6SRafael Auler private: 68316a497c6SRafael Auler void computeEdgeFrequencies(const uint64_t *Counters, 68416a497c6SRafael Auler ProfileWriterContext &Ctx); 68516a497c6SRafael Auler void dumpEdgeFreqs() const; 686cc4b2fb6SRafael Auler }; 687cc4b2fb6SRafael Auler 68816a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D, 68916a497c6SRafael Auler const uint64_t *Counters, ProfileWriterContext &Ctx) 69016a497c6SRafael Auler : Alloc(Alloc), D(D) { 691cc4b2fb6SRafael Auler DEBUG(reportNumber("G = 0x", (uint64_t)this, 16)); 692cc4b2fb6SRafael Auler // First pass to determine number of nodes 69316a497c6SRafael Auler int32_t MaxNodes = -1; 69416a497c6SRafael Auler CallFreqs = nullptr; 69516a497c6SRafael Auler EdgeFreqs = nullptr; 69616a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 69716a497c6SRafael Auler if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes) 69816a497c6SRafael Auler MaxNodes = D.Edges[I].FromNode; 69916a497c6SRafael Auler if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes) 70016a497c6SRafael Auler MaxNodes = D.Edges[I].ToNode; 701cc4b2fb6SRafael Auler } 70216a497c6SRafael Auler for (int I = 0; I < D.NumLeafNodes; ++I) { 70316a497c6SRafael Auler if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes) 70416a497c6SRafael Auler MaxNodes = D.LeafNodes[I].Node; 705cc4b2fb6SRafael Auler } 70616a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 70716a497c6SRafael Auler if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes) 70816a497c6SRafael Auler MaxNodes = D.Calls[I].FromNode; 70916a497c6SRafael Auler } 71016a497c6SRafael Auler // No nodes? Nothing to do 71116a497c6SRafael Auler if (MaxNodes < 0) { 71216a497c6SRafael Auler DEBUG(report("No nodes!\n")); 713cc4b2fb6SRafael Auler CFGNodes = nullptr; 714cc4b2fb6SRafael Auler SpanningTreeNodes = nullptr; 715cc4b2fb6SRafael Auler NumNodes = 0; 716cc4b2fb6SRafael Auler return; 717cc4b2fb6SRafael Auler } 718cc4b2fb6SRafael Auler ++MaxNodes; 719cc4b2fb6SRafael Auler DEBUG(reportNumber("NumNodes = ", MaxNodes, 10)); 72016a497c6SRafael Auler NumNodes = static_cast<uint32_t>(MaxNodes); 721cc4b2fb6SRafael Auler 722cc4b2fb6SRafael Auler // Initial allocations 723cc4b2fb6SRafael Auler CFGNodes = new (Alloc) Node[MaxNodes]; 724cc4b2fb6SRafael Auler DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16)); 725cc4b2fb6SRafael Auler SpanningTreeNodes = new (Alloc) Node[MaxNodes]; 726cc4b2fb6SRafael Auler DEBUG(reportNumber("G->SpanningTreeNodes = 0x", 727cc4b2fb6SRafael Auler (uint64_t)SpanningTreeNodes, 16)); 728cc4b2fb6SRafael Auler 729cc4b2fb6SRafael Auler // Figure out how much to allocate to each vector (in/out edge sets) 73016a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 73116a497c6SRafael Auler CFGNodes[D.Edges[I].FromNode].NumOutEdges++; 73216a497c6SRafael Auler CFGNodes[D.Edges[I].ToNode].NumInEdges++; 73316a497c6SRafael Auler if (D.Edges[I].Counter != 0xffffffff) 734cc4b2fb6SRafael Auler continue; 735cc4b2fb6SRafael Auler 73616a497c6SRafael Auler SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++; 73716a497c6SRafael Auler SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++; 738cc4b2fb6SRafael Auler } 739cc4b2fb6SRafael Auler 740cc4b2fb6SRafael Auler // Allocate in/out edge sets 741cc4b2fb6SRafael Auler for (int I = 0; I < MaxNodes; ++I) { 742cc4b2fb6SRafael Auler if (CFGNodes[I].NumInEdges > 0) 743cc4b2fb6SRafael Auler CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges]; 744cc4b2fb6SRafael Auler if (CFGNodes[I].NumOutEdges > 0) 745cc4b2fb6SRafael Auler CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges]; 746cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].NumInEdges > 0) 747cc4b2fb6SRafael Auler SpanningTreeNodes[I].InEdges = 748cc4b2fb6SRafael Auler new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges]; 749cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].NumOutEdges > 0) 750cc4b2fb6SRafael Auler SpanningTreeNodes[I].OutEdges = 751cc4b2fb6SRafael Auler new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges]; 752cc4b2fb6SRafael Auler CFGNodes[I].NumInEdges = 0; 753cc4b2fb6SRafael Auler CFGNodes[I].NumOutEdges = 0; 754cc4b2fb6SRafael Auler SpanningTreeNodes[I].NumInEdges = 0; 755cc4b2fb6SRafael Auler SpanningTreeNodes[I].NumOutEdges = 0; 756cc4b2fb6SRafael Auler } 757cc4b2fb6SRafael Auler 758cc4b2fb6SRafael Auler // Fill in/out edge sets 75916a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 76016a497c6SRafael Auler const uint32_t Src = D.Edges[I].FromNode; 76116a497c6SRafael Auler const uint32_t Dst = D.Edges[I].ToNode; 762cc4b2fb6SRafael Auler Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++]; 763cc4b2fb6SRafael Auler E->Node = Dst; 764cc4b2fb6SRafael Auler E->ID = I; 765cc4b2fb6SRafael Auler 766cc4b2fb6SRafael Auler E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++]; 767cc4b2fb6SRafael Auler E->Node = Src; 768cc4b2fb6SRafael Auler E->ID = I; 769cc4b2fb6SRafael Auler 77016a497c6SRafael Auler if (D.Edges[I].Counter != 0xffffffff) 771cc4b2fb6SRafael Auler continue; 772cc4b2fb6SRafael Auler 773cc4b2fb6SRafael Auler E = &SpanningTreeNodes[Src] 774cc4b2fb6SRafael Auler .OutEdges[SpanningTreeNodes[Src].NumOutEdges++]; 775cc4b2fb6SRafael Auler E->Node = Dst; 776cc4b2fb6SRafael Auler E->ID = I; 777cc4b2fb6SRafael Auler 778cc4b2fb6SRafael Auler E = &SpanningTreeNodes[Dst] 779cc4b2fb6SRafael Auler .InEdges[SpanningTreeNodes[Dst].NumInEdges++]; 780cc4b2fb6SRafael Auler E->Node = Src; 781cc4b2fb6SRafael Auler E->ID = I; 782cc4b2fb6SRafael Auler } 78316a497c6SRafael Auler 78416a497c6SRafael Auler computeEdgeFrequencies(Counters, Ctx); 785cc4b2fb6SRafael Auler } 786cc4b2fb6SRafael Auler 787cc4b2fb6SRafael Auler Graph::~Graph() { 78816a497c6SRafael Auler if (CallFreqs) 78916a497c6SRafael Auler Alloc.deallocate(CallFreqs); 79016a497c6SRafael Auler if (EdgeFreqs) 79116a497c6SRafael Auler Alloc.deallocate(EdgeFreqs); 792cc4b2fb6SRafael Auler for (int I = NumNodes - 1; I >= 0; --I) { 793cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].OutEdges) 794cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes[I].OutEdges); 795cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].InEdges) 796cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes[I].InEdges); 797cc4b2fb6SRafael Auler if (CFGNodes[I].OutEdges) 798cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes[I].OutEdges); 799cc4b2fb6SRafael Auler if (CFGNodes[I].InEdges) 800cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes[I].InEdges); 801cc4b2fb6SRafael Auler } 802cc4b2fb6SRafael Auler if (SpanningTreeNodes) 803cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes); 804cc4b2fb6SRafael Auler if (CFGNodes) 805cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes); 806cc4b2fb6SRafael Auler } 807cc4b2fb6SRafael Auler 808cc4b2fb6SRafael Auler void Graph::dump() const { 809cc4b2fb6SRafael Auler reportNumber("Dumping graph with number of nodes: ", NumNodes, 10); 810cc4b2fb6SRafael Auler report(" Full graph:\n"); 811cc4b2fb6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 812cc4b2fb6SRafael Auler const Node *N = &CFGNodes[I]; 813cc4b2fb6SRafael Auler reportNumber(" Node #", I, 10); 814cc4b2fb6SRafael Auler reportNumber(" InEdges total ", N->NumInEdges, 10); 815cc4b2fb6SRafael Auler for (int J = 0; J < N->NumInEdges; ++J) 816cc4b2fb6SRafael Auler reportNumber(" ", N->InEdges[J].Node, 10); 817cc4b2fb6SRafael Auler reportNumber(" OutEdges total ", N->NumOutEdges, 10); 818cc4b2fb6SRafael Auler for (int J = 0; J < N->NumOutEdges; ++J) 819cc4b2fb6SRafael Auler reportNumber(" ", N->OutEdges[J].Node, 10); 820cc4b2fb6SRafael Auler report("\n"); 821cc4b2fb6SRafael Auler } 822cc4b2fb6SRafael Auler report(" Spanning tree:\n"); 823cc4b2fb6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 824cc4b2fb6SRafael Auler const Node *N = &SpanningTreeNodes[I]; 825cc4b2fb6SRafael Auler reportNumber(" Node #", I, 10); 826cc4b2fb6SRafael Auler reportNumber(" InEdges total ", N->NumInEdges, 10); 827cc4b2fb6SRafael Auler for (int J = 0; J < N->NumInEdges; ++J) 828cc4b2fb6SRafael Auler reportNumber(" ", N->InEdges[J].Node, 10); 829cc4b2fb6SRafael Auler reportNumber(" OutEdges total ", N->NumOutEdges, 10); 830cc4b2fb6SRafael Auler for (int J = 0; J < N->NumOutEdges; ++J) 831cc4b2fb6SRafael Auler reportNumber(" ", N->OutEdges[J].Node, 10); 832cc4b2fb6SRafael Auler report("\n"); 833cc4b2fb6SRafael Auler } 834cc4b2fb6SRafael Auler } 835cc4b2fb6SRafael Auler 83616a497c6SRafael Auler void Graph::dumpEdgeFreqs() const { 83716a497c6SRafael Auler reportNumber( 83816a497c6SRafael Auler "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10); 83916a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 84016a497c6SRafael Auler reportNumber("* Src: ", D.Edges[I].FromNode, 10); 84116a497c6SRafael Auler reportNumber(" Dst: ", D.Edges[I].ToNode, 10); 842cc4b2fb6SRafael Auler reportNumber(" Cnt: ", EdgeFreqs[I], 10); 843cc4b2fb6SRafael Auler } 844cc4b2fb6SRafael Auler } 845cc4b2fb6SRafael Auler 84616a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of 84716a497c6SRafael Auler /// the function CFG 84816a497c6SRafael Auler struct NodeToCallsMap { 84916a497c6SRafael Auler struct MapEntry { 85016a497c6SRafael Auler uint32_t NumCalls; 85116a497c6SRafael Auler uint32_t *Calls; 85216a497c6SRafael Auler }; 85316a497c6SRafael Auler MapEntry *Entries; 85416a497c6SRafael Auler BumpPtrAllocator &Alloc; 85516a497c6SRafael Auler const uint32_t NumNodes; 856cc4b2fb6SRafael Auler 85716a497c6SRafael Auler NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D, 85816a497c6SRafael Auler uint32_t NumNodes) 85916a497c6SRafael Auler : Alloc(Alloc), NumNodes(NumNodes) { 86016a497c6SRafael Auler Entries = new (Alloc, 0) MapEntry[NumNodes]; 86116a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 86216a497c6SRafael Auler DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10)); 86316a497c6SRafael Auler ++Entries[D.Calls[I].FromNode].NumCalls; 86416a497c6SRafael Auler } 86516a497c6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 86616a497c6SRafael Auler Entries[I].Calls = Entries[I].NumCalls ? new (Alloc) 86716a497c6SRafael Auler uint32_t[Entries[I].NumCalls] 86816a497c6SRafael Auler : nullptr; 86916a497c6SRafael Auler Entries[I].NumCalls = 0; 87016a497c6SRafael Auler } 87116a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 87216a497c6SRafael Auler auto &Entry = Entries[D.Calls[I].FromNode]; 87316a497c6SRafael Auler Entry.Calls[Entry.NumCalls++] = I; 87416a497c6SRafael Auler } 87516a497c6SRafael Auler } 87616a497c6SRafael Auler 87716a497c6SRafael Auler /// Set the frequency of all calls in node \p NodeID to Freq. However, if 87816a497c6SRafael Auler /// the calls have their own counters and do not depend on the basic block 87916a497c6SRafael Auler /// counter, this means they have landing pads and throw exceptions. In this 88016a497c6SRafael Auler /// case, set their frequency with their counters and return the maximum 88116a497c6SRafael Auler /// value observed in such counters. This will be used as the new frequency 88216a497c6SRafael Auler /// at basic block entry. This is used to fix the CFG edge frequencies in the 88316a497c6SRafael Auler /// presence of exceptions. 88416a497c6SRafael Auler uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs, 88516a497c6SRafael Auler const FunctionDescription &D, 88616a497c6SRafael Auler const uint64_t *Counters, 88716a497c6SRafael Auler ProfileWriterContext &Ctx) const { 88816a497c6SRafael Auler const auto &Entry = Entries[NodeID]; 88916a497c6SRafael Auler uint64_t MaxValue = 0ull; 89016a497c6SRafael Auler for (int I = 0, E = Entry.NumCalls; I != E; ++I) { 89116a497c6SRafael Auler const auto CallID = Entry.Calls[I]; 89216a497c6SRafael Auler DEBUG(reportNumber(" Setting freq for call ID: ", CallID, 10)); 89316a497c6SRafael Auler auto &CallDesc = D.Calls[CallID]; 89416a497c6SRafael Auler if (CallDesc.Counter == 0xffffffff) { 89516a497c6SRafael Auler CallFreqs[CallID] = Freq; 89616a497c6SRafael Auler DEBUG(reportNumber(" with : ", Freq, 10)); 89716a497c6SRafael Auler } else { 89816a497c6SRafael Auler const auto CounterVal = Counters[CallDesc.Counter]; 89916a497c6SRafael Auler CallFreqs[CallID] = CounterVal; 90016a497c6SRafael Auler MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue; 90116a497c6SRafael Auler DEBUG(reportNumber(" with (private counter) : ", CounterVal, 10)); 90216a497c6SRafael Auler } 90316a497c6SRafael Auler DEBUG(reportNumber(" Address: 0x", CallDesc.TargetAddress, 16)); 90416a497c6SRafael Auler if (CallFreqs[CallID] > 0) 90516a497c6SRafael Auler Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls += 90616a497c6SRafael Auler CallFreqs[CallID]; 90716a497c6SRafael Auler } 90816a497c6SRafael Auler return MaxValue; 90916a497c6SRafael Auler } 91016a497c6SRafael Auler 91116a497c6SRafael Auler ~NodeToCallsMap() { 91216a497c6SRafael Auler for (int I = NumNodes - 1; I >= 0; --I) { 91316a497c6SRafael Auler if (Entries[I].Calls) 91416a497c6SRafael Auler Alloc.deallocate(Entries[I].Calls); 91516a497c6SRafael Auler } 91616a497c6SRafael Auler Alloc.deallocate(Entries); 91716a497c6SRafael Auler } 91816a497c6SRafael Auler }; 91916a497c6SRafael Auler 92016a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented 92116a497c6SRafael Auler /// by G, as well as another array for each call. 92216a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters, 92316a497c6SRafael Auler ProfileWriterContext &Ctx) { 92416a497c6SRafael Auler if (NumNodes == 0) 92516a497c6SRafael Auler return; 92616a497c6SRafael Auler 92716a497c6SRafael Auler EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr; 92816a497c6SRafael Auler CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr; 92916a497c6SRafael Auler 93016a497c6SRafael Auler // Setup a lookup for calls present in each node (BB) 93116a497c6SRafael Auler NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes); 932cc4b2fb6SRafael Auler 933cc4b2fb6SRafael Auler // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the 934cc4b2fb6SRafael Auler // spanning tree don't have explicit counters. We must infer their value using 935cc4b2fb6SRafael Auler // a linear combination of other counters (sum of counters of the outgoing 936cc4b2fb6SRafael Auler // edges minus sum of counters of the incoming edges). 93716a497c6SRafael Auler uint32_t *Stack = new (Alloc) uint32_t [NumNodes]; 938cc4b2fb6SRafael Auler uint32_t StackTop = 0; 939cc4b2fb6SRafael Auler enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED }; 94016a497c6SRafael Auler Status *Visited = new (Alloc, 0) Status[NumNodes]; 94116a497c6SRafael Auler uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes]; 94216a497c6SRafael Auler uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes]; 943cc4b2fb6SRafael Auler 944cc4b2fb6SRafael Auler // Setup a fast lookup for frequency of leaf nodes, which have special 945cc4b2fb6SRafael Auler // basic block frequency instrumentation (they are not edge profiled). 94616a497c6SRafael Auler for (int I = 0; I < D.NumLeafNodes; ++I) { 94716a497c6SRafael Auler LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter]; 948cc4b2fb6SRafael Auler DEBUG({ 94916a497c6SRafael Auler if (Counters[D.LeafNodes[I].Counter] > 0) { 95016a497c6SRafael Auler reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10); 95116a497c6SRafael Auler reportNumber(" Counter: ", Counters[D.LeafNodes[I].Counter], 10); 952cc4b2fb6SRafael Auler } 953cc4b2fb6SRafael Auler }); 95416a497c6SRafael Auler } 95516a497c6SRafael Auler for (int I = 0; I < D.NumEntryNodes; ++I) { 95616a497c6SRafael Auler EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address; 95716a497c6SRafael Auler DEBUG({ 95816a497c6SRafael Auler reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10); 95916a497c6SRafael Auler reportNumber(" Address: ", D.EntryNodes[I].Address, 16); 96016a497c6SRafael Auler }); 961cc4b2fb6SRafael Auler } 962cc4b2fb6SRafael Auler // Add all root nodes to the stack 96316a497c6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 96416a497c6SRafael Auler if (SpanningTreeNodes[I].NumInEdges == 0) 965cc4b2fb6SRafael Auler Stack[StackTop++] = I; 966cc4b2fb6SRafael Auler } 967cc4b2fb6SRafael Auler // Empty stack? 968cc4b2fb6SRafael Auler if (StackTop == 0) { 96916a497c6SRafael Auler DEBUG(report("Empty stack!\n")); 97016a497c6SRafael Auler Alloc.deallocate(EntryAddress); 971cc4b2fb6SRafael Auler Alloc.deallocate(LeafFrequency); 972cc4b2fb6SRafael Auler Alloc.deallocate(Visited); 973cc4b2fb6SRafael Auler Alloc.deallocate(Stack); 97416a497c6SRafael Auler CallMap->~NodeToCallsMap(); 97516a497c6SRafael Auler Alloc.deallocate(CallMap); 97616a497c6SRafael Auler if (CallFreqs) 97716a497c6SRafael Auler Alloc.deallocate(CallFreqs); 97816a497c6SRafael Auler if (EdgeFreqs) 97916a497c6SRafael Auler Alloc.deallocate(EdgeFreqs); 98016a497c6SRafael Auler EdgeFreqs = nullptr; 98116a497c6SRafael Auler CallFreqs = nullptr; 98216a497c6SRafael Auler return; 983cc4b2fb6SRafael Auler } 984cc4b2fb6SRafael Auler // Add all known edge counts, will infer the rest 98516a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 98616a497c6SRafael Auler const uint32_t C = D.Edges[I].Counter; 987cc4b2fb6SRafael Auler if (C == 0xffffffff) // inferred counter - we will compute its value 988cc4b2fb6SRafael Auler continue; 98916a497c6SRafael Auler EdgeFreqs[I] = Counters[C]; 990cc4b2fb6SRafael Auler } 991cc4b2fb6SRafael Auler 992cc4b2fb6SRafael Auler while (StackTop > 0) { 993cc4b2fb6SRafael Auler const uint32_t Cur = Stack[--StackTop]; 994cc4b2fb6SRafael Auler DEBUG({ 995cc4b2fb6SRafael Auler if (Visited[Cur] == S_VISITING) 996cc4b2fb6SRafael Auler report("(visiting) "); 997cc4b2fb6SRafael Auler else 998cc4b2fb6SRafael Auler report("(new) "); 999cc4b2fb6SRafael Auler reportNumber("Cur: ", Cur, 10); 1000cc4b2fb6SRafael Auler }); 1001cc4b2fb6SRafael Auler 1002cc4b2fb6SRafael Auler // This shouldn't happen in a tree 1003cc4b2fb6SRafael Auler assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack"); 1004cc4b2fb6SRafael Auler if (Visited[Cur] == S_NEW) { 1005cc4b2fb6SRafael Auler Visited[Cur] = S_VISITING; 1006cc4b2fb6SRafael Auler Stack[StackTop++] = Cur; 100716a497c6SRafael Auler assert(StackTop <= NumNodes, "stack grew too large"); 100816a497c6SRafael Auler for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) { 100916a497c6SRafael Auler const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node; 1010cc4b2fb6SRafael Auler Stack[StackTop++] = Succ; 101116a497c6SRafael Auler assert(StackTop <= NumNodes, "stack grew too large"); 1012cc4b2fb6SRafael Auler } 1013cc4b2fb6SRafael Auler continue; 1014cc4b2fb6SRafael Auler } 1015cc4b2fb6SRafael Auler Visited[Cur] = S_VISITED; 1016cc4b2fb6SRafael Auler 1017cc4b2fb6SRafael Auler // Establish our node frequency based on outgoing edges, which should all be 1018cc4b2fb6SRafael Auler // resolved by now. 1019cc4b2fb6SRafael Auler int64_t CurNodeFreq = LeafFrequency[Cur]; 1020cc4b2fb6SRafael Auler // Not a leaf? 1021cc4b2fb6SRafael Auler if (!CurNodeFreq) { 102216a497c6SRafael Auler for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) { 102316a497c6SRafael Auler const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID; 102416a497c6SRafael Auler CurNodeFreq += EdgeFreqs[SuccEdge]; 1025cc4b2fb6SRafael Auler } 1026cc4b2fb6SRafael Auler } 102716a497c6SRafael Auler if (CurNodeFreq < 0) 102816a497c6SRafael Auler CurNodeFreq = 0; 102916a497c6SRafael Auler 103016a497c6SRafael Auler const uint64_t CallFreq = CallMap->visitAllCallsIn( 103116a497c6SRafael Auler Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx); 103216a497c6SRafael Auler 103316a497c6SRafael Auler // Exception handling affected our output flow? Fix with calls info 103416a497c6SRafael Auler DEBUG({ 103516a497c6SRafael Auler if (CallFreq > CurNodeFreq) 103616a497c6SRafael Auler report("Bumping node frequency with call info\n"); 103716a497c6SRafael Auler }); 103816a497c6SRafael Auler CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq; 103916a497c6SRafael Auler 104016a497c6SRafael Auler if (CurNodeFreq > 0) { 104116a497c6SRafael Auler if (uint64_t Addr = EntryAddress[Cur]) { 104216a497c6SRafael Auler DEBUG( 104316a497c6SRafael Auler reportNumber(" Setting flow at entry point address 0x", Addr, 16)); 104416a497c6SRafael Auler DEBUG(reportNumber(" with: ", CurNodeFreq, 10)); 104516a497c6SRafael Auler Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq; 104616a497c6SRafael Auler } 104716a497c6SRafael Auler } 104816a497c6SRafael Auler 104916a497c6SRafael Auler // No parent? Reached a tree root, limit to call frequency updating. 105016a497c6SRafael Auler if (SpanningTreeNodes[Cur].NumInEdges == 0) { 105116a497c6SRafael Auler continue; 105216a497c6SRafael Auler } 105316a497c6SRafael Auler 105416a497c6SRafael Auler assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent"); 105516a497c6SRafael Auler const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node; 105616a497c6SRafael Auler const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID; 105716a497c6SRafael Auler 1058cc4b2fb6SRafael Auler // Calculate parent edge freq. 105916a497c6SRafael Auler int64_t ParentEdgeFreq = CurNodeFreq; 106016a497c6SRafael Auler for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) { 106116a497c6SRafael Auler const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID; 106216a497c6SRafael Auler ParentEdgeFreq -= EdgeFreqs[PredEdge]; 1063cc4b2fb6SRafael Auler } 106416a497c6SRafael Auler 1065cc4b2fb6SRafael Auler // Sometimes the conservative CFG that BOLT builds will lead to incorrect 1066cc4b2fb6SRafael Auler // flow computation. For example, in a BB that transitively calls the exit 1067cc4b2fb6SRafael Auler // syscall, BOLT will add a fall-through successor even though it should not 1068cc4b2fb6SRafael Auler // have any successors. So this block execution will likely be wrong. We 1069cc4b2fb6SRafael Auler // tolerate this imperfection since this case should be quite infrequent. 1070cc4b2fb6SRafael Auler if (ParentEdgeFreq < 0) { 107116a497c6SRafael Auler DEBUG(dumpEdgeFreqs()); 1072cc4b2fb6SRafael Auler DEBUG(report("WARNING: incorrect flow")); 1073cc4b2fb6SRafael Auler ParentEdgeFreq = 0; 1074cc4b2fb6SRafael Auler } 1075cc4b2fb6SRafael Auler DEBUG(reportNumber(" Setting freq for ParentEdge: ", ParentEdge, 10)); 1076cc4b2fb6SRafael Auler DEBUG(reportNumber(" with ParentEdgeFreq: ", ParentEdgeFreq, 10)); 107716a497c6SRafael Auler EdgeFreqs[ParentEdge] = ParentEdgeFreq; 1078cc4b2fb6SRafael Auler } 1079cc4b2fb6SRafael Auler 108016a497c6SRafael Auler Alloc.deallocate(EntryAddress); 1081cc4b2fb6SRafael Auler Alloc.deallocate(LeafFrequency); 1082cc4b2fb6SRafael Auler Alloc.deallocate(Visited); 1083cc4b2fb6SRafael Auler Alloc.deallocate(Stack); 108416a497c6SRafael Auler CallMap->~NodeToCallsMap(); 108516a497c6SRafael Auler Alloc.deallocate(CallMap); 108616a497c6SRafael Auler DEBUG(dumpEdgeFreqs()); 1087cc4b2fb6SRafael Auler } 1088cc4b2fb6SRafael Auler 108916a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses 109016a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for 109116a497c6SRafael Auler /// edges that we do not explictly instrument. 109216a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx, 109316a497c6SRafael Auler const uint8_t *FuncDesc, 109416a497c6SRafael Auler BumpPtrAllocator &Alloc) { 109516a497c6SRafael Auler const FunctionDescription F(FuncDesc); 109616a497c6SRafael Auler const uint8_t *next = FuncDesc + F.getSize(); 1097cc4b2fb6SRafael Auler 1098cc4b2fb6SRafael Auler // Skip funcs we know are cold 1099cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG 110016a497c6SRafael Auler uint64_t CountersFreq = 0; 110116a497c6SRafael Auler for (int I = 0; I < F.NumLeafNodes; ++I) { 110216a497c6SRafael Auler CountersFreq += __bolt_instr_locations[F.LeafNodes[I].Counter]; 1103cc4b2fb6SRafael Auler } 110416a497c6SRafael Auler if (CountersFreq == 0) { 110516a497c6SRafael Auler for (int I = 0; I < F.NumEdges; ++I) { 110616a497c6SRafael Auler const uint32_t C = F.Edges[I].Counter; 110716a497c6SRafael Auler if (C == 0xffffffff) 110816a497c6SRafael Auler continue; 110916a497c6SRafael Auler CountersFreq += __bolt_instr_locations[C]; 111016a497c6SRafael Auler } 111116a497c6SRafael Auler if (CountersFreq == 0) { 111216a497c6SRafael Auler for (int I = 0; I < F.NumCalls; ++I) { 111316a497c6SRafael Auler const uint32_t C = F.Calls[I].Counter; 111416a497c6SRafael Auler if (C == 0xffffffff) 111516a497c6SRafael Auler continue; 111616a497c6SRafael Auler CountersFreq += __bolt_instr_locations[C]; 111716a497c6SRafael Auler } 111816a497c6SRafael Auler if (CountersFreq == 0) 1119cc4b2fb6SRafael Auler return next; 112016a497c6SRafael Auler } 112116a497c6SRafael Auler } 1122cc4b2fb6SRafael Auler #endif 1123cc4b2fb6SRafael Auler 112416a497c6SRafael Auler Graph *G = new (Alloc) Graph(Alloc, F, __bolt_instr_locations, Ctx); 1125cc4b2fb6SRafael Auler DEBUG(G->dump()); 112616a497c6SRafael Auler if (!G->EdgeFreqs && !G->CallFreqs) { 1127cc4b2fb6SRafael Auler G->~Graph(); 1128cc4b2fb6SRafael Auler Alloc.deallocate(G); 1129cc4b2fb6SRafael Auler return next; 1130cc4b2fb6SRafael Auler } 1131cc4b2fb6SRafael Auler 113216a497c6SRafael Auler for (int I = 0; I < F.NumEdges; ++I) { 113316a497c6SRafael Auler const uint64_t Freq = G->EdgeFreqs[I]; 1134cc4b2fb6SRafael Auler if (Freq == 0) 1135cc4b2fb6SRafael Auler continue; 113616a497c6SRafael Auler const EdgeDescription *Desc = &F.Edges[I]; 1137cc4b2fb6SRafael Auler char LineBuf[BufSize]; 1138cc4b2fb6SRafael Auler char *Ptr = LineBuf; 113916a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize); 114016a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf)); 1141cc4b2fb6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22); 1142cc4b2fb6SRafael Auler Ptr = intToStr(Ptr, Freq, 10); 1143cc4b2fb6SRafael Auler *Ptr++ = '\n'; 1144cc4b2fb6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 1145cc4b2fb6SRafael Auler } 1146cc4b2fb6SRafael Auler 114716a497c6SRafael Auler for (int I = 0; I < F.NumCalls; ++I) { 114816a497c6SRafael Auler const uint64_t Freq = G->CallFreqs[I]; 114916a497c6SRafael Auler if (Freq == 0) 115016a497c6SRafael Auler continue; 115116a497c6SRafael Auler char LineBuf[BufSize]; 115216a497c6SRafael Auler char *Ptr = LineBuf; 115316a497c6SRafael Auler const CallDescription *Desc = &F.Calls[I]; 115416a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize); 115516a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf)); 115616a497c6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 115716a497c6SRafael Auler Ptr = intToStr(Ptr, Freq, 10); 115816a497c6SRafael Auler *Ptr++ = '\n'; 115916a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 116016a497c6SRafael Auler } 116116a497c6SRafael Auler 1162cc4b2fb6SRafael Auler G->~Graph(); 1163cc4b2fb6SRafael Auler Alloc.deallocate(G); 1164cc4b2fb6SRafael Auler return next; 1165cc4b2fb6SRafael Auler } 1166cc4b2fb6SRafael Auler 116716a497c6SRafael Auler const IndCallTargetDescription * 116816a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const { 116916a497c6SRafael Auler uint32_t B = 0; 117016a497c6SRafael Auler uint32_t E = __bolt_instr_num_ind_targets; 117116a497c6SRafael Auler if (E == 0) 117216a497c6SRafael Auler return nullptr; 117316a497c6SRafael Auler do { 117416a497c6SRafael Auler uint32_t I = (E - B) / 2 + B; 117516a497c6SRafael Auler if (IndCallTargets[I].Address == Target) 117616a497c6SRafael Auler return &IndCallTargets[I]; 117716a497c6SRafael Auler if (IndCallTargets[I].Address < Target) 117816a497c6SRafael Auler B = I + 1; 117916a497c6SRafael Auler else 118016a497c6SRafael Auler E = I; 118116a497c6SRafael Auler } while (B < E); 118216a497c6SRafael Auler return nullptr; 1183cc4b2fb6SRafael Auler } 118462aa74f8SRafael Auler 118516a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file 118616a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry, 118716a497c6SRafael Auler int FD, int CallsiteID, 118816a497c6SRafael Auler ProfileWriterContext *Ctx) { 118916a497c6SRafael Auler if (Entry.Val == 0) 119016a497c6SRafael Auler return; 119116a497c6SRafael Auler DEBUG(reportNumber("Target func 0x", Entry.Key, 16)); 119216a497c6SRafael Auler DEBUG(reportNumber("Target freq: ", Entry.Val, 10)); 119316a497c6SRafael Auler const IndCallDescription *CallsiteDesc = 119416a497c6SRafael Auler &Ctx->IndCallDescriptions[CallsiteID]; 119516a497c6SRafael Auler const IndCallTargetDescription *TargetDesc = 119616a497c6SRafael Auler Ctx->lookupIndCallTarget(Entry.Key); 119716a497c6SRafael Auler if (!TargetDesc) { 119816a497c6SRafael Auler DEBUG(report("Failed to lookup indirect call target\n")); 1199cc4b2fb6SRafael Auler char LineBuf[BufSize]; 120062aa74f8SRafael Auler char *Ptr = LineBuf; 120116a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize); 120216a497c6SRafael Auler Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40); 120316a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val, 10); 120416a497c6SRafael Auler *Ptr++ = '\n'; 120516a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 120616a497c6SRafael Auler return; 120716a497c6SRafael Auler } 120816a497c6SRafael Auler Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val; 120916a497c6SRafael Auler char LineBuf[BufSize]; 121016a497c6SRafael Auler char *Ptr = LineBuf; 121116a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize); 121216a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf)); 1213cc4b2fb6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 121416a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val, 10); 121562aa74f8SRafael Auler *Ptr++ = '\n'; 1216821480d2SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 121762aa74f8SRafael Auler } 1218cc4b2fb6SRafael Auler 121916a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles. 122016a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) { 122116a497c6SRafael Auler for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) { 122216a497c6SRafael Auler DEBUG(reportNumber("IndCallsite #", I, 10)); 122316a497c6SRafael Auler GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx); 122416a497c6SRafael Auler } 122516a497c6SRafael Auler } 122616a497c6SRafael Auler 122716a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are 122816a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source 122916a497c6SRafael Auler /// [unknown] in the profile. 123016a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD, 123116a497c6SRafael Auler ProfileWriterContext *Ctx) { 123216a497c6SRafael Auler DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16)); 123316a497c6SRafael Auler DEBUG(reportNumber("Calls: ", Entry.Calls, 10)); 123416a497c6SRafael Auler DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10)); 123516a497c6SRafael Auler DEBUG({ 123616a497c6SRafael Auler if (Entry.Calls > Entry.Val) 123716a497c6SRafael Auler report(" More calls than expected!\n"); 123816a497c6SRafael Auler }); 123916a497c6SRafael Auler if (Entry.Val <= Entry.Calls) 124016a497c6SRafael Auler return; 124116a497c6SRafael Auler DEBUG(reportNumber( 124216a497c6SRafael Auler " Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10)); 124316a497c6SRafael Auler const IndCallTargetDescription *TargetDesc = 124416a497c6SRafael Auler Ctx->lookupIndCallTarget(Entry.Key); 124516a497c6SRafael Auler if (!TargetDesc) { 124616a497c6SRafael Auler // There is probably something wrong with this callee and this should be 124716a497c6SRafael Auler // investigated, but I don't want to assert and lose all data collected. 124816a497c6SRafael Auler DEBUG(report("WARNING: failed to look up call target!\n")); 124916a497c6SRafael Auler return; 125016a497c6SRafael Auler } 125116a497c6SRafael Auler char LineBuf[BufSize]; 125216a497c6SRafael Auler char *Ptr = LineBuf; 125316a497c6SRafael Auler Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize); 125416a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf)); 125516a497c6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 125616a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10); 125716a497c6SRafael Auler *Ptr++ = '\n'; 125816a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 125916a497c6SRafael Auler } 126016a497c6SRafael Auler 126116a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting 126216a497c6SRafael Auler /// program upon failure. 126316a497c6SRafael Auler int openProfile() { 126416a497c6SRafael Auler // Build the profile name string by appending our PID 126516a497c6SRafael Auler char Buf[BufSize]; 126616a497c6SRafael Auler char *Ptr = Buf; 126716a497c6SRafael Auler uint64_t PID = __getpid(); 126816a497c6SRafael Auler Ptr = strCopy(Buf, __bolt_instr_filename, BufSize); 126916a497c6SRafael Auler if (__bolt_instr_use_pid) { 127016a497c6SRafael Auler Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1)); 127116a497c6SRafael Auler Ptr = intToStr(Ptr, PID, 10); 127216a497c6SRafael Auler Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1)); 127316a497c6SRafael Auler } 127416a497c6SRafael Auler *Ptr++ = '\0'; 127516a497c6SRafael Auler uint64_t FD = __open(Buf, 127616a497c6SRafael Auler /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/, 127716a497c6SRafael Auler /*mode=*/0666); 127816a497c6SRafael Auler if (static_cast<int64_t>(FD) < 0) { 127916a497c6SRafael Auler report("Error while trying to open profile file for writing: "); 128016a497c6SRafael Auler report(Buf); 128116a497c6SRafael Auler reportNumber("\nFailed with error number: 0x", 128216a497c6SRafael Auler 0 - static_cast<int64_t>(FD), 16); 128316a497c6SRafael Auler __exit(1); 128416a497c6SRafael Auler } 128516a497c6SRafael Auler return FD; 128616a497c6SRafael Auler } 128716a497c6SRafael Auler } // anonymous namespace 128816a497c6SRafael Auler 128916a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your 129016a497c6SRafael Auler /// program independently of prior phases. 129116a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by 129216a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb: 129316a497c6SRafael Auler /// 129416a497c6SRafael Auler /// gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \ 129516a497c6SRafael Auler /// -ex 'set confirm off' -ex quit 129616a497c6SRafael Auler /// 129716a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file 129816a497c6SRafael Auler /// name. 129916a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() { 130016a497c6SRafael Auler memSet(reinterpret_cast<char *>(__bolt_instr_locations), 0, 130116a497c6SRafael Auler __bolt_num_counters * 8); 130216a497c6SRafael Auler for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) { 130316a497c6SRafael Auler GlobalIndCallCounters[I].resetCounters(); 130416a497c6SRafael Auler } 130516a497c6SRafael Auler } 130616a497c6SRafael Auler 130716a497c6SRafael Auler /// This is the entry point for profile writing. 130816a497c6SRafael Auler /// There are three ways of getting here: 130916a497c6SRafael Auler /// 131016a497c6SRafael Auler /// * Program execution ended, finalization methods are running and BOLT 131116a497c6SRafael Auler /// hooked into FINI from your binary dynamic section; 131216a497c6SRafael Auler /// * You used the sleep timer option and during initialization we forked 131316a497c6SRafael Auler /// a separete process that will call this function periodically; 131416a497c6SRafael Auler /// * BOLT prints this function address so you can attach a debugger and 131516a497c6SRafael Auler /// call this function directly to get your profile written to disk 131616a497c6SRafael Auler /// on demand. 131716a497c6SRafael Auler /// 131816a497c6SRafael Auler extern "C" void __bolt_instr_data_dump() { 131916a497c6SRafael Auler // Already dumping 132016a497c6SRafael Auler if (!GlobalWriteProfileMutex->acquire()) 132116a497c6SRafael Auler return; 132216a497c6SRafael Auler 132316a497c6SRafael Auler BumpPtrAllocator HashAlloc; 132416a497c6SRafael Auler HashAlloc.setMaxSize(0x6400000); 132516a497c6SRafael Auler ProfileWriterContext Ctx = readDescriptions(); 132616a497c6SRafael Auler Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc); 132716a497c6SRafael Auler 132816a497c6SRafael Auler DEBUG(printStats(Ctx)); 132916a497c6SRafael Auler 133016a497c6SRafael Auler int FD = openProfile(); 133116a497c6SRafael Auler 1332cc4b2fb6SRafael Auler BumpPtrAllocator Alloc; 133316a497c6SRafael Auler const uint8_t *FuncDesc = Ctx.FuncDescriptions; 1334cc4b2fb6SRafael Auler for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) { 133516a497c6SRafael Auler FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc); 133616a497c6SRafael Auler Alloc.clear(); 1337cc4b2fb6SRafael Auler DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16)); 1338cc4b2fb6SRafael Auler } 133916a497c6SRafael Auler assert(FuncDesc == (void *)Ctx.Strings, 1340cc4b2fb6SRafael Auler "FuncDesc ptr must be equal to stringtable"); 1341cc4b2fb6SRafael Auler 134216a497c6SRafael Auler writeIndirectCallProfile(FD, Ctx); 134316a497c6SRafael Auler Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx); 134416a497c6SRafael Auler 1345821480d2SRafael Auler __close(FD); 134616a497c6SRafael Auler __munmap(Ctx.MMapPtr, Ctx.MMapSize); 134716a497c6SRafael Auler __close(Ctx.FileDesc); 134816a497c6SRafael Auler HashAlloc.destroy(); 134916a497c6SRafael Auler GlobalWriteProfileMutex->release(); 135016a497c6SRafael Auler DEBUG(report("Finished writing profile.\n")); 135116a497c6SRafael Auler } 135216a497c6SRafael Auler 135316a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data 135416a497c6SRafael Auler /// at user-specified intervals 135516a497c6SRafael Auler void watchProcess() { 135616a497c6SRafael Auler timespec ts, rem; 135716a497c6SRafael Auler uint64_t Ellapsed = 0ull; 135816a497c6SRafael Auler ts.tv_sec = 1; 135916a497c6SRafael Auler ts.tv_nsec = 0; 136016a497c6SRafael Auler while (1) { 136116a497c6SRafael Auler __nanosleep(&ts, &rem); 136216a497c6SRafael Auler // This means our parent process died, so no need for us to keep dumping. 136316a497c6SRafael Auler // Notice that make and some systems will wait until all child processes 136416a497c6SRafael Auler // of a command finishes before proceeding, so it is important to exit as 136516a497c6SRafael Auler // early as possible once our parent dies. 136616a497c6SRafael Auler if (__getppid() == 1) { 136716a497c6SRafael Auler break; 136816a497c6SRafael Auler } 136916a497c6SRafael Auler if (++Ellapsed < __bolt_instr_sleep_time) 137016a497c6SRafael Auler continue; 137116a497c6SRafael Auler Ellapsed = 0; 137216a497c6SRafael Auler __bolt_instr_data_dump(); 137316a497c6SRafael Auler __bolt_instr_clear_counters(); 137416a497c6SRafael Auler } 137516a497c6SRafael Auler DEBUG(report("My parent process is dead, bye!\n")); 137616a497c6SRafael Auler __exit(0); 137716a497c6SRafael Auler } 137816a497c6SRafael Auler 137916a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call(); 138016a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall(); 138116a497c6SRafael Auler 138216a497c6SRafael Auler /// Initialization code 138316a497c6SRafael Auler extern "C" void __bolt_instr_setup() { 138416a497c6SRafael Auler const uint64_t CountersStart = 138516a497c6SRafael Auler reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]); 138616a497c6SRafael Auler const uint64_t CountersEnd = alignTo( 138716a497c6SRafael Auler reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]), 138816a497c6SRafael Auler 0x1000); 138916a497c6SRafael Auler DEBUG(reportNumber("replace mmap start: ", CountersStart, 16)); 139016a497c6SRafael Auler DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16)); 139116a497c6SRafael Auler assert (CountersEnd > CountersStart, "no counters"); 139216a497c6SRafael Auler // Maps our counters to be shared instead of private, so we keep counting for 139316a497c6SRafael Auler // forked processes 139416a497c6SRafael Auler __mmap(CountersStart, CountersEnd - CountersStart, 139516a497c6SRafael Auler 0x3 /*PROT_READ|PROT_WRITE*/, 139616a497c6SRafael Auler 0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0); 139716a497c6SRafael Auler 139816a497c6SRafael Auler __bolt_trampoline_ind_call = __bolt_instr_indirect_call; 139916a497c6SRafael Auler __bolt_trampoline_ind_tailcall = __bolt_instr_indirect_tailcall; 140016a497c6SRafael Auler // Conservatively reserve 100MiB shared pages 140116a497c6SRafael Auler GlobalAlloc.setMaxSize(0x6400000); 140216a497c6SRafael Auler GlobalAlloc.setShared(true); 140316a497c6SRafael Auler GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex(); 140416a497c6SRafael Auler if (__bolt_instr_num_ind_calls > 0) 140516a497c6SRafael Auler GlobalIndCallCounters = 140616a497c6SRafael Auler new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls]; 140716a497c6SRafael Auler 140816a497c6SRafael Auler if (__bolt_instr_sleep_time != 0) { 140916a497c6SRafael Auler if (auto PID = __fork()) 141016a497c6SRafael Auler return; 141116a497c6SRafael Auler watchProcess(); 141216a497c6SRafael Auler } 141316a497c6SRafael Auler } 141416a497c6SRafael Auler 141516a497c6SRafael Auler extern "C" void instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) { 141616a497c6SRafael Auler GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc); 141716a497c6SRafael Auler } 141816a497c6SRafael Auler 141916a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site 142016a497c6SRafael Auler /// as well as the target address for the call 142116a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call() 142216a497c6SRafael Auler { 142316a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 1424c6799a68SRafael Auler "mov 0x90(%%rsp), %%rdi\n" 1425c6799a68SRafael Auler "mov 0x88(%%rsp), %%rsi\n" 142616a497c6SRafael Auler "call instrumentIndirectCall\n" 142716a497c6SRafael Auler RESTORE_ALL 142816a497c6SRafael Auler "pop %%rdi\n" 142916a497c6SRafael Auler "add $16, %%rsp\n" 143016a497c6SRafael Auler "xchg (%%rsp), %%rdi\n" 143116a497c6SRafael Auler "jmp *-8(%%rsp)\n" 143216a497c6SRafael Auler :::); 143316a497c6SRafael Auler } 143416a497c6SRafael Auler 143516a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall() 143616a497c6SRafael Auler { 143716a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 1438c6799a68SRafael Auler "mov 0x88(%%rsp), %%rdi\n" 1439c6799a68SRafael Auler "mov 0x80(%%rsp), %%rsi\n" 144016a497c6SRafael Auler "call instrumentIndirectCall\n" 144116a497c6SRafael Auler RESTORE_ALL 144216a497c6SRafael Auler "add $16, %%rsp\n" 144316a497c6SRafael Auler "pop %%rdi\n" 144416a497c6SRafael Auler "jmp *-16(%%rsp)\n" 144516a497c6SRafael Auler :::); 144616a497c6SRafael Auler } 144716a497c6SRafael Auler 144816a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state. 144916a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start() 145016a497c6SRafael Auler { 145116a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 145216a497c6SRafael Auler "call __bolt_instr_setup\n" 145316a497c6SRafael Auler RESTORE_ALL 14548c7f524aSAlexander Shaposhnikov "jmp *__bolt_instr_init_ptr(%%rip)\n" 145516a497c6SRafael Auler :::); 145616a497c6SRafael Auler } 145716a497c6SRafael Auler 145816a497c6SRafael Auler /// This is hooking into ELF's DT_FINI 145916a497c6SRafael Auler extern "C" void __bolt_instr_fini() { 146016a497c6SRafael Auler __bolt_instr_fini_ptr(); 146116a497c6SRafael Auler if (__bolt_instr_sleep_time == 0) 146216a497c6SRafael Auler __bolt_instr_data_dump(); 146316a497c6SRafael Auler DEBUG(report("Finished.\n")); 146462aa74f8SRafael Auler } 1465bbd9d610SAlexander Shaposhnikov 1466bbd9d610SAlexander Shaposhnikov #else 1467bbd9d610SAlexander Shaposhnikov 1468bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains 1469bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup. 1470*1cf23e5eSAlexander Shaposhnikov extern "C" __attribute((section("__TEXT,__setup"))) void _bolt_instr_setup() { 1471*1cf23e5eSAlexander Shaposhnikov const char* Message = "Hello!\n"; 1472*1cf23e5eSAlexander Shaposhnikov __write(2, Message, 7); 1473*1cf23e5eSAlexander Shaposhnikov } 1474bbd9d610SAlexander Shaposhnikov 1475bbd9d610SAlexander Shaposhnikov #endif 1476