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 6016a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when 6116a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct 6216a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters 6316a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be 6416a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG. 6562aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[]; 6616a497c6SRafael Auler extern uint32_t __bolt_num_counters; 6716a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT, 6816a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a 6916a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs, 7016a497c6SRafael Auler // Location, IntrumentedNode and EntryNode. 7116a497c6SRafael Auler // Number of indirect call site descriptions 7216a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls; 7316a497c6SRafael Auler // Number of indirect call target descriptions 7416a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets; 75cc4b2fb6SRafael Auler // Number of function descriptions 76cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs; 7716a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk) 7816a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time; 79cc4b2fb6SRafael Auler // Filename to dump data to 8062aa74f8SRafael Auler extern char __bolt_instr_filename[]; 8116a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so 8216a497c6SRafael Auler // different invocations of the same program can be differentiated. 8316a497c6SRafael Auler extern bool __bolt_instr_use_pid; 8416a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass 8516a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these 8616a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to 8716a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We 8816a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT, 8916a497c6SRafael Auler // *not* the other way around. 9016a497c6SRafael Auler // TODO: We need better linking support to make that happen. 9116a497c6SRafael Auler extern void (*__bolt_trampoline_ind_call)(); 9216a497c6SRafael Auler extern void (*__bolt_trampoline_ind_tailcall)(); 9316a497c6SRafael Auler // Function pointers to init/fini routines in the binary, so we can resume 9416a497c6SRafael Auler // regular execution of these functions that we hooked 9516a497c6SRafael Auler extern void (*__bolt_instr_init_ptr)(); 9616a497c6SRafael Auler extern void (*__bolt_instr_fini_ptr)(); 9762aa74f8SRafael Auler 98cc4b2fb6SRafael Auler namespace { 99cc4b2fb6SRafael Auler 100cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space 101cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that 10216a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements. 10316a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we 10416a497c6SRafael Auler /// are done processing something. 105cc4b2fb6SRafael Auler class BumpPtrAllocator { 10616a497c6SRafael Auler /// This is written before each allocation and act as a canary to detect when 10716a497c6SRafael Auler /// a bug caused our program to cross allocation boundaries. 108cc4b2fb6SRafael Auler struct EntryMetadata { 109cc4b2fb6SRafael Auler uint64_t Magic; 110cc4b2fb6SRafael Auler uint64_t AllocSize; 111cc4b2fb6SRafael Auler }; 1129bd71615SXun Li 113cc4b2fb6SRafael Auler public: 114cc4b2fb6SRafael Auler void *allocate(uintptr_t Size) { 11516a497c6SRafael Auler Lock L(M); 116cc4b2fb6SRafael Auler if (StackBase == nullptr) { 11716a497c6SRafael Auler StackBase = reinterpret_cast<uint8_t *>( 11816a497c6SRafael Auler __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/, 11916a497c6SRafael Auler Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/ 12016a497c6SRafael Auler : 0x22 /* MAP_PRIVATE | MAP_ANONYMOUS*/, 12116a497c6SRafael Auler -1, 0)); 122cc4b2fb6SRafael Auler StackSize = 0; 123cc4b2fb6SRafael Auler } 124cc4b2fb6SRafael Auler Size = alignTo(Size + sizeof(EntryMetadata), 16); 125cc4b2fb6SRafael Auler uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata); 126cc4b2fb6SRafael Auler auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize); 12716a497c6SRafael Auler M->Magic = Magic; 128cc4b2fb6SRafael Auler M->AllocSize = Size; 129cc4b2fb6SRafael Auler StackSize += Size; 13016a497c6SRafael Auler assert(StackSize < MaxSize, "allocator ran out of memory"); 131cc4b2fb6SRafael Auler return AllocAddress; 132cc4b2fb6SRafael Auler } 133cc4b2fb6SRafael Auler 13416a497c6SRafael Auler #ifdef DEBUG 13516a497c6SRafael Auler /// Element-wise deallocation is only used for debugging to catch memory 13616a497c6SRafael Auler /// bugs by checking magic bytes. Ordinarily, we reset the allocator once 13716a497c6SRafael Auler /// we are done with it. Reset is done with clear(). There's no need 13816a497c6SRafael Auler /// to deallocate each element individually. 139cc4b2fb6SRafael Auler void deallocate(void *Ptr) { 14016a497c6SRafael Auler Lock L(M); 141cc4b2fb6SRafael Auler uint8_t MetadataOffset = sizeof(EntryMetadata); 142cc4b2fb6SRafael Auler auto *M = reinterpret_cast<EntryMetadata *>( 143cc4b2fb6SRafael Auler reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset); 144cc4b2fb6SRafael Auler const uint8_t *StackTop = StackBase + StackSize + MetadataOffset; 145cc4b2fb6SRafael Auler // Validate size 146cc4b2fb6SRafael Auler if (Ptr != StackTop - M->AllocSize) { 14716a497c6SRafael Auler // Failed validation, check if it is a pointer returned by operator new [] 148cc4b2fb6SRafael Auler MetadataOffset += 149cc4b2fb6SRafael Auler sizeof(uint64_t); // Space for number of elements alloc'ed 150cc4b2fb6SRafael Auler M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) - 151cc4b2fb6SRafael Auler MetadataOffset); 15216a497c6SRafael Auler // Ok, it failed both checks if this assertion fails. Stop the program, we 15316a497c6SRafael Auler // have a memory bug. 154cc4b2fb6SRafael Auler assert(Ptr == StackTop - M->AllocSize, 155cc4b2fb6SRafael Auler "must deallocate the last element alloc'ed"); 156cc4b2fb6SRafael Auler } 15716a497c6SRafael Auler assert(M->Magic == Magic, "allocator magic is corrupt"); 158cc4b2fb6SRafael Auler StackSize -= M->AllocSize; 159cc4b2fb6SRafael Auler } 16016a497c6SRafael Auler #else 16116a497c6SRafael Auler void deallocate(void *) {} 16216a497c6SRafael Auler #endif 16316a497c6SRafael Auler 16416a497c6SRafael Auler void clear() { 16516a497c6SRafael Auler Lock L(M); 16616a497c6SRafael Auler StackSize = 0; 16716a497c6SRafael Auler } 16816a497c6SRafael Auler 16916a497c6SRafael Auler /// Set mmap reservation size (only relevant before first allocation) 1709bd71615SXun Li void setMaxSize(uint64_t Size) { MaxSize = Size; } 17116a497c6SRafael Auler 17216a497c6SRafael Auler /// Set mmap reservation privacy (only relevant before first allocation) 1739bd71615SXun Li void setShared(bool S) { Shared = S; } 17416a497c6SRafael Auler 17516a497c6SRafael Auler void destroy() { 17616a497c6SRafael Auler if (StackBase == nullptr) 17716a497c6SRafael Auler return; 17816a497c6SRafael Auler __munmap(StackBase, MaxSize); 17916a497c6SRafael Auler } 180cc4b2fb6SRafael Auler 181cc4b2fb6SRafael Auler private: 18216a497c6SRafael Auler static constexpr uint64_t Magic = 0x1122334455667788ull; 18316a497c6SRafael Auler uint64_t MaxSize = 0xa00000; 184cc4b2fb6SRafael Auler uint8_t *StackBase{nullptr}; 185cc4b2fb6SRafael Auler uint64_t StackSize{0}; 18616a497c6SRafael Auler bool Shared{false}; 18716a497c6SRafael Auler Mutex M; 188cc4b2fb6SRafael Auler }; 189cc4b2fb6SRafael Auler 19016a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by 19116a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine. 19216a497c6SRafael Auler BumpPtrAllocator GlobalAlloc; 193cc4b2fb6SRafael Auler } // anonymous namespace 194cc4b2fb6SRafael Auler 195cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to 196cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the 197cc4b2fb6SRafael Auler // stack instead of in a data section (global). 1989bd71615SXun Li void *operator new(uintptr_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); } 199cc4b2fb6SRafael Auler void *operator new(uintptr_t Sz, BumpPtrAllocator &A, char C) { 200cc4b2fb6SRafael Auler auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz)); 201cc4b2fb6SRafael Auler memSet(Ptr, C, Sz); 202cc4b2fb6SRafael Auler return Ptr; 203cc4b2fb6SRafael Auler } 204cc4b2fb6SRafael Auler void *operator new[](uintptr_t Sz, BumpPtrAllocator &A) { 205cc4b2fb6SRafael Auler return A.allocate(Sz); 206cc4b2fb6SRafael Auler } 207cc4b2fb6SRafael Auler void *operator new[](uintptr_t Sz, BumpPtrAllocator &A, char C) { 208cc4b2fb6SRafael Auler auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz)); 209cc4b2fb6SRafael Auler memSet(Ptr, C, Sz); 210cc4b2fb6SRafael Auler return Ptr; 211cc4b2fb6SRafael Auler } 212cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc. 213cc4b2fb6SRafael Auler // C++ language weirdness 2149bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); } 215cc4b2fb6SRafael Auler 216cc4b2fb6SRafael Auler namespace { 217cc4b2fb6SRafael Auler 21816a497c6SRafael Auler /// Basic key-val atom stored in our hash 21916a497c6SRafael Auler struct SimpleHashTableEntryBase { 22016a497c6SRafael Auler uint64_t Key; 22116a497c6SRafael Auler uint64_t Val; 22216a497c6SRafael Auler }; 22316a497c6SRafael Auler 22416a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size 22516a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves 22616a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our 22716a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers. 22816a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime). 22916a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO) 23016a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it 23116a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for 23216a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a 23316a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites) 23416a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7, 23516a497c6SRafael Auler uint32_t IncSize = 7> 23616a497c6SRafael Auler class SimpleHashTable { 23716a497c6SRafael Auler public: 23816a497c6SRafael Auler using MapEntry = T; 23916a497c6SRafael Auler 24016a497c6SRafael Auler /// Increment by 1 the value of \p Key. If it is not in this table, it will be 24116a497c6SRafael Auler /// added to the table and its value set to 1. 24216a497c6SRafael Auler void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) { 24316a497c6SRafael Auler ++get(Key, Alloc).Val; 24416a497c6SRafael Auler } 24516a497c6SRafael Auler 24616a497c6SRafael Auler /// Basic member accessing interface. Here we pass the allocator explicitly to 24716a497c6SRafael Auler /// avoid storing a pointer to it as part of this table (remember there is one 24816a497c6SRafael Auler /// hash for each indirect call site, so we wan't to minimize our footprint). 24916a497c6SRafael Auler MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) { 25016a497c6SRafael Auler Lock L(M); 25116a497c6SRafael Auler if (TableRoot) 25216a497c6SRafael Auler return getEntry(TableRoot, Key, Key, Alloc, 0); 25316a497c6SRafael Auler return firstAllocation(Key, Alloc); 25416a497c6SRafael Auler } 25516a497c6SRafael Auler 25616a497c6SRafael Auler /// Traverses all elements in the table 25716a497c6SRafael Auler template <typename... Args> 25816a497c6SRafael Auler void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) { 25916a497c6SRafael Auler if (!TableRoot) 26016a497c6SRafael Auler return; 26116a497c6SRafael Auler return forEachElement(Callback, InitialSize, TableRoot, args...); 26216a497c6SRafael Auler } 26316a497c6SRafael Auler 26416a497c6SRafael Auler void resetCounters(); 26516a497c6SRafael Auler 26616a497c6SRafael Auler private: 26716a497c6SRafael Auler constexpr static uint64_t VacantMarker = 0; 26816a497c6SRafael Auler constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull; 26916a497c6SRafael Auler 27016a497c6SRafael Auler MapEntry *TableRoot{nullptr}; 27116a497c6SRafael Auler Mutex M; 27216a497c6SRafael Auler 27316a497c6SRafael Auler template <typename... Args> 27416a497c6SRafael Auler void forEachElement(void (*Callback)(MapEntry &, Args...), 27516a497c6SRafael Auler uint32_t NumEntries, MapEntry *Entries, Args... args) { 27616a497c6SRafael Auler for (int I = 0; I < NumEntries; ++I) { 27716a497c6SRafael Auler auto &Entry = Entries[I]; 27816a497c6SRafael Auler if (Entry.Key == VacantMarker) 27916a497c6SRafael Auler continue; 28016a497c6SRafael Auler if (Entry.Key & FollowUpTableMarker) { 28116a497c6SRafael Auler forEachElement(Callback, IncSize, 28216a497c6SRafael Auler reinterpret_cast<MapEntry *>(Entry.Key & 28316a497c6SRafael Auler ~FollowUpTableMarker), 28416a497c6SRafael Auler args...); 28516a497c6SRafael Auler continue; 28616a497c6SRafael Auler } 28716a497c6SRafael Auler Callback(Entry, args...); 28816a497c6SRafael Auler } 28916a497c6SRafael Auler } 29016a497c6SRafael Auler 29116a497c6SRafael Auler MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) { 29216a497c6SRafael Auler TableRoot = new (Alloc, 0) MapEntry[InitialSize]; 29316a497c6SRafael Auler auto &Entry = TableRoot[Key % InitialSize]; 29416a497c6SRafael Auler Entry.Key = Key; 29516a497c6SRafael Auler return Entry; 29616a497c6SRafael Auler } 29716a497c6SRafael Auler 29816a497c6SRafael Auler MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector, 29916a497c6SRafael Auler BumpPtrAllocator &Alloc, int CurLevel) { 30016a497c6SRafael Auler const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize; 30116a497c6SRafael Auler uint64_t Remainder = Selector / NumEntries; 30216a497c6SRafael Auler Selector = Selector % NumEntries; 30316a497c6SRafael Auler auto &Entry = Entries[Selector]; 30416a497c6SRafael Auler 30516a497c6SRafael Auler // A hit 30616a497c6SRafael Auler if (Entry.Key == Key) { 30716a497c6SRafael Auler return Entry; 30816a497c6SRafael Auler } 30916a497c6SRafael Auler 31016a497c6SRafael Auler // Vacant - add new entry 31116a497c6SRafael Auler if (Entry.Key == VacantMarker) { 31216a497c6SRafael Auler Entry.Key = Key; 31316a497c6SRafael Auler return Entry; 31416a497c6SRafael Auler } 31516a497c6SRafael Auler 31616a497c6SRafael Auler // Defer to the next level 31716a497c6SRafael Auler if (Entry.Key & FollowUpTableMarker) { 31816a497c6SRafael Auler return getEntry( 31916a497c6SRafael Auler reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker), 32016a497c6SRafael Auler Key, Remainder, Alloc, CurLevel + 1); 32116a497c6SRafael Auler } 32216a497c6SRafael Auler 32316a497c6SRafael Auler // Conflict - create the next level 32416a497c6SRafael Auler MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize]; 32516a497c6SRafael Auler uint64_t CurEntrySelector = Entry.Key / InitialSize; 32616a497c6SRafael Auler for (int I = 0; I < CurLevel; ++I) 32716a497c6SRafael Auler CurEntrySelector /= IncSize; 32816a497c6SRafael Auler CurEntrySelector = CurEntrySelector % IncSize; 32916a497c6SRafael Auler NextLevelTbl[CurEntrySelector] = Entry; 33016a497c6SRafael Auler Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker; 33116a497c6SRafael Auler return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1); 33216a497c6SRafael Auler } 33316a497c6SRafael Auler }; 33416a497c6SRafael Auler 33516a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) { 33616a497c6SRafael Auler Entry.Val = 0; 33716a497c6SRafael Auler } 33816a497c6SRafael Auler 33916a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y> 34016a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() { 34116a497c6SRafael Auler Lock L(M); 34216a497c6SRafael Auler forEachElement(resetIndCallCounter); 34316a497c6SRafael Auler } 34416a497c6SRafael Auler 34516a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter. 34616a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>; 34716a497c6SRafael Auler 34816a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the 34916a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening 35016a497c6SRafael Auler /// during runtime, one table per call site. 35116a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{ 35216a497c6SRafael Auler reinterpret_cast<IndirectCallHashTable *>(1)}; 35316a497c6SRafael Auler 35416a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes 35516a497c6SRafael Auler /// it 35616a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)}; 35716a497c6SRafael Auler 35816a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency 35916a497c6SRafael Auler /// as perceived by the basic block counter (Val). 36016a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase { 36116a497c6SRafael Auler uint64_t Calls; 36216a497c6SRafael Auler }; 36316a497c6SRafael Auler 36416a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>; 36516a497c6SRafael Auler 36616a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and 36716a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for 36816a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the 36916a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two 37016a497c6SRafael Auler /// possible scenarios here: 37116a497c6SRafael Auler /// 37216a497c6SRafael Auler /// * Entry BB has higher frequency than all known calls to this function. 37316a497c6SRafael Auler /// In this case, we have dynamic library code or any uninstrumented code 37416a497c6SRafael Auler /// calling this function. We will write the profile for these untracked 37516a497c6SRafael Auler /// calls as having source "0 [unknown] 0" in the fdata file. 37616a497c6SRafael Auler /// 37716a497c6SRafael Auler /// * Number of known calls is higher than the frequency of entry BB 37816a497c6SRafael Auler /// This only happens when there is no counter for the entry BB / callee 37916a497c6SRafael Auler /// function is not simple (in BOLT terms). We don't do anything special 38016a497c6SRafael Auler /// here and just ignore those (we still report all calls to the non-simple 38116a497c6SRafael Auler /// function, though). 38216a497c6SRafael Auler /// 38316a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase { 38416a497c6SRafael Auler public: 38516a497c6SRafael Auler CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {} 38616a497c6SRafael Auler 38716a497c6SRafael Auler MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); } 38816a497c6SRafael Auler 38916a497c6SRafael Auler private: 39016a497c6SRafael Auler // Different than the hash table for indirect call targets, we do store the 39116a497c6SRafael Auler // allocator here since there is only one call flow hash and space overhead 39216a497c6SRafael Auler // is negligible. 39316a497c6SRafael Auler BumpPtrAllocator &Alloc; 39416a497c6SRafael Auler }; 39516a497c6SRafael Auler 39616a497c6SRafael Auler /// 39716a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to 39816a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote() 39916a497c6SRafael Auler /// 40016a497c6SRafael Auler struct Location { 40116a497c6SRafael Auler uint32_t FunctionName; 40216a497c6SRafael Auler uint32_t Offset; 40316a497c6SRafael Auler }; 40416a497c6SRafael Auler 40516a497c6SRafael Auler struct CallDescription { 40616a497c6SRafael Auler Location From; 40716a497c6SRafael Auler uint32_t FromNode; 40816a497c6SRafael Auler Location To; 40916a497c6SRafael Auler uint32_t Counter; 41016a497c6SRafael Auler uint64_t TargetAddress; 41116a497c6SRafael Auler }; 41216a497c6SRafael Auler 41316a497c6SRafael Auler using IndCallDescription = Location; 41416a497c6SRafael Auler 41516a497c6SRafael Auler struct IndCallTargetDescription { 41616a497c6SRafael Auler Location Loc; 41716a497c6SRafael Auler uint64_t Address; 41816a497c6SRafael Auler }; 41916a497c6SRafael Auler 42016a497c6SRafael Auler struct EdgeDescription { 42116a497c6SRafael Auler Location From; 42216a497c6SRafael Auler uint32_t FromNode; 42316a497c6SRafael Auler Location To; 42416a497c6SRafael Auler uint32_t ToNode; 42516a497c6SRafael Auler uint32_t Counter; 42616a497c6SRafael Auler }; 42716a497c6SRafael Auler 42816a497c6SRafael Auler struct InstrumentedNode { 42916a497c6SRafael Auler uint32_t Node; 43016a497c6SRafael Auler uint32_t Counter; 43116a497c6SRafael Auler }; 43216a497c6SRafael Auler 43316a497c6SRafael Auler struct EntryNode { 43416a497c6SRafael Auler uint64_t Node; 43516a497c6SRafael Auler uint64_t Address; 43616a497c6SRafael Auler }; 43716a497c6SRafael Auler 43816a497c6SRafael Auler struct FunctionDescription { 43916a497c6SRafael Auler uint32_t NumLeafNodes; 44016a497c6SRafael Auler const InstrumentedNode *LeafNodes; 44116a497c6SRafael Auler uint32_t NumEdges; 44216a497c6SRafael Auler const EdgeDescription *Edges; 44316a497c6SRafael Auler uint32_t NumCalls; 44416a497c6SRafael Auler const CallDescription *Calls; 44516a497c6SRafael Auler uint32_t NumEntryNodes; 44616a497c6SRafael Auler const EntryNode *EntryNodes; 44716a497c6SRafael Auler 44816a497c6SRafael Auler /// Constructor will parse the serialized function metadata written by BOLT 44916a497c6SRafael Auler FunctionDescription(const uint8_t *FuncDesc); 45016a497c6SRafael Auler 45116a497c6SRafael Auler uint64_t getSize() const { 45216a497c6SRafael Auler return 16 + NumLeafNodes * sizeof(InstrumentedNode) + 45316a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + 45416a497c6SRafael Auler NumCalls * sizeof(CallDescription) + 45516a497c6SRafael Auler NumEntryNodes * sizeof(EntryNode); 45616a497c6SRafael Auler } 45716a497c6SRafael Auler }; 45816a497c6SRafael Auler 45916a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk 46016a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the 46116a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization 46216a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements. 46316a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs. 46416a497c6SRafael Auler struct ProfileWriterContext { 46516a497c6SRafael Auler IndCallDescription *IndCallDescriptions; 46616a497c6SRafael Auler IndCallTargetDescription *IndCallTargets; 46716a497c6SRafael Auler uint8_t *FuncDescriptions; 46816a497c6SRafael Auler char *Strings; // String table with function names used in this binary 46916a497c6SRafael Auler int FileDesc; // File descriptor for the file on disk backing this 47016a497c6SRafael Auler // information in memory via mmap 47116a497c6SRafael Auler void *MMapPtr; // The mmap ptr 47216a497c6SRafael Auler int MMapSize; // The mmap size 47316a497c6SRafael Auler 47416a497c6SRafael Auler /// Hash table storing all possible call destinations to detect untracked 47516a497c6SRafael Auler /// calls and correctly report them as [unknown] in output fdata. 47616a497c6SRafael Auler CallFlowHashTable *CallFlowTable; 47716a497c6SRafael Auler 47816a497c6SRafael Auler /// Lookup the sorted indirect call target vector to fetch function name and 47916a497c6SRafael Auler /// offset for an arbitrary function pointer. 48016a497c6SRafael Auler const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const; 48116a497c6SRafael Auler }; 48216a497c6SRafael Auler 48316a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares 48416a497c6SRafael Auler /// at most Size characters. 485cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) { 486821480d2SRafael Auler while (*Str1 == *Str2) { 487821480d2SRafael Auler if (*Str1 == '\0' || --Size == 0) 488821480d2SRafael Auler return 0; 489821480d2SRafael Auler ++Str1; 490821480d2SRafael Auler ++Str2; 491821480d2SRafael Auler } 492821480d2SRafael Auler return 1; 493821480d2SRafael Auler } 494821480d2SRafael Auler 49516a497c6SRafael Auler /// Output Location to the fdata file 49616a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf, 497cc4b2fb6SRafael Auler const Location Loc, uint32_t BufSize) { 498821480d2SRafael Auler // fdata location format: Type Name Offset 499821480d2SRafael Auler // Type 1 - regular symbol 500821480d2SRafael Auler OutBuf = strCopy(OutBuf, "1 "); 50116a497c6SRafael Auler const char *Str = Ctx.Strings + Loc.FunctionName; 502cc4b2fb6SRafael Auler uint32_t Size = 25; 50362aa74f8SRafael Auler while (*Str) { 50462aa74f8SRafael Auler *OutBuf++ = *Str++; 505cc4b2fb6SRafael Auler if (++Size >= BufSize) 506cc4b2fb6SRafael Auler break; 50762aa74f8SRafael Auler } 508cc4b2fb6SRafael Auler assert(!*Str, "buffer overflow, function name too large"); 50962aa74f8SRafael Auler *OutBuf++ = ' '; 510821480d2SRafael Auler OutBuf = intToStr(OutBuf, Loc.Offset, 16); 51162aa74f8SRafael Auler *OutBuf++ = ' '; 51262aa74f8SRafael Auler return OutBuf; 51362aa74f8SRafael Auler } 51462aa74f8SRafael Auler 51516a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc 51616a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file. 51716a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote() 51816a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) { 51916a497c6SRafael Auler NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc); 52016a497c6SRafael Auler DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10)); 52116a497c6SRafael Auler LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4); 52216a497c6SRafael Auler 52316a497c6SRafael Auler NumEdges = *reinterpret_cast<const uint32_t *>( 52416a497c6SRafael Auler FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode)); 52516a497c6SRafael Auler DEBUG(reportNumber("NumEdges = ", NumEdges, 10)); 52616a497c6SRafael Auler Edges = reinterpret_cast<const EdgeDescription *>( 52716a497c6SRafael Auler FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode)); 52816a497c6SRafael Auler 52916a497c6SRafael Auler NumCalls = *reinterpret_cast<const uint32_t *>( 53016a497c6SRafael Auler FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) + 53116a497c6SRafael Auler NumEdges * sizeof(EdgeDescription)); 53216a497c6SRafael Auler DEBUG(reportNumber("NumCalls = ", NumCalls, 10)); 53316a497c6SRafael Auler Calls = reinterpret_cast<const CallDescription *>( 53416a497c6SRafael Auler FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) + 53516a497c6SRafael Auler NumEdges * sizeof(EdgeDescription)); 53616a497c6SRafael Auler NumEntryNodes = *reinterpret_cast<const uint32_t *>( 53716a497c6SRafael Auler FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) + 53816a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription)); 53916a497c6SRafael Auler DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10)); 54016a497c6SRafael Auler EntryNodes = reinterpret_cast<const EntryNode *>( 54116a497c6SRafael Auler FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) + 54216a497c6SRafael Auler NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription)); 54316a497c6SRafael Auler } 54416a497c6SRafael Auler 54516a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes 54616a497c6SRafael Auler /// section 547ba31344fSRafael Auler #ifdef HAVE_ELF_H 54816a497c6SRafael Auler ProfileWriterContext readDescriptions() { 54916a497c6SRafael Auler ProfileWriterContext Result; 550821480d2SRafael Auler uint64_t FD = __open("/proc/self/exe", 551821480d2SRafael Auler /*flags=*/0 /*O_RDONLY*/, 552821480d2SRafael Auler /*mode=*/0666); 553cc4b2fb6SRafael Auler assert(static_cast<int64_t>(FD) > 0, "Failed to open /proc/self/exe"); 554821480d2SRafael Auler Result.FileDesc = FD; 555821480d2SRafael Auler 556821480d2SRafael Auler // mmap our binary to memory 557821480d2SRafael Auler uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/); 558821480d2SRafael Auler uint8_t *BinContents = reinterpret_cast<uint8_t *>( 559821480d2SRafael Auler __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0)); 560821480d2SRafael Auler Result.MMapPtr = BinContents; 561821480d2SRafael Auler Result.MMapSize = Size; 562821480d2SRafael Auler Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents); 563821480d2SRafael Auler Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff); 564821480d2SRafael Auler Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>( 565821480d2SRafael Auler BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize); 566821480d2SRafael Auler 567821480d2SRafael Auler // Find .bolt.instr.tables with the data we need and set pointers to it 568821480d2SRafael Auler for (int I = 0; I < Hdr->e_shnum; ++I) { 569821480d2SRafael Auler char *SecName = reinterpret_cast<char *>( 570821480d2SRafael Auler BinContents + StringTblHeader->sh_offset + Shdr->sh_name); 571821480d2SRafael Auler if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) { 572821480d2SRafael Auler Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff + 573821480d2SRafael Auler (I + 1) * Hdr->e_shentsize); 574821480d2SRafael Auler continue; 575821480d2SRafael Auler } 576821480d2SRafael Auler // Actual contents of the ELF note start after offset 20 decimal: 577821480d2SRafael Auler // Offset 0: Producer name size (4 bytes) 578821480d2SRafael Auler // Offset 4: Contents size (4 bytes) 579821480d2SRafael Auler // Offset 8: Note type (4 bytes) 580821480d2SRafael Auler // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary) 581821480d2SRafael Auler // Offset 20: Contents 58216a497c6SRafael Auler uint32_t IndCallDescSize = 583cc4b2fb6SRafael Auler *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20); 58416a497c6SRafael Auler uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>( 58516a497c6SRafael Auler BinContents + Shdr->sh_offset + 24 + IndCallDescSize); 58616a497c6SRafael Auler uint32_t FuncDescSize = 58716a497c6SRafael Auler *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 + 58816a497c6SRafael Auler IndCallDescSize + IndCallTargetDescSize); 58916a497c6SRafael Auler Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>( 59016a497c6SRafael Auler BinContents + Shdr->sh_offset + 24); 59116a497c6SRafael Auler Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>( 59216a497c6SRafael Auler BinContents + Shdr->sh_offset + 28 + IndCallDescSize); 59316a497c6SRafael Auler Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 + 59416a497c6SRafael Auler IndCallDescSize + IndCallTargetDescSize; 59516a497c6SRafael Auler Result.Strings = reinterpret_cast<char *>( 59616a497c6SRafael Auler BinContents + Shdr->sh_offset + 32 + IndCallDescSize + 59716a497c6SRafael Auler IndCallTargetDescSize + FuncDescSize); 598821480d2SRafael Auler return Result; 599821480d2SRafael Auler } 600821480d2SRafael Auler const char ErrMsg[] = 601821480d2SRafael Auler "BOLT instrumentation runtime error: could not find section " 602821480d2SRafael Auler ".bolt.instr.tables\n"; 603821480d2SRafael Auler reportError(ErrMsg, sizeof(ErrMsg)); 604821480d2SRafael Auler return Result; 605821480d2SRafael Auler } 606ba31344fSRafael Auler #else 60716a497c6SRafael Auler ProfileWriterContext readDescriptions() { 60816a497c6SRafael Auler ProfileWriterContext Result; 609ba31344fSRafael Auler const char ErrMsg[] = 610ba31344fSRafael Auler "BOLT instrumentation runtime error: unsupported binary format.\n"; 611ba31344fSRafael Auler reportError(ErrMsg, sizeof(ErrMsg)); 612ba31344fSRafael Auler return Result; 613ba31344fSRafael Auler } 614ba31344fSRafael Auler #endif 615821480d2SRafael Auler 61616a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane 61716a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) { 618cc4b2fb6SRafael Auler char StatMsg[BufSize]; 619cc4b2fb6SRafael Auler char *StatPtr = StatMsg; 62016a497c6SRafael Auler StatPtr = 62116a497c6SRafael Auler strCopy(StatPtr, 62216a497c6SRafael Auler "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: "); 623cc4b2fb6SRafael Auler StatPtr = intToStr(StatPtr, 62416a497c6SRafael Auler Ctx.FuncDescriptions - 62516a497c6SRafael Auler reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions), 626cc4b2fb6SRafael Auler 10); 627cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\nFuncDescSize: "); 628cc4b2fb6SRafael Auler StatPtr = intToStr( 629cc4b2fb6SRafael Auler StatPtr, 63016a497c6SRafael Auler reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10); 63116a497c6SRafael Auler StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: "); 63216a497c6SRafael Auler StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10); 633cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: "); 634cc4b2fb6SRafael Auler StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10); 635cc4b2fb6SRafael Auler StatPtr = strCopy(StatPtr, "\n"); 636cc4b2fb6SRafael Auler __write(2, StatMsg, StatPtr - StatMsg); 637cc4b2fb6SRafael Auler } 638cc4b2fb6SRafael Auler 639cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store 640cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store 641cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning 642cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in 643cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes. 644cc4b2fb6SRafael Auler struct Edge { 645cc4b2fb6SRafael Auler uint32_t Node; // Index in nodes array regarding the destination of this edge 646cc4b2fb6SRafael Auler uint32_t ID; // Edge index in an array comprising all edges of the graph 647cc4b2fb6SRafael Auler }; 648cc4b2fb6SRafael Auler 649cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node 650cc4b2fb6SRafael Auler struct Node { 651cc4b2fb6SRafael Auler uint32_t NumInEdges{0}; // Input edge count used to size InEdge 652cc4b2fb6SRafael Auler uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges 653cc4b2fb6SRafael Auler Edge *InEdges{nullptr}; // Created and managed by \p Graph 654cc4b2fb6SRafael Auler Edge *OutEdges{nullptr}; // ditto 655cc4b2fb6SRafael Auler }; 656cc4b2fb6SRafael Auler 657cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and 658cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding 659cc4b2fb6SRafael Auler /// spanning tree nodes. 660cc4b2fb6SRafael Auler struct Graph { 661cc4b2fb6SRafael Auler uint32_t NumNodes; 662cc4b2fb6SRafael Auler Node *CFGNodes; 663cc4b2fb6SRafael Auler Node *SpanningTreeNodes; 66416a497c6SRafael Auler uint64_t *EdgeFreqs; 66516a497c6SRafael Auler uint64_t *CallFreqs; 666cc4b2fb6SRafael Auler BumpPtrAllocator &Alloc; 66716a497c6SRafael Auler const FunctionDescription &D; 668cc4b2fb6SRafael Auler 66916a497c6SRafael Auler /// Reads a list of edges from function description \p D and builds 670cc4b2fb6SRafael Auler /// the graph from it. Allocates several internal dynamic structures that are 67116a497c6SRafael Auler /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all 672cc4b2fb6SRafael Auler /// spanning tree leaf nodes descriptions (their counters). They are the seed 673cc4b2fb6SRafael Auler /// used to compute the rest of the missing edge counts in a bottom-up 674cc4b2fb6SRafael Auler /// traversal of the spanning tree. 67516a497c6SRafael Auler Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D, 67616a497c6SRafael Auler const uint64_t *Counters, ProfileWriterContext &Ctx); 677cc4b2fb6SRafael Auler ~Graph(); 678cc4b2fb6SRafael Auler void dump() const; 67916a497c6SRafael Auler 68016a497c6SRafael Auler private: 68116a497c6SRafael Auler void computeEdgeFrequencies(const uint64_t *Counters, 68216a497c6SRafael Auler ProfileWriterContext &Ctx); 68316a497c6SRafael Auler void dumpEdgeFreqs() const; 684cc4b2fb6SRafael Auler }; 685cc4b2fb6SRafael Auler 68616a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D, 68716a497c6SRafael Auler const uint64_t *Counters, ProfileWriterContext &Ctx) 68816a497c6SRafael Auler : Alloc(Alloc), D(D) { 689cc4b2fb6SRafael Auler DEBUG(reportNumber("G = 0x", (uint64_t)this, 16)); 690cc4b2fb6SRafael Auler // First pass to determine number of nodes 69116a497c6SRafael Auler int32_t MaxNodes = -1; 69216a497c6SRafael Auler CallFreqs = nullptr; 69316a497c6SRafael Auler EdgeFreqs = nullptr; 69416a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 69516a497c6SRafael Auler if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes) 69616a497c6SRafael Auler MaxNodes = D.Edges[I].FromNode; 69716a497c6SRafael Auler if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes) 69816a497c6SRafael Auler MaxNodes = D.Edges[I].ToNode; 699cc4b2fb6SRafael Auler } 70016a497c6SRafael Auler for (int I = 0; I < D.NumLeafNodes; ++I) { 70116a497c6SRafael Auler if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes) 70216a497c6SRafael Auler MaxNodes = D.LeafNodes[I].Node; 703cc4b2fb6SRafael Auler } 70416a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 70516a497c6SRafael Auler if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes) 70616a497c6SRafael Auler MaxNodes = D.Calls[I].FromNode; 70716a497c6SRafael Auler } 70816a497c6SRafael Auler // No nodes? Nothing to do 70916a497c6SRafael Auler if (MaxNodes < 0) { 71016a497c6SRafael Auler DEBUG(report("No nodes!\n")); 711cc4b2fb6SRafael Auler CFGNodes = nullptr; 712cc4b2fb6SRafael Auler SpanningTreeNodes = nullptr; 713cc4b2fb6SRafael Auler NumNodes = 0; 714cc4b2fb6SRafael Auler return; 715cc4b2fb6SRafael Auler } 716cc4b2fb6SRafael Auler ++MaxNodes; 717cc4b2fb6SRafael Auler DEBUG(reportNumber("NumNodes = ", MaxNodes, 10)); 71816a497c6SRafael Auler NumNodes = static_cast<uint32_t>(MaxNodes); 719cc4b2fb6SRafael Auler 720cc4b2fb6SRafael Auler // Initial allocations 721cc4b2fb6SRafael Auler CFGNodes = new (Alloc) Node[MaxNodes]; 722cc4b2fb6SRafael Auler DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16)); 723cc4b2fb6SRafael Auler SpanningTreeNodes = new (Alloc) Node[MaxNodes]; 724cc4b2fb6SRafael Auler DEBUG(reportNumber("G->SpanningTreeNodes = 0x", 725cc4b2fb6SRafael Auler (uint64_t)SpanningTreeNodes, 16)); 726cc4b2fb6SRafael Auler 727cc4b2fb6SRafael Auler // Figure out how much to allocate to each vector (in/out edge sets) 72816a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 72916a497c6SRafael Auler CFGNodes[D.Edges[I].FromNode].NumOutEdges++; 73016a497c6SRafael Auler CFGNodes[D.Edges[I].ToNode].NumInEdges++; 73116a497c6SRafael Auler if (D.Edges[I].Counter != 0xffffffff) 732cc4b2fb6SRafael Auler continue; 733cc4b2fb6SRafael Auler 73416a497c6SRafael Auler SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++; 73516a497c6SRafael Auler SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++; 736cc4b2fb6SRafael Auler } 737cc4b2fb6SRafael Auler 738cc4b2fb6SRafael Auler // Allocate in/out edge sets 739cc4b2fb6SRafael Auler for (int I = 0; I < MaxNodes; ++I) { 740cc4b2fb6SRafael Auler if (CFGNodes[I].NumInEdges > 0) 741cc4b2fb6SRafael Auler CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges]; 742cc4b2fb6SRafael Auler if (CFGNodes[I].NumOutEdges > 0) 743cc4b2fb6SRafael Auler CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges]; 744cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].NumInEdges > 0) 745cc4b2fb6SRafael Auler SpanningTreeNodes[I].InEdges = 746cc4b2fb6SRafael Auler new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges]; 747cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].NumOutEdges > 0) 748cc4b2fb6SRafael Auler SpanningTreeNodes[I].OutEdges = 749cc4b2fb6SRafael Auler new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges]; 750cc4b2fb6SRafael Auler CFGNodes[I].NumInEdges = 0; 751cc4b2fb6SRafael Auler CFGNodes[I].NumOutEdges = 0; 752cc4b2fb6SRafael Auler SpanningTreeNodes[I].NumInEdges = 0; 753cc4b2fb6SRafael Auler SpanningTreeNodes[I].NumOutEdges = 0; 754cc4b2fb6SRafael Auler } 755cc4b2fb6SRafael Auler 756cc4b2fb6SRafael Auler // Fill in/out edge sets 75716a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 75816a497c6SRafael Auler const uint32_t Src = D.Edges[I].FromNode; 75916a497c6SRafael Auler const uint32_t Dst = D.Edges[I].ToNode; 760cc4b2fb6SRafael Auler Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++]; 761cc4b2fb6SRafael Auler E->Node = Dst; 762cc4b2fb6SRafael Auler E->ID = I; 763cc4b2fb6SRafael Auler 764cc4b2fb6SRafael Auler E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++]; 765cc4b2fb6SRafael Auler E->Node = Src; 766cc4b2fb6SRafael Auler E->ID = I; 767cc4b2fb6SRafael Auler 76816a497c6SRafael Auler if (D.Edges[I].Counter != 0xffffffff) 769cc4b2fb6SRafael Auler continue; 770cc4b2fb6SRafael Auler 771cc4b2fb6SRafael Auler E = &SpanningTreeNodes[Src] 772cc4b2fb6SRafael Auler .OutEdges[SpanningTreeNodes[Src].NumOutEdges++]; 773cc4b2fb6SRafael Auler E->Node = Dst; 774cc4b2fb6SRafael Auler E->ID = I; 775cc4b2fb6SRafael Auler 776cc4b2fb6SRafael Auler E = &SpanningTreeNodes[Dst] 777cc4b2fb6SRafael Auler .InEdges[SpanningTreeNodes[Dst].NumInEdges++]; 778cc4b2fb6SRafael Auler E->Node = Src; 779cc4b2fb6SRafael Auler E->ID = I; 780cc4b2fb6SRafael Auler } 78116a497c6SRafael Auler 78216a497c6SRafael Auler computeEdgeFrequencies(Counters, Ctx); 783cc4b2fb6SRafael Auler } 784cc4b2fb6SRafael Auler 785cc4b2fb6SRafael Auler Graph::~Graph() { 78616a497c6SRafael Auler if (CallFreqs) 78716a497c6SRafael Auler Alloc.deallocate(CallFreqs); 78816a497c6SRafael Auler if (EdgeFreqs) 78916a497c6SRafael Auler Alloc.deallocate(EdgeFreqs); 790cc4b2fb6SRafael Auler for (int I = NumNodes - 1; I >= 0; --I) { 791cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].OutEdges) 792cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes[I].OutEdges); 793cc4b2fb6SRafael Auler if (SpanningTreeNodes[I].InEdges) 794cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes[I].InEdges); 795cc4b2fb6SRafael Auler if (CFGNodes[I].OutEdges) 796cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes[I].OutEdges); 797cc4b2fb6SRafael Auler if (CFGNodes[I].InEdges) 798cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes[I].InEdges); 799cc4b2fb6SRafael Auler } 800cc4b2fb6SRafael Auler if (SpanningTreeNodes) 801cc4b2fb6SRafael Auler Alloc.deallocate(SpanningTreeNodes); 802cc4b2fb6SRafael Auler if (CFGNodes) 803cc4b2fb6SRafael Auler Alloc.deallocate(CFGNodes); 804cc4b2fb6SRafael Auler } 805cc4b2fb6SRafael Auler 806cc4b2fb6SRafael Auler void Graph::dump() const { 807cc4b2fb6SRafael Auler reportNumber("Dumping graph with number of nodes: ", NumNodes, 10); 808cc4b2fb6SRafael Auler report(" Full graph:\n"); 809cc4b2fb6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 810cc4b2fb6SRafael Auler const Node *N = &CFGNodes[I]; 811cc4b2fb6SRafael Auler reportNumber(" Node #", I, 10); 812cc4b2fb6SRafael Auler reportNumber(" InEdges total ", N->NumInEdges, 10); 813cc4b2fb6SRafael Auler for (int J = 0; J < N->NumInEdges; ++J) 814cc4b2fb6SRafael Auler reportNumber(" ", N->InEdges[J].Node, 10); 815cc4b2fb6SRafael Auler reportNumber(" OutEdges total ", N->NumOutEdges, 10); 816cc4b2fb6SRafael Auler for (int J = 0; J < N->NumOutEdges; ++J) 817cc4b2fb6SRafael Auler reportNumber(" ", N->OutEdges[J].Node, 10); 818cc4b2fb6SRafael Auler report("\n"); 819cc4b2fb6SRafael Auler } 820cc4b2fb6SRafael Auler report(" Spanning tree:\n"); 821cc4b2fb6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 822cc4b2fb6SRafael Auler const Node *N = &SpanningTreeNodes[I]; 823cc4b2fb6SRafael Auler reportNumber(" Node #", I, 10); 824cc4b2fb6SRafael Auler reportNumber(" InEdges total ", N->NumInEdges, 10); 825cc4b2fb6SRafael Auler for (int J = 0; J < N->NumInEdges; ++J) 826cc4b2fb6SRafael Auler reportNumber(" ", N->InEdges[J].Node, 10); 827cc4b2fb6SRafael Auler reportNumber(" OutEdges total ", N->NumOutEdges, 10); 828cc4b2fb6SRafael Auler for (int J = 0; J < N->NumOutEdges; ++J) 829cc4b2fb6SRafael Auler reportNumber(" ", N->OutEdges[J].Node, 10); 830cc4b2fb6SRafael Auler report("\n"); 831cc4b2fb6SRafael Auler } 832cc4b2fb6SRafael Auler } 833cc4b2fb6SRafael Auler 83416a497c6SRafael Auler void Graph::dumpEdgeFreqs() const { 83516a497c6SRafael Auler reportNumber( 83616a497c6SRafael Auler "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10); 83716a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 83816a497c6SRafael Auler reportNumber("* Src: ", D.Edges[I].FromNode, 10); 83916a497c6SRafael Auler reportNumber(" Dst: ", D.Edges[I].ToNode, 10); 840cc4b2fb6SRafael Auler reportNumber(" Cnt: ", EdgeFreqs[I], 10); 841cc4b2fb6SRafael Auler } 842cc4b2fb6SRafael Auler } 843cc4b2fb6SRafael Auler 84416a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of 84516a497c6SRafael Auler /// the function CFG 84616a497c6SRafael Auler struct NodeToCallsMap { 84716a497c6SRafael Auler struct MapEntry { 84816a497c6SRafael Auler uint32_t NumCalls; 84916a497c6SRafael Auler uint32_t *Calls; 85016a497c6SRafael Auler }; 85116a497c6SRafael Auler MapEntry *Entries; 85216a497c6SRafael Auler BumpPtrAllocator &Alloc; 85316a497c6SRafael Auler const uint32_t NumNodes; 854cc4b2fb6SRafael Auler 85516a497c6SRafael Auler NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D, 85616a497c6SRafael Auler uint32_t NumNodes) 85716a497c6SRafael Auler : Alloc(Alloc), NumNodes(NumNodes) { 85816a497c6SRafael Auler Entries = new (Alloc, 0) MapEntry[NumNodes]; 85916a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 86016a497c6SRafael Auler DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10)); 86116a497c6SRafael Auler ++Entries[D.Calls[I].FromNode].NumCalls; 86216a497c6SRafael Auler } 86316a497c6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 86416a497c6SRafael Auler Entries[I].Calls = Entries[I].NumCalls ? new (Alloc) 86516a497c6SRafael Auler uint32_t[Entries[I].NumCalls] 86616a497c6SRafael Auler : nullptr; 86716a497c6SRafael Auler Entries[I].NumCalls = 0; 86816a497c6SRafael Auler } 86916a497c6SRafael Auler for (int I = 0; I < D.NumCalls; ++I) { 87016a497c6SRafael Auler auto &Entry = Entries[D.Calls[I].FromNode]; 87116a497c6SRafael Auler Entry.Calls[Entry.NumCalls++] = I; 87216a497c6SRafael Auler } 87316a497c6SRafael Auler } 87416a497c6SRafael Auler 87516a497c6SRafael Auler /// Set the frequency of all calls in node \p NodeID to Freq. However, if 87616a497c6SRafael Auler /// the calls have their own counters and do not depend on the basic block 87716a497c6SRafael Auler /// counter, this means they have landing pads and throw exceptions. In this 87816a497c6SRafael Auler /// case, set their frequency with their counters and return the maximum 87916a497c6SRafael Auler /// value observed in such counters. This will be used as the new frequency 88016a497c6SRafael Auler /// at basic block entry. This is used to fix the CFG edge frequencies in the 88116a497c6SRafael Auler /// presence of exceptions. 88216a497c6SRafael Auler uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs, 88316a497c6SRafael Auler const FunctionDescription &D, 88416a497c6SRafael Auler const uint64_t *Counters, 88516a497c6SRafael Auler ProfileWriterContext &Ctx) const { 88616a497c6SRafael Auler const auto &Entry = Entries[NodeID]; 88716a497c6SRafael Auler uint64_t MaxValue = 0ull; 88816a497c6SRafael Auler for (int I = 0, E = Entry.NumCalls; I != E; ++I) { 88916a497c6SRafael Auler const auto CallID = Entry.Calls[I]; 89016a497c6SRafael Auler DEBUG(reportNumber(" Setting freq for call ID: ", CallID, 10)); 89116a497c6SRafael Auler auto &CallDesc = D.Calls[CallID]; 89216a497c6SRafael Auler if (CallDesc.Counter == 0xffffffff) { 89316a497c6SRafael Auler CallFreqs[CallID] = Freq; 89416a497c6SRafael Auler DEBUG(reportNumber(" with : ", Freq, 10)); 89516a497c6SRafael Auler } else { 89616a497c6SRafael Auler const auto CounterVal = Counters[CallDesc.Counter]; 89716a497c6SRafael Auler CallFreqs[CallID] = CounterVal; 89816a497c6SRafael Auler MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue; 89916a497c6SRafael Auler DEBUG(reportNumber(" with (private counter) : ", CounterVal, 10)); 90016a497c6SRafael Auler } 90116a497c6SRafael Auler DEBUG(reportNumber(" Address: 0x", CallDesc.TargetAddress, 16)); 90216a497c6SRafael Auler if (CallFreqs[CallID] > 0) 90316a497c6SRafael Auler Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls += 90416a497c6SRafael Auler CallFreqs[CallID]; 90516a497c6SRafael Auler } 90616a497c6SRafael Auler return MaxValue; 90716a497c6SRafael Auler } 90816a497c6SRafael Auler 90916a497c6SRafael Auler ~NodeToCallsMap() { 91016a497c6SRafael Auler for (int I = NumNodes - 1; I >= 0; --I) { 91116a497c6SRafael Auler if (Entries[I].Calls) 91216a497c6SRafael Auler Alloc.deallocate(Entries[I].Calls); 91316a497c6SRafael Auler } 91416a497c6SRafael Auler Alloc.deallocate(Entries); 91516a497c6SRafael Auler } 91616a497c6SRafael Auler }; 91716a497c6SRafael Auler 91816a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented 91916a497c6SRafael Auler /// by G, as well as another array for each call. 92016a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters, 92116a497c6SRafael Auler ProfileWriterContext &Ctx) { 92216a497c6SRafael Auler if (NumNodes == 0) 92316a497c6SRafael Auler return; 92416a497c6SRafael Auler 92516a497c6SRafael Auler EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr; 92616a497c6SRafael Auler CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr; 92716a497c6SRafael Auler 92816a497c6SRafael Auler // Setup a lookup for calls present in each node (BB) 92916a497c6SRafael Auler NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes); 930cc4b2fb6SRafael Auler 931cc4b2fb6SRafael Auler // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the 932cc4b2fb6SRafael Auler // spanning tree don't have explicit counters. We must infer their value using 933cc4b2fb6SRafael Auler // a linear combination of other counters (sum of counters of the outgoing 934cc4b2fb6SRafael Auler // edges minus sum of counters of the incoming edges). 93516a497c6SRafael Auler uint32_t *Stack = new (Alloc) uint32_t [NumNodes]; 936cc4b2fb6SRafael Auler uint32_t StackTop = 0; 937cc4b2fb6SRafael Auler enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED }; 93816a497c6SRafael Auler Status *Visited = new (Alloc, 0) Status[NumNodes]; 93916a497c6SRafael Auler uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes]; 94016a497c6SRafael Auler uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes]; 941cc4b2fb6SRafael Auler 942cc4b2fb6SRafael Auler // Setup a fast lookup for frequency of leaf nodes, which have special 943cc4b2fb6SRafael Auler // basic block frequency instrumentation (they are not edge profiled). 94416a497c6SRafael Auler for (int I = 0; I < D.NumLeafNodes; ++I) { 94516a497c6SRafael Auler LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter]; 946cc4b2fb6SRafael Auler DEBUG({ 94716a497c6SRafael Auler if (Counters[D.LeafNodes[I].Counter] > 0) { 94816a497c6SRafael Auler reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10); 94916a497c6SRafael Auler reportNumber(" Counter: ", Counters[D.LeafNodes[I].Counter], 10); 950cc4b2fb6SRafael Auler } 951cc4b2fb6SRafael Auler }); 95216a497c6SRafael Auler } 95316a497c6SRafael Auler for (int I = 0; I < D.NumEntryNodes; ++I) { 95416a497c6SRafael Auler EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address; 95516a497c6SRafael Auler DEBUG({ 95616a497c6SRafael Auler reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10); 95716a497c6SRafael Auler reportNumber(" Address: ", D.EntryNodes[I].Address, 16); 95816a497c6SRafael Auler }); 959cc4b2fb6SRafael Auler } 960cc4b2fb6SRafael Auler // Add all root nodes to the stack 96116a497c6SRafael Auler for (int I = 0; I < NumNodes; ++I) { 96216a497c6SRafael Auler if (SpanningTreeNodes[I].NumInEdges == 0) 963cc4b2fb6SRafael Auler Stack[StackTop++] = I; 964cc4b2fb6SRafael Auler } 965cc4b2fb6SRafael Auler // Empty stack? 966cc4b2fb6SRafael Auler if (StackTop == 0) { 96716a497c6SRafael Auler DEBUG(report("Empty stack!\n")); 96816a497c6SRafael Auler Alloc.deallocate(EntryAddress); 969cc4b2fb6SRafael Auler Alloc.deallocate(LeafFrequency); 970cc4b2fb6SRafael Auler Alloc.deallocate(Visited); 971cc4b2fb6SRafael Auler Alloc.deallocate(Stack); 97216a497c6SRafael Auler CallMap->~NodeToCallsMap(); 97316a497c6SRafael Auler Alloc.deallocate(CallMap); 97416a497c6SRafael Auler if (CallFreqs) 97516a497c6SRafael Auler Alloc.deallocate(CallFreqs); 97616a497c6SRafael Auler if (EdgeFreqs) 97716a497c6SRafael Auler Alloc.deallocate(EdgeFreqs); 97816a497c6SRafael Auler EdgeFreqs = nullptr; 97916a497c6SRafael Auler CallFreqs = nullptr; 98016a497c6SRafael Auler return; 981cc4b2fb6SRafael Auler } 982cc4b2fb6SRafael Auler // Add all known edge counts, will infer the rest 98316a497c6SRafael Auler for (int I = 0; I < D.NumEdges; ++I) { 98416a497c6SRafael Auler const uint32_t C = D.Edges[I].Counter; 985cc4b2fb6SRafael Auler if (C == 0xffffffff) // inferred counter - we will compute its value 986cc4b2fb6SRafael Auler continue; 98716a497c6SRafael Auler EdgeFreqs[I] = Counters[C]; 988cc4b2fb6SRafael Auler } 989cc4b2fb6SRafael Auler 990cc4b2fb6SRafael Auler while (StackTop > 0) { 991cc4b2fb6SRafael Auler const uint32_t Cur = Stack[--StackTop]; 992cc4b2fb6SRafael Auler DEBUG({ 993cc4b2fb6SRafael Auler if (Visited[Cur] == S_VISITING) 994cc4b2fb6SRafael Auler report("(visiting) "); 995cc4b2fb6SRafael Auler else 996cc4b2fb6SRafael Auler report("(new) "); 997cc4b2fb6SRafael Auler reportNumber("Cur: ", Cur, 10); 998cc4b2fb6SRafael Auler }); 999cc4b2fb6SRafael Auler 1000cc4b2fb6SRafael Auler // This shouldn't happen in a tree 1001cc4b2fb6SRafael Auler assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack"); 1002cc4b2fb6SRafael Auler if (Visited[Cur] == S_NEW) { 1003cc4b2fb6SRafael Auler Visited[Cur] = S_VISITING; 1004cc4b2fb6SRafael Auler Stack[StackTop++] = Cur; 100516a497c6SRafael Auler assert(StackTop <= NumNodes, "stack grew too large"); 100616a497c6SRafael Auler for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) { 100716a497c6SRafael Auler const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node; 1008cc4b2fb6SRafael Auler Stack[StackTop++] = Succ; 100916a497c6SRafael Auler assert(StackTop <= NumNodes, "stack grew too large"); 1010cc4b2fb6SRafael Auler } 1011cc4b2fb6SRafael Auler continue; 1012cc4b2fb6SRafael Auler } 1013cc4b2fb6SRafael Auler Visited[Cur] = S_VISITED; 1014cc4b2fb6SRafael Auler 1015cc4b2fb6SRafael Auler // Establish our node frequency based on outgoing edges, which should all be 1016cc4b2fb6SRafael Auler // resolved by now. 1017cc4b2fb6SRafael Auler int64_t CurNodeFreq = LeafFrequency[Cur]; 1018cc4b2fb6SRafael Auler // Not a leaf? 1019cc4b2fb6SRafael Auler if (!CurNodeFreq) { 102016a497c6SRafael Auler for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) { 102116a497c6SRafael Auler const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID; 102216a497c6SRafael Auler CurNodeFreq += EdgeFreqs[SuccEdge]; 1023cc4b2fb6SRafael Auler } 1024cc4b2fb6SRafael Auler } 102516a497c6SRafael Auler if (CurNodeFreq < 0) 102616a497c6SRafael Auler CurNodeFreq = 0; 102716a497c6SRafael Auler 102816a497c6SRafael Auler const uint64_t CallFreq = CallMap->visitAllCallsIn( 102916a497c6SRafael Auler Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx); 103016a497c6SRafael Auler 103116a497c6SRafael Auler // Exception handling affected our output flow? Fix with calls info 103216a497c6SRafael Auler DEBUG({ 103316a497c6SRafael Auler if (CallFreq > CurNodeFreq) 103416a497c6SRafael Auler report("Bumping node frequency with call info\n"); 103516a497c6SRafael Auler }); 103616a497c6SRafael Auler CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq; 103716a497c6SRafael Auler 103816a497c6SRafael Auler if (CurNodeFreq > 0) { 103916a497c6SRafael Auler if (uint64_t Addr = EntryAddress[Cur]) { 104016a497c6SRafael Auler DEBUG( 104116a497c6SRafael Auler reportNumber(" Setting flow at entry point address 0x", Addr, 16)); 104216a497c6SRafael Auler DEBUG(reportNumber(" with: ", CurNodeFreq, 10)); 104316a497c6SRafael Auler Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq; 104416a497c6SRafael Auler } 104516a497c6SRafael Auler } 104616a497c6SRafael Auler 104716a497c6SRafael Auler // No parent? Reached a tree root, limit to call frequency updating. 104816a497c6SRafael Auler if (SpanningTreeNodes[Cur].NumInEdges == 0) { 104916a497c6SRafael Auler continue; 105016a497c6SRafael Auler } 105116a497c6SRafael Auler 105216a497c6SRafael Auler assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent"); 105316a497c6SRafael Auler const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node; 105416a497c6SRafael Auler const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID; 105516a497c6SRafael Auler 1056cc4b2fb6SRafael Auler // Calculate parent edge freq. 105716a497c6SRafael Auler int64_t ParentEdgeFreq = CurNodeFreq; 105816a497c6SRafael Auler for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) { 105916a497c6SRafael Auler const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID; 106016a497c6SRafael Auler ParentEdgeFreq -= EdgeFreqs[PredEdge]; 1061cc4b2fb6SRafael Auler } 106216a497c6SRafael Auler 1063cc4b2fb6SRafael Auler // Sometimes the conservative CFG that BOLT builds will lead to incorrect 1064cc4b2fb6SRafael Auler // flow computation. For example, in a BB that transitively calls the exit 1065cc4b2fb6SRafael Auler // syscall, BOLT will add a fall-through successor even though it should not 1066cc4b2fb6SRafael Auler // have any successors. So this block execution will likely be wrong. We 1067cc4b2fb6SRafael Auler // tolerate this imperfection since this case should be quite infrequent. 1068cc4b2fb6SRafael Auler if (ParentEdgeFreq < 0) { 106916a497c6SRafael Auler DEBUG(dumpEdgeFreqs()); 1070cc4b2fb6SRafael Auler DEBUG(report("WARNING: incorrect flow")); 1071cc4b2fb6SRafael Auler ParentEdgeFreq = 0; 1072cc4b2fb6SRafael Auler } 1073cc4b2fb6SRafael Auler DEBUG(reportNumber(" Setting freq for ParentEdge: ", ParentEdge, 10)); 1074cc4b2fb6SRafael Auler DEBUG(reportNumber(" with ParentEdgeFreq: ", ParentEdgeFreq, 10)); 107516a497c6SRafael Auler EdgeFreqs[ParentEdge] = ParentEdgeFreq; 1076cc4b2fb6SRafael Auler } 1077cc4b2fb6SRafael Auler 107816a497c6SRafael Auler Alloc.deallocate(EntryAddress); 1079cc4b2fb6SRafael Auler Alloc.deallocate(LeafFrequency); 1080cc4b2fb6SRafael Auler Alloc.deallocate(Visited); 1081cc4b2fb6SRafael Auler Alloc.deallocate(Stack); 108216a497c6SRafael Auler CallMap->~NodeToCallsMap(); 108316a497c6SRafael Auler Alloc.deallocate(CallMap); 108416a497c6SRafael Auler DEBUG(dumpEdgeFreqs()); 1085cc4b2fb6SRafael Auler } 1086cc4b2fb6SRafael Auler 108716a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses 108816a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for 108916a497c6SRafael Auler /// edges that we do not explictly instrument. 109016a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx, 109116a497c6SRafael Auler const uint8_t *FuncDesc, 109216a497c6SRafael Auler BumpPtrAllocator &Alloc) { 109316a497c6SRafael Auler const FunctionDescription F(FuncDesc); 109416a497c6SRafael Auler const uint8_t *next = FuncDesc + F.getSize(); 1095cc4b2fb6SRafael Auler 1096cc4b2fb6SRafael Auler // Skip funcs we know are cold 1097cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG 109816a497c6SRafael Auler uint64_t CountersFreq = 0; 109916a497c6SRafael Auler for (int I = 0; I < F.NumLeafNodes; ++I) { 110016a497c6SRafael Auler CountersFreq += __bolt_instr_locations[F.LeafNodes[I].Counter]; 1101cc4b2fb6SRafael Auler } 110216a497c6SRafael Auler if (CountersFreq == 0) { 110316a497c6SRafael Auler for (int I = 0; I < F.NumEdges; ++I) { 110416a497c6SRafael Auler const uint32_t C = F.Edges[I].Counter; 110516a497c6SRafael Auler if (C == 0xffffffff) 110616a497c6SRafael Auler continue; 110716a497c6SRafael Auler CountersFreq += __bolt_instr_locations[C]; 110816a497c6SRafael Auler } 110916a497c6SRafael Auler if (CountersFreq == 0) { 111016a497c6SRafael Auler for (int I = 0; I < F.NumCalls; ++I) { 111116a497c6SRafael Auler const uint32_t C = F.Calls[I].Counter; 111216a497c6SRafael Auler if (C == 0xffffffff) 111316a497c6SRafael Auler continue; 111416a497c6SRafael Auler CountersFreq += __bolt_instr_locations[C]; 111516a497c6SRafael Auler } 111616a497c6SRafael Auler if (CountersFreq == 0) 1117cc4b2fb6SRafael Auler return next; 111816a497c6SRafael Auler } 111916a497c6SRafael Auler } 1120cc4b2fb6SRafael Auler #endif 1121cc4b2fb6SRafael Auler 112216a497c6SRafael Auler Graph *G = new (Alloc) Graph(Alloc, F, __bolt_instr_locations, Ctx); 1123cc4b2fb6SRafael Auler DEBUG(G->dump()); 112416a497c6SRafael Auler if (!G->EdgeFreqs && !G->CallFreqs) { 1125cc4b2fb6SRafael Auler G->~Graph(); 1126cc4b2fb6SRafael Auler Alloc.deallocate(G); 1127cc4b2fb6SRafael Auler return next; 1128cc4b2fb6SRafael Auler } 1129cc4b2fb6SRafael Auler 113016a497c6SRafael Auler for (int I = 0; I < F.NumEdges; ++I) { 113116a497c6SRafael Auler const uint64_t Freq = G->EdgeFreqs[I]; 1132cc4b2fb6SRafael Auler if (Freq == 0) 1133cc4b2fb6SRafael Auler continue; 113416a497c6SRafael Auler const EdgeDescription *Desc = &F.Edges[I]; 1135cc4b2fb6SRafael Auler char LineBuf[BufSize]; 1136cc4b2fb6SRafael Auler char *Ptr = LineBuf; 113716a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize); 113816a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf)); 1139cc4b2fb6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22); 1140cc4b2fb6SRafael Auler Ptr = intToStr(Ptr, Freq, 10); 1141cc4b2fb6SRafael Auler *Ptr++ = '\n'; 1142cc4b2fb6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 1143cc4b2fb6SRafael Auler } 1144cc4b2fb6SRafael Auler 114516a497c6SRafael Auler for (int I = 0; I < F.NumCalls; ++I) { 114616a497c6SRafael Auler const uint64_t Freq = G->CallFreqs[I]; 114716a497c6SRafael Auler if (Freq == 0) 114816a497c6SRafael Auler continue; 114916a497c6SRafael Auler char LineBuf[BufSize]; 115016a497c6SRafael Auler char *Ptr = LineBuf; 115116a497c6SRafael Auler const CallDescription *Desc = &F.Calls[I]; 115216a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize); 115316a497c6SRafael Auler Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf)); 115416a497c6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 115516a497c6SRafael Auler Ptr = intToStr(Ptr, Freq, 10); 115616a497c6SRafael Auler *Ptr++ = '\n'; 115716a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 115816a497c6SRafael Auler } 115916a497c6SRafael Auler 1160cc4b2fb6SRafael Auler G->~Graph(); 1161cc4b2fb6SRafael Auler Alloc.deallocate(G); 1162cc4b2fb6SRafael Auler return next; 1163cc4b2fb6SRafael Auler } 1164cc4b2fb6SRafael Auler 116516a497c6SRafael Auler const IndCallTargetDescription * 116616a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const { 116716a497c6SRafael Auler uint32_t B = 0; 116816a497c6SRafael Auler uint32_t E = __bolt_instr_num_ind_targets; 116916a497c6SRafael Auler if (E == 0) 117016a497c6SRafael Auler return nullptr; 117116a497c6SRafael Auler do { 117216a497c6SRafael Auler uint32_t I = (E - B) / 2 + B; 117316a497c6SRafael Auler if (IndCallTargets[I].Address == Target) 117416a497c6SRafael Auler return &IndCallTargets[I]; 117516a497c6SRafael Auler if (IndCallTargets[I].Address < Target) 117616a497c6SRafael Auler B = I + 1; 117716a497c6SRafael Auler else 117816a497c6SRafael Auler E = I; 117916a497c6SRafael Auler } while (B < E); 118016a497c6SRafael Auler return nullptr; 1181cc4b2fb6SRafael Auler } 118262aa74f8SRafael Auler 118316a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file 118416a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry, 118516a497c6SRafael Auler int FD, int CallsiteID, 118616a497c6SRafael Auler ProfileWriterContext *Ctx) { 118716a497c6SRafael Auler if (Entry.Val == 0) 118816a497c6SRafael Auler return; 118916a497c6SRafael Auler DEBUG(reportNumber("Target func 0x", Entry.Key, 16)); 119016a497c6SRafael Auler DEBUG(reportNumber("Target freq: ", Entry.Val, 10)); 119116a497c6SRafael Auler const IndCallDescription *CallsiteDesc = 119216a497c6SRafael Auler &Ctx->IndCallDescriptions[CallsiteID]; 119316a497c6SRafael Auler const IndCallTargetDescription *TargetDesc = 119416a497c6SRafael Auler Ctx->lookupIndCallTarget(Entry.Key); 119516a497c6SRafael Auler if (!TargetDesc) { 119616a497c6SRafael Auler DEBUG(report("Failed to lookup indirect call target\n")); 1197cc4b2fb6SRafael Auler char LineBuf[BufSize]; 119862aa74f8SRafael Auler char *Ptr = LineBuf; 119916a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize); 120016a497c6SRafael Auler Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40); 120116a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val, 10); 120216a497c6SRafael Auler *Ptr++ = '\n'; 120316a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 120416a497c6SRafael Auler return; 120516a497c6SRafael Auler } 120616a497c6SRafael Auler Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val; 120716a497c6SRafael Auler char LineBuf[BufSize]; 120816a497c6SRafael Auler char *Ptr = LineBuf; 120916a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize); 121016a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf)); 1211cc4b2fb6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 121216a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val, 10); 121362aa74f8SRafael Auler *Ptr++ = '\n'; 1214821480d2SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 121562aa74f8SRafael Auler } 1216cc4b2fb6SRafael Auler 121716a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles. 121816a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) { 121916a497c6SRafael Auler for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) { 122016a497c6SRafael Auler DEBUG(reportNumber("IndCallsite #", I, 10)); 122116a497c6SRafael Auler GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx); 122216a497c6SRafael Auler } 122316a497c6SRafael Auler } 122416a497c6SRafael Auler 122516a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are 122616a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source 122716a497c6SRafael Auler /// [unknown] in the profile. 122816a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD, 122916a497c6SRafael Auler ProfileWriterContext *Ctx) { 123016a497c6SRafael Auler DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16)); 123116a497c6SRafael Auler DEBUG(reportNumber("Calls: ", Entry.Calls, 10)); 123216a497c6SRafael Auler DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10)); 123316a497c6SRafael Auler DEBUG({ 123416a497c6SRafael Auler if (Entry.Calls > Entry.Val) 123516a497c6SRafael Auler report(" More calls than expected!\n"); 123616a497c6SRafael Auler }); 123716a497c6SRafael Auler if (Entry.Val <= Entry.Calls) 123816a497c6SRafael Auler return; 123916a497c6SRafael Auler DEBUG(reportNumber( 124016a497c6SRafael Auler " Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10)); 124116a497c6SRafael Auler const IndCallTargetDescription *TargetDesc = 124216a497c6SRafael Auler Ctx->lookupIndCallTarget(Entry.Key); 124316a497c6SRafael Auler if (!TargetDesc) { 124416a497c6SRafael Auler // There is probably something wrong with this callee and this should be 124516a497c6SRafael Auler // investigated, but I don't want to assert and lose all data collected. 124616a497c6SRafael Auler DEBUG(report("WARNING: failed to look up call target!\n")); 124716a497c6SRafael Auler return; 124816a497c6SRafael Auler } 124916a497c6SRafael Auler char LineBuf[BufSize]; 125016a497c6SRafael Auler char *Ptr = LineBuf; 125116a497c6SRafael Auler Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize); 125216a497c6SRafael Auler Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf)); 125316a497c6SRafael Auler Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25); 125416a497c6SRafael Auler Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10); 125516a497c6SRafael Auler *Ptr++ = '\n'; 125616a497c6SRafael Auler __write(FD, LineBuf, Ptr - LineBuf); 125716a497c6SRafael Auler } 125816a497c6SRafael Auler 125916a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting 126016a497c6SRafael Auler /// program upon failure. 126116a497c6SRafael Auler int openProfile() { 126216a497c6SRafael Auler // Build the profile name string by appending our PID 126316a497c6SRafael Auler char Buf[BufSize]; 126416a497c6SRafael Auler char *Ptr = Buf; 126516a497c6SRafael Auler uint64_t PID = __getpid(); 126616a497c6SRafael Auler Ptr = strCopy(Buf, __bolt_instr_filename, BufSize); 126716a497c6SRafael Auler if (__bolt_instr_use_pid) { 126816a497c6SRafael Auler Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1)); 126916a497c6SRafael Auler Ptr = intToStr(Ptr, PID, 10); 127016a497c6SRafael Auler Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1)); 127116a497c6SRafael Auler } 127216a497c6SRafael Auler *Ptr++ = '\0'; 127316a497c6SRafael Auler uint64_t FD = __open(Buf, 127416a497c6SRafael Auler /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/, 127516a497c6SRafael Auler /*mode=*/0666); 127616a497c6SRafael Auler if (static_cast<int64_t>(FD) < 0) { 127716a497c6SRafael Auler report("Error while trying to open profile file for writing: "); 127816a497c6SRafael Auler report(Buf); 127916a497c6SRafael Auler reportNumber("\nFailed with error number: 0x", 128016a497c6SRafael Auler 0 - static_cast<int64_t>(FD), 16); 128116a497c6SRafael Auler __exit(1); 128216a497c6SRafael Auler } 128316a497c6SRafael Auler return FD; 128416a497c6SRafael Auler } 128516a497c6SRafael Auler } // anonymous namespace 128616a497c6SRafael Auler 128716a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your 128816a497c6SRafael Auler /// program independently of prior phases. 128916a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by 129016a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb: 129116a497c6SRafael Auler /// 129216a497c6SRafael Auler /// gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \ 129316a497c6SRafael Auler /// -ex 'set confirm off' -ex quit 129416a497c6SRafael Auler /// 129516a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file 129616a497c6SRafael Auler /// name. 129716a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() { 129816a497c6SRafael Auler memSet(reinterpret_cast<char *>(__bolt_instr_locations), 0, 129916a497c6SRafael Auler __bolt_num_counters * 8); 130016a497c6SRafael Auler for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) { 130116a497c6SRafael Auler GlobalIndCallCounters[I].resetCounters(); 130216a497c6SRafael Auler } 130316a497c6SRafael Auler } 130416a497c6SRafael Auler 130516a497c6SRafael Auler /// This is the entry point for profile writing. 130616a497c6SRafael Auler /// There are three ways of getting here: 130716a497c6SRafael Auler /// 130816a497c6SRafael Auler /// * Program execution ended, finalization methods are running and BOLT 130916a497c6SRafael Auler /// hooked into FINI from your binary dynamic section; 131016a497c6SRafael Auler /// * You used the sleep timer option and during initialization we forked 131116a497c6SRafael Auler /// a separete process that will call this function periodically; 131216a497c6SRafael Auler /// * BOLT prints this function address so you can attach a debugger and 131316a497c6SRafael Auler /// call this function directly to get your profile written to disk 131416a497c6SRafael Auler /// on demand. 131516a497c6SRafael Auler /// 131616a497c6SRafael Auler extern "C" void __bolt_instr_data_dump() { 131716a497c6SRafael Auler // Already dumping 131816a497c6SRafael Auler if (!GlobalWriteProfileMutex->acquire()) 131916a497c6SRafael Auler return; 132016a497c6SRafael Auler 132116a497c6SRafael Auler BumpPtrAllocator HashAlloc; 132216a497c6SRafael Auler HashAlloc.setMaxSize(0x6400000); 132316a497c6SRafael Auler ProfileWriterContext Ctx = readDescriptions(); 132416a497c6SRafael Auler Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc); 132516a497c6SRafael Auler 132616a497c6SRafael Auler DEBUG(printStats(Ctx)); 132716a497c6SRafael Auler 132816a497c6SRafael Auler int FD = openProfile(); 132916a497c6SRafael Auler 1330cc4b2fb6SRafael Auler BumpPtrAllocator Alloc; 133116a497c6SRafael Auler const uint8_t *FuncDesc = Ctx.FuncDescriptions; 1332cc4b2fb6SRafael Auler for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) { 133316a497c6SRafael Auler FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc); 133416a497c6SRafael Auler Alloc.clear(); 1335cc4b2fb6SRafael Auler DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16)); 1336cc4b2fb6SRafael Auler } 133716a497c6SRafael Auler assert(FuncDesc == (void *)Ctx.Strings, 1338cc4b2fb6SRafael Auler "FuncDesc ptr must be equal to stringtable"); 1339cc4b2fb6SRafael Auler 134016a497c6SRafael Auler writeIndirectCallProfile(FD, Ctx); 134116a497c6SRafael Auler Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx); 134216a497c6SRafael Auler 1343821480d2SRafael Auler __close(FD); 134416a497c6SRafael Auler __munmap(Ctx.MMapPtr, Ctx.MMapSize); 134516a497c6SRafael Auler __close(Ctx.FileDesc); 134616a497c6SRafael Auler HashAlloc.destroy(); 134716a497c6SRafael Auler GlobalWriteProfileMutex->release(); 134816a497c6SRafael Auler DEBUG(report("Finished writing profile.\n")); 134916a497c6SRafael Auler } 135016a497c6SRafael Auler 135116a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data 135216a497c6SRafael Auler /// at user-specified intervals 135316a497c6SRafael Auler void watchProcess() { 135416a497c6SRafael Auler timespec ts, rem; 135516a497c6SRafael Auler uint64_t Ellapsed = 0ull; 135616a497c6SRafael Auler ts.tv_sec = 1; 135716a497c6SRafael Auler ts.tv_nsec = 0; 135816a497c6SRafael Auler while (1) { 135916a497c6SRafael Auler __nanosleep(&ts, &rem); 136016a497c6SRafael Auler // This means our parent process died, so no need for us to keep dumping. 136116a497c6SRafael Auler // Notice that make and some systems will wait until all child processes 136216a497c6SRafael Auler // of a command finishes before proceeding, so it is important to exit as 136316a497c6SRafael Auler // early as possible once our parent dies. 136416a497c6SRafael Auler if (__getppid() == 1) { 136516a497c6SRafael Auler break; 136616a497c6SRafael Auler } 136716a497c6SRafael Auler if (++Ellapsed < __bolt_instr_sleep_time) 136816a497c6SRafael Auler continue; 136916a497c6SRafael Auler Ellapsed = 0; 137016a497c6SRafael Auler __bolt_instr_data_dump(); 137116a497c6SRafael Auler __bolt_instr_clear_counters(); 137216a497c6SRafael Auler } 137316a497c6SRafael Auler DEBUG(report("My parent process is dead, bye!\n")); 137416a497c6SRafael Auler __exit(0); 137516a497c6SRafael Auler } 137616a497c6SRafael Auler 137716a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call(); 137816a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall(); 137916a497c6SRafael Auler 138016a497c6SRafael Auler /// Initialization code 138116a497c6SRafael Auler extern "C" void __bolt_instr_setup() { 138216a497c6SRafael Auler const uint64_t CountersStart = 138316a497c6SRafael Auler reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]); 138416a497c6SRafael Auler const uint64_t CountersEnd = alignTo( 138516a497c6SRafael Auler reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]), 138616a497c6SRafael Auler 0x1000); 138716a497c6SRafael Auler DEBUG(reportNumber("replace mmap start: ", CountersStart, 16)); 138816a497c6SRafael Auler DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16)); 138916a497c6SRafael Auler assert (CountersEnd > CountersStart, "no counters"); 139016a497c6SRafael Auler // Maps our counters to be shared instead of private, so we keep counting for 139116a497c6SRafael Auler // forked processes 139216a497c6SRafael Auler __mmap(CountersStart, CountersEnd - CountersStart, 139316a497c6SRafael Auler 0x3 /*PROT_READ|PROT_WRITE*/, 139416a497c6SRafael Auler 0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0); 139516a497c6SRafael Auler 139616a497c6SRafael Auler __bolt_trampoline_ind_call = __bolt_instr_indirect_call; 139716a497c6SRafael Auler __bolt_trampoline_ind_tailcall = __bolt_instr_indirect_tailcall; 139816a497c6SRafael Auler // Conservatively reserve 100MiB shared pages 139916a497c6SRafael Auler GlobalAlloc.setMaxSize(0x6400000); 140016a497c6SRafael Auler GlobalAlloc.setShared(true); 140116a497c6SRafael Auler GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex(); 140216a497c6SRafael Auler if (__bolt_instr_num_ind_calls > 0) 140316a497c6SRafael Auler GlobalIndCallCounters = 140416a497c6SRafael Auler new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls]; 140516a497c6SRafael Auler 140616a497c6SRafael Auler if (__bolt_instr_sleep_time != 0) { 140716a497c6SRafael Auler if (auto PID = __fork()) 140816a497c6SRafael Auler return; 140916a497c6SRafael Auler watchProcess(); 141016a497c6SRafael Auler } 141116a497c6SRafael Auler } 141216a497c6SRafael Auler 141316a497c6SRafael Auler extern "C" void instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) { 141416a497c6SRafael Auler GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc); 141516a497c6SRafael Auler } 141616a497c6SRafael Auler 141716a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site 141816a497c6SRafael Auler /// as well as the target address for the call 141916a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call() 142016a497c6SRafael Auler { 142116a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 1422*c6799a68SRafael Auler "mov 0x90(%%rsp), %%rdi\n" 1423*c6799a68SRafael Auler "mov 0x88(%%rsp), %%rsi\n" 142416a497c6SRafael Auler "call instrumentIndirectCall\n" 142516a497c6SRafael Auler RESTORE_ALL 142616a497c6SRafael Auler "pop %%rdi\n" 142716a497c6SRafael Auler "add $16, %%rsp\n" 142816a497c6SRafael Auler "xchg (%%rsp), %%rdi\n" 142916a497c6SRafael Auler "jmp *-8(%%rsp)\n" 143016a497c6SRafael Auler :::); 143116a497c6SRafael Auler } 143216a497c6SRafael Auler 143316a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall() 143416a497c6SRafael Auler { 143516a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 1436*c6799a68SRafael Auler "mov 0x88(%%rsp), %%rdi\n" 1437*c6799a68SRafael Auler "mov 0x80(%%rsp), %%rsi\n" 143816a497c6SRafael Auler "call instrumentIndirectCall\n" 143916a497c6SRafael Auler RESTORE_ALL 144016a497c6SRafael Auler "add $16, %%rsp\n" 144116a497c6SRafael Auler "pop %%rdi\n" 144216a497c6SRafael Auler "jmp *-16(%%rsp)\n" 144316a497c6SRafael Auler :::); 144416a497c6SRafael Auler } 144516a497c6SRafael Auler 144616a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state. 144716a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start() 144816a497c6SRafael Auler { 144916a497c6SRafael Auler __asm__ __volatile__(SAVE_ALL 145016a497c6SRafael Auler "call __bolt_instr_setup\n" 145116a497c6SRafael Auler RESTORE_ALL 14528c7f524aSAlexander Shaposhnikov "jmp *__bolt_instr_init_ptr(%%rip)\n" 145316a497c6SRafael Auler :::); 145416a497c6SRafael Auler } 145516a497c6SRafael Auler 145616a497c6SRafael Auler /// This is hooking into ELF's DT_FINI 145716a497c6SRafael Auler extern "C" void __bolt_instr_fini() { 145816a497c6SRafael Auler __bolt_instr_fini_ptr(); 145916a497c6SRafael Auler if (__bolt_instr_sleep_time == 0) 146016a497c6SRafael Auler __bolt_instr_data_dump(); 146116a497c6SRafael Auler DEBUG(report("Finished.\n")); 146262aa74f8SRafael Auler } 1463