xref: /llvm-project/bolt/lib/Passes/Instrumentation.cpp (revision 5c4d306a10abc8c607ebfa50d73f008010b902f3)
1 //===- bolt/Passes/Instrumentation.cpp ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Instrumentation class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/Instrumentation.h"
14 #include "bolt/Core/ParallelUtilities.h"
15 #include "bolt/RuntimeLibs/InstrumentationRuntimeLibrary.h"
16 #include "bolt/Utils/Utils.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/RWMutex.h"
19 #include <stack>
20 
21 #define DEBUG_TYPE "bolt-instrumentation"
22 
23 using namespace llvm;
24 
25 namespace opts {
26 extern cl::OptionCategory BoltInstrCategory;
27 
28 cl::opt<std::string> InstrumentationFilename(
29     "instrumentation-file",
30     cl::desc("file name where instrumented profile will be saved (default: "
31              "/tmp/prof.fdata)"),
32     cl::init("/tmp/prof.fdata"), cl::Optional, cl::cat(BoltInstrCategory));
33 
34 cl::opt<std::string> InstrumentationBinpath(
35     "instrumentation-binpath",
36     cl::desc("path to instumented binary in case if /proc/self/map_files "
37              "is not accessible due to access restriction issues"),
38     cl::Optional, cl::cat(BoltInstrCategory));
39 
40 cl::opt<bool> InstrumentationFileAppendPID(
41     "instrumentation-file-append-pid",
42     cl::desc("append PID to saved profile file name (default: false)"),
43     cl::init(false), cl::Optional, cl::cat(BoltInstrCategory));
44 
45 cl::opt<bool> ConservativeInstrumentation(
46     "conservative-instrumentation",
47     cl::desc("disable instrumentation optimizations that sacrifice profile "
48              "accuracy (for debugging, default: false)"),
49     cl::init(false), cl::Optional, cl::cat(BoltInstrCategory));
50 
51 cl::opt<uint32_t> InstrumentationSleepTime(
52     "instrumentation-sleep-time",
53     cl::desc("interval between profile writes (default: 0 = write only at "
54              "program end).  This is useful for service workloads when you "
55              "want to dump profile every X minutes or if you are killing the "
56              "program and the profile is not being dumped at the end."),
57     cl::init(0), cl::Optional, cl::cat(BoltInstrCategory));
58 
59 cl::opt<bool> InstrumentationNoCountersClear(
60     "instrumentation-no-counters-clear",
61     cl::desc("Don't clear counters across dumps "
62              "(use with instrumentation-sleep-time option)"),
63     cl::init(false), cl::Optional, cl::cat(BoltInstrCategory));
64 
65 cl::opt<bool> InstrumentationWaitForks(
66     "instrumentation-wait-forks",
67     cl::desc("Wait until all forks of instrumented process will finish "
68              "(use with instrumentation-sleep-time option)"),
69     cl::init(false), cl::Optional, cl::cat(BoltInstrCategory));
70 
71 cl::opt<bool>
72     InstrumentHotOnly("instrument-hot-only",
73                       cl::desc("only insert instrumentation on hot functions "
74                                "(needs profile, default: false)"),
75                       cl::init(false), cl::Optional,
76                       cl::cat(BoltInstrCategory));
77 
78 cl::opt<bool> InstrumentCalls("instrument-calls",
79                               cl::desc("record profile for inter-function "
80                                        "control flow activity (default: true)"),
81                               cl::init(true), cl::Optional,
82                               cl::cat(BoltInstrCategory));
83 } // namespace opts
84 
85 namespace llvm {
86 namespace bolt {
87 
88 uint32_t Instrumentation::getFunctionNameIndex(const BinaryFunction &Function) {
89   auto Iter = FuncToStringIdx.find(&Function);
90   if (Iter != FuncToStringIdx.end())
91     return Iter->second;
92   size_t Idx = Summary->StringTable.size();
93   FuncToStringIdx.emplace(std::make_pair(&Function, Idx));
94   Summary->StringTable.append(getEscapedName(Function.getOneName()));
95   Summary->StringTable.append(1, '\0');
96   return Idx;
97 }
98 
99 bool Instrumentation::createCallDescription(FunctionDescription &FuncDesc,
100                                             const BinaryFunction &FromFunction,
101                                             uint32_t From, uint32_t FromNodeID,
102                                             const BinaryFunction &ToFunction,
103                                             uint32_t To, bool IsInvoke) {
104   CallDescription CD;
105   // Ordinarily, we don't augment direct calls with an explicit counter, except
106   // when forced to do so or when we know this callee could be throwing
107   // exceptions, in which case there is no other way to accurately record its
108   // frequency.
109   bool ForceInstrumentation = opts::ConservativeInstrumentation || IsInvoke;
110   CD.FromLoc.FuncString = getFunctionNameIndex(FromFunction);
111   CD.FromLoc.Offset = From;
112   CD.FromNode = FromNodeID;
113   CD.Target = &ToFunction;
114   CD.ToLoc.FuncString = getFunctionNameIndex(ToFunction);
115   CD.ToLoc.Offset = To;
116   CD.Counter = ForceInstrumentation ? Summary->Counters.size() : 0xffffffff;
117   if (ForceInstrumentation)
118     ++DirectCallCounters;
119   FuncDesc.Calls.emplace_back(CD);
120   return ForceInstrumentation;
121 }
122 
123 void Instrumentation::createIndCallDescription(
124     const BinaryFunction &FromFunction, uint32_t From) {
125   IndCallDescription ICD;
126   ICD.FromLoc.FuncString = getFunctionNameIndex(FromFunction);
127   ICD.FromLoc.Offset = From;
128   Summary->IndCallDescriptions.emplace_back(ICD);
129 }
130 
131 void Instrumentation::createIndCallTargetDescription(
132     const BinaryFunction &ToFunction, uint32_t To) {
133   IndCallTargetDescription ICD;
134   ICD.ToLoc.FuncString = getFunctionNameIndex(ToFunction);
135   ICD.ToLoc.Offset = To;
136   ICD.Target = &ToFunction;
137   Summary->IndCallTargetDescriptions.emplace_back(ICD);
138 }
139 
140 bool Instrumentation::createEdgeDescription(FunctionDescription &FuncDesc,
141                                             const BinaryFunction &FromFunction,
142                                             uint32_t From, uint32_t FromNodeID,
143                                             const BinaryFunction &ToFunction,
144                                             uint32_t To, uint32_t ToNodeID,
145                                             bool Instrumented) {
146   EdgeDescription ED;
147   auto Result = FuncDesc.EdgesSet.insert(std::make_pair(FromNodeID, ToNodeID));
148   // Avoid creating duplicated edge descriptions. This happens in CFGs where a
149   // block jumps to its fall-through.
150   if (Result.second == false)
151     return false;
152   ED.FromLoc.FuncString = getFunctionNameIndex(FromFunction);
153   ED.FromLoc.Offset = From;
154   ED.FromNode = FromNodeID;
155   ED.ToLoc.FuncString = getFunctionNameIndex(ToFunction);
156   ED.ToLoc.Offset = To;
157   ED.ToNode = ToNodeID;
158   ED.Counter = Instrumented ? Summary->Counters.size() : 0xffffffff;
159   if (Instrumented)
160     ++BranchCounters;
161   FuncDesc.Edges.emplace_back(ED);
162   return Instrumented;
163 }
164 
165 void Instrumentation::createLeafNodeDescription(FunctionDescription &FuncDesc,
166                                                 uint32_t Node) {
167   InstrumentedNode IN;
168   IN.Node = Node;
169   IN.Counter = Summary->Counters.size();
170   ++LeafNodeCounters;
171   FuncDesc.LeafNodes.emplace_back(IN);
172 }
173 
174 InstructionListType
175 Instrumentation::createInstrumentationSnippet(BinaryContext &BC, bool IsLeaf) {
176   auto L = BC.scopeLock();
177   MCSymbol *Label = BC.Ctx->createNamedTempSymbol("InstrEntry");
178   Summary->Counters.emplace_back(Label);
179   return BC.MIB->createInstrIncMemory(Label, BC.Ctx.get(), IsLeaf);
180 }
181 
182 // Helper instruction sequence insertion function
183 static BinaryBasicBlock::iterator
184 insertInstructions(InstructionListType &Instrs, BinaryBasicBlock &BB,
185                    BinaryBasicBlock::iterator Iter) {
186   for (MCInst &NewInst : Instrs) {
187     Iter = BB.insertInstruction(Iter, NewInst);
188     ++Iter;
189   }
190   return Iter;
191 }
192 
193 void Instrumentation::instrumentLeafNode(BinaryBasicBlock &BB,
194                                          BinaryBasicBlock::iterator Iter,
195                                          bool IsLeaf,
196                                          FunctionDescription &FuncDesc,
197                                          uint32_t Node) {
198   createLeafNodeDescription(FuncDesc, Node);
199   InstructionListType CounterInstrs = createInstrumentationSnippet(
200       BB.getFunction()->getBinaryContext(), IsLeaf);
201   insertInstructions(CounterInstrs, BB, Iter);
202 }
203 
204 void Instrumentation::instrumentIndirectTarget(BinaryBasicBlock &BB,
205                                                BinaryBasicBlock::iterator &Iter,
206                                                BinaryFunction &FromFunction,
207                                                uint32_t From) {
208   auto L = FromFunction.getBinaryContext().scopeLock();
209   const size_t IndCallSiteID = Summary->IndCallDescriptions.size();
210   createIndCallDescription(FromFunction, From);
211 
212   BinaryContext &BC = FromFunction.getBinaryContext();
213   bool IsTailCall = BC.MIB->isTailCall(*Iter);
214   InstructionListType CounterInstrs = BC.MIB->createInstrumentedIndirectCall(
215       std::move(*Iter),
216       IsTailCall ? IndTailCallHandlerExitBBFunction->getSymbol()
217                  : IndCallHandlerExitBBFunction->getSymbol(),
218       IndCallSiteID, &*BC.Ctx);
219 
220   Iter = BB.eraseInstruction(Iter);
221   Iter = insertInstructions(CounterInstrs, BB, Iter);
222   --Iter;
223 }
224 
225 bool Instrumentation::instrumentOneTarget(
226     SplitWorklistTy &SplitWorklist, SplitInstrsTy &SplitInstrs,
227     BinaryBasicBlock::iterator &Iter, BinaryFunction &FromFunction,
228     BinaryBasicBlock &FromBB, uint32_t From, BinaryFunction &ToFunc,
229     BinaryBasicBlock *TargetBB, uint32_t ToOffset, bool IsLeaf, bool IsInvoke,
230     FunctionDescription *FuncDesc, uint32_t FromNodeID, uint32_t ToNodeID) {
231   BinaryContext &BC = FromFunction.getBinaryContext();
232   {
233     auto L = BC.scopeLock();
234     bool Created = true;
235     if (!TargetBB)
236       Created = createCallDescription(*FuncDesc, FromFunction, From, FromNodeID,
237                                       ToFunc, ToOffset, IsInvoke);
238     else
239       Created = createEdgeDescription(*FuncDesc, FromFunction, From, FromNodeID,
240                                       ToFunc, ToOffset, ToNodeID,
241                                       /*Instrumented=*/true);
242     if (!Created)
243       return false;
244   }
245 
246   InstructionListType CounterInstrs = createInstrumentationSnippet(BC, IsLeaf);
247 
248   const MCInst &Inst = *Iter;
249   if (BC.MIB->isCall(Inst)) {
250     // This code handles both
251     // - (regular) inter-function calls (cross-function control transfer),
252     // - (rare) intra-function calls (function-local control transfer)
253     Iter = insertInstructions(CounterInstrs, FromBB, Iter);
254     return true;
255   }
256 
257   if (!TargetBB || !FuncDesc)
258     return false;
259 
260   // Indirect branch, conditional branches or fall-throughs
261   // Regular cond branch, put counter at start of target block
262   //
263   // N.B.: (FromBB != TargetBBs) checks below handle conditional jumps where
264   // we can't put the instrumentation counter in this block because not all
265   // paths that reach it at this point will be taken and going to the target.
266   if (TargetBB->pred_size() == 1 && &FromBB != TargetBB &&
267       !TargetBB->isEntryPoint()) {
268     insertInstructions(CounterInstrs, *TargetBB, TargetBB->begin());
269     return true;
270   }
271   if (FromBB.succ_size() == 1 && &FromBB != TargetBB) {
272     Iter = insertInstructions(CounterInstrs, FromBB, Iter);
273     return true;
274   }
275   // Critical edge, create BB and put counter there
276   SplitWorklist.emplace_back(&FromBB, TargetBB);
277   SplitInstrs.emplace_back(std::move(CounterInstrs));
278   return true;
279 }
280 
281 void Instrumentation::instrumentFunction(BinaryFunction &Function,
282                                          MCPlusBuilder::AllocatorIdTy AllocId) {
283   if (Function.hasUnknownControlFlow())
284     return;
285 
286   BinaryContext &BC = Function.getBinaryContext();
287   if (BC.isMachO() && Function.hasName("___GLOBAL_init_65535/1"))
288     return;
289 
290   SplitWorklistTy SplitWorklist;
291   SplitInstrsTy SplitInstrs;
292 
293   FunctionDescription *FuncDesc = nullptr;
294   {
295     std::unique_lock<llvm::sys::RWMutex> L(FDMutex);
296     Summary->FunctionDescriptions.emplace_back();
297     FuncDesc = &Summary->FunctionDescriptions.back();
298   }
299 
300   FuncDesc->Function = &Function;
301   Function.disambiguateJumpTables(AllocId);
302   Function.deleteConservativeEdges();
303 
304   std::unordered_map<const BinaryBasicBlock *, uint32_t> BBToID;
305   uint32_t Id = 0;
306   for (auto BBI = Function.begin(); BBI != Function.end(); ++BBI) {
307     BBToID[&*BBI] = Id++;
308   }
309   std::unordered_set<const BinaryBasicBlock *> VisitedSet;
310   // DFS to establish edges we will use for a spanning tree. Edges in the
311   // spanning tree can be instrumentation-free since their count can be
312   // inferred by solving flow equations on a bottom-up traversal of the tree.
313   // Exit basic blocks are always instrumented so we start the traversal with
314   // a minimum number of defined variables to make the equation solvable.
315   std::stack<std::pair<const BinaryBasicBlock *, BinaryBasicBlock *>> Stack;
316   std::unordered_map<const BinaryBasicBlock *,
317                      std::set<const BinaryBasicBlock *>>
318       STOutSet;
319   for (auto BBI = Function.getLayout().block_rbegin();
320        BBI != Function.getLayout().block_rend(); ++BBI) {
321     if ((*BBI)->isEntryPoint() || (*BBI)->isLandingPad()) {
322       Stack.push(std::make_pair(nullptr, *BBI));
323       if (opts::InstrumentCalls && (*BBI)->isEntryPoint()) {
324         EntryNode E;
325         E.Node = BBToID[&**BBI];
326         E.Address = (*BBI)->getInputOffset();
327         FuncDesc->EntryNodes.emplace_back(E);
328         createIndCallTargetDescription(Function, (*BBI)->getInputOffset());
329       }
330     }
331   }
332 
333   // Modified version of BinaryFunction::dfs() to build a spanning tree
334   if (!opts::ConservativeInstrumentation) {
335     while (!Stack.empty()) {
336       BinaryBasicBlock *BB;
337       const BinaryBasicBlock *Pred;
338       std::tie(Pred, BB) = Stack.top();
339       Stack.pop();
340       if (llvm::is_contained(VisitedSet, BB))
341         continue;
342 
343       VisitedSet.insert(BB);
344       if (Pred)
345         STOutSet[Pred].insert(BB);
346 
347       for (BinaryBasicBlock *SuccBB : BB->successors())
348         Stack.push(std::make_pair(BB, SuccBB));
349     }
350   }
351 
352   // Determine whether this is a leaf function, which needs special
353   // instructions to protect the red zone
354   bool IsLeafFunction = true;
355   DenseSet<const BinaryBasicBlock *> InvokeBlocks;
356   for (const BinaryBasicBlock &BB : Function) {
357     for (const MCInst &Inst : BB) {
358       if (BC.MIB->isCall(Inst)) {
359         if (BC.MIB->isInvoke(Inst))
360           InvokeBlocks.insert(&BB);
361         if (!BC.MIB->isTailCall(Inst))
362           IsLeafFunction = false;
363       }
364     }
365   }
366 
367   for (auto BBI = Function.begin(), BBE = Function.end(); BBI != BBE; ++BBI) {
368     BinaryBasicBlock &BB = *BBI;
369     bool HasUnconditionalBranch = false;
370     bool HasJumpTable = false;
371     bool IsInvokeBlock = InvokeBlocks.count(&BB) > 0;
372 
373     for (auto I = BB.begin(); I != BB.end(); ++I) {
374       const MCInst &Inst = *I;
375       if (!BC.MIB->getOffset(Inst))
376         continue;
377 
378       const bool IsJumpTable = Function.getJumpTable(Inst);
379       if (IsJumpTable)
380         HasJumpTable = true;
381       else if (BC.MIB->isUnconditionalBranch(Inst))
382         HasUnconditionalBranch = true;
383       else if ((!BC.MIB->isCall(Inst) && !BC.MIB->isConditionalBranch(Inst)) ||
384                BC.MIB->isUnsupportedBranch(Inst))
385         continue;
386 
387       const uint32_t FromOffset = *BC.MIB->getOffset(Inst);
388       const MCSymbol *Target = BC.MIB->getTargetSymbol(Inst);
389       BinaryBasicBlock *TargetBB = Function.getBasicBlockForLabel(Target);
390       uint32_t ToOffset = TargetBB ? TargetBB->getInputOffset() : 0;
391       BinaryFunction *TargetFunc =
392           TargetBB ? &Function : BC.getFunctionForSymbol(Target);
393       if (TargetFunc && BC.MIB->isCall(Inst)) {
394         if (opts::InstrumentCalls) {
395           const BinaryBasicBlock *ForeignBB =
396               TargetFunc->getBasicBlockForLabel(Target);
397           if (ForeignBB)
398             ToOffset = ForeignBB->getInputOffset();
399           instrumentOneTarget(SplitWorklist, SplitInstrs, I, Function, BB,
400                               FromOffset, *TargetFunc, TargetBB, ToOffset,
401                               IsLeafFunction, IsInvokeBlock, FuncDesc,
402                               BBToID[&BB]);
403         }
404         continue;
405       }
406       if (TargetFunc) {
407         // Do not instrument edges in the spanning tree
408         if (llvm::is_contained(STOutSet[&BB], TargetBB)) {
409           auto L = BC.scopeLock();
410           createEdgeDescription(*FuncDesc, Function, FromOffset, BBToID[&BB],
411                                 Function, ToOffset, BBToID[TargetBB],
412                                 /*Instrumented=*/false);
413           continue;
414         }
415         instrumentOneTarget(SplitWorklist, SplitInstrs, I, Function, BB,
416                             FromOffset, *TargetFunc, TargetBB, ToOffset,
417                             IsLeafFunction, IsInvokeBlock, FuncDesc,
418                             BBToID[&BB], BBToID[TargetBB]);
419         continue;
420       }
421 
422       if (IsJumpTable) {
423         for (BinaryBasicBlock *&Succ : BB.successors()) {
424           // Do not instrument edges in the spanning tree
425           if (llvm::is_contained(STOutSet[&BB], &*Succ)) {
426             auto L = BC.scopeLock();
427             createEdgeDescription(*FuncDesc, Function, FromOffset, BBToID[&BB],
428                                   Function, Succ->getInputOffset(),
429                                   BBToID[&*Succ], /*Instrumented=*/false);
430             continue;
431           }
432           instrumentOneTarget(
433               SplitWorklist, SplitInstrs, I, Function, BB, FromOffset, Function,
434               &*Succ, Succ->getInputOffset(), IsLeafFunction, IsInvokeBlock,
435               FuncDesc, BBToID[&BB], BBToID[&*Succ]);
436         }
437         continue;
438       }
439 
440       // Handle indirect calls -- could be direct calls with unknown targets
441       // or secondary entry points of known functions, so check it is indirect
442       // to be sure.
443       if (opts::InstrumentCalls && BC.MIB->isIndirectCall(*I))
444         instrumentIndirectTarget(BB, I, Function, FromOffset);
445 
446     } // End of instructions loop
447 
448     // Instrument fallthroughs (when the direct jump instruction is missing)
449     if (!HasUnconditionalBranch && !HasJumpTable && BB.succ_size() > 0 &&
450         BB.size() > 0) {
451       BinaryBasicBlock *FTBB = BB.getFallthrough();
452       assert(FTBB && "expected valid fall-through basic block");
453       auto I = BB.begin();
454       auto LastInstr = BB.end();
455       --LastInstr;
456       while (LastInstr != I && BC.MIB->isPseudo(*LastInstr))
457         --LastInstr;
458       uint32_t FromOffset = 0;
459       // The last instruction in the BB should have an annotation, except
460       // if it was branching to the end of the function as a result of
461       // __builtin_unreachable(), in which case it was deleted by fixBranches.
462       // Ignore this case. FIXME: force fixBranches() to preserve the offset.
463       if (!BC.MIB->getOffset(*LastInstr))
464         continue;
465       FromOffset = *BC.MIB->getOffset(*LastInstr);
466 
467       // Do not instrument edges in the spanning tree
468       if (llvm::is_contained(STOutSet[&BB], FTBB)) {
469         auto L = BC.scopeLock();
470         createEdgeDescription(*FuncDesc, Function, FromOffset, BBToID[&BB],
471                               Function, FTBB->getInputOffset(), BBToID[FTBB],
472                               /*Instrumented=*/false);
473         continue;
474       }
475       instrumentOneTarget(SplitWorklist, SplitInstrs, I, Function, BB,
476                           FromOffset, Function, FTBB, FTBB->getInputOffset(),
477                           IsLeafFunction, IsInvokeBlock, FuncDesc, BBToID[&BB],
478                           BBToID[FTBB]);
479     }
480   } // End of BBs loop
481 
482   // Instrument spanning tree leaves
483   if (!opts::ConservativeInstrumentation) {
484     for (auto BBI = Function.begin(), BBE = Function.end(); BBI != BBE; ++BBI) {
485       BinaryBasicBlock &BB = *BBI;
486       if (STOutSet[&BB].size() == 0)
487         instrumentLeafNode(BB, BB.begin(), IsLeafFunction, *FuncDesc,
488                            BBToID[&BB]);
489     }
490   }
491 
492   // Consume list of critical edges: split them and add instrumentation to the
493   // newly created BBs
494   auto Iter = SplitInstrs.begin();
495   for (std::pair<BinaryBasicBlock *, BinaryBasicBlock *> &BBPair :
496        SplitWorklist) {
497     BinaryBasicBlock *NewBB = Function.splitEdge(BBPair.first, BBPair.second);
498     NewBB->addInstructions(Iter->begin(), Iter->end());
499     ++Iter;
500   }
501 
502   // Unused now
503   FuncDesc->EdgesSet.clear();
504 }
505 
506 void Instrumentation::runOnFunctions(BinaryContext &BC) {
507   if (!BC.isX86())
508     return;
509 
510   const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/false,
511                                                  /*IsText=*/false,
512                                                  /*IsAllocatable=*/true);
513   BC.registerOrUpdateSection(".bolt.instr.counters", ELF::SHT_PROGBITS, Flags,
514                              nullptr, 0, 1);
515 
516   BC.registerOrUpdateNoteSection(".bolt.instr.tables", nullptr, 0,
517                                  /*Alignment=*/1,
518                                  /*IsReadOnly=*/true, ELF::SHT_NOTE);
519 
520   Summary->IndCallCounterFuncPtr =
521       BC.Ctx->getOrCreateSymbol("__bolt_ind_call_counter_func_pointer");
522   Summary->IndTailCallCounterFuncPtr =
523       BC.Ctx->getOrCreateSymbol("__bolt_ind_tailcall_counter_func_pointer");
524 
525   createAuxiliaryFunctions(BC);
526 
527   ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
528     return (!BF.isSimple() || BF.isIgnored() ||
529             (opts::InstrumentHotOnly && !BF.getKnownExecutionCount()));
530   };
531 
532   ParallelUtilities::WorkFuncWithAllocTy WorkFun =
533       [&](BinaryFunction &BF, MCPlusBuilder::AllocatorIdTy AllocatorId) {
534         instrumentFunction(BF, AllocatorId);
535       };
536 
537   ParallelUtilities::runOnEachFunctionWithUniqueAllocId(
538       BC, ParallelUtilities::SchedulingPolicy::SP_INST_QUADRATIC, WorkFun,
539       SkipPredicate, "instrumentation", /* ForceSequential=*/true);
540 
541   if (BC.isMachO()) {
542     if (BC.StartFunctionAddress) {
543       BinaryFunction *Main =
544           BC.getBinaryFunctionAtAddress(*BC.StartFunctionAddress);
545       assert(Main && "Entry point function not found");
546       BinaryBasicBlock &BB = Main->front();
547 
548       ErrorOr<BinarySection &> SetupSection =
549           BC.getUniqueSectionByName("I__setup");
550       if (!SetupSection) {
551         llvm::errs() << "Cannot find I__setup section\n";
552         exit(1);
553       }
554       MCSymbol *Target = BC.registerNameAtAddress(
555           "__bolt_instr_setup", SetupSection->getAddress(), 0, 0);
556       MCInst NewInst;
557       BC.MIB->createCall(NewInst, Target, BC.Ctx.get());
558       BB.insertInstruction(BB.begin(), std::move(NewInst));
559     } else {
560       llvm::errs() << "BOLT-WARNING: Entry point not found\n";
561     }
562 
563     if (BinaryData *BD = BC.getBinaryDataByName("___GLOBAL_init_65535/1")) {
564       BinaryFunction *Ctor = BC.getBinaryFunctionAtAddress(BD->getAddress());
565       assert(Ctor && "___GLOBAL_init_65535 function not found");
566       BinaryBasicBlock &BB = Ctor->front();
567       ErrorOr<BinarySection &> FiniSection =
568           BC.getUniqueSectionByName("I__fini");
569       if (!FiniSection) {
570         llvm::errs() << "Cannot find I__fini section\n";
571         exit(1);
572       }
573       MCSymbol *Target = BC.registerNameAtAddress(
574           "__bolt_instr_fini", FiniSection->getAddress(), 0, 0);
575       auto IsLEA = [&BC](const MCInst &Inst) { return BC.MIB->isLEA64r(Inst); };
576       const auto LEA = std::find_if(
577           std::next(llvm::find_if(reverse(BB), IsLEA)), BB.rend(), IsLEA);
578       LEA->getOperand(4).setExpr(
579           MCSymbolRefExpr::create(Target, MCSymbolRefExpr::VK_None, *BC.Ctx));
580     } else {
581       llvm::errs() << "BOLT-WARNING: ___GLOBAL_init_65535 not found\n";
582     }
583   }
584 
585   setupRuntimeLibrary(BC);
586 }
587 
588 void Instrumentation::createAuxiliaryFunctions(BinaryContext &BC) {
589   auto createSimpleFunction =
590       [&](StringRef Title, InstructionListType Instrs) -> BinaryFunction * {
591     BinaryFunction *Func = BC.createInjectedBinaryFunction(std::string(Title));
592 
593     std::vector<std::unique_ptr<BinaryBasicBlock>> BBs;
594     BBs.emplace_back(Func->createBasicBlock());
595     BBs.back()->addInstructions(Instrs.begin(), Instrs.end());
596     BBs.back()->setCFIState(0);
597     Func->insertBasicBlocks(nullptr, std::move(BBs),
598                             /*UpdateLayout=*/true,
599                             /*UpdateCFIState=*/false);
600     Func->updateState(BinaryFunction::State::CFG_Finalized);
601     return Func;
602   };
603 
604   // Here we are creating a set of functions to handle BB entry/exit.
605   // IndCallHandlerExitBB contains instructions to finish handling traffic to an
606   // indirect call. We pass it to createInstrumentedIndCallHandlerEntryBB(),
607   // which will check if a pointer to runtime library traffic accounting
608   // function was initialized (it is done during initialization of runtime
609   // library). If it is so - calls it. Then this routine returns to normal
610   // execution by jumping to exit BB.
611   BinaryFunction *IndCallHandlerExitBB =
612       createSimpleFunction("__bolt_instr_ind_call_handler",
613                            BC.MIB->createInstrumentedIndCallHandlerExitBB());
614 
615   IndCallHandlerExitBBFunction =
616       createSimpleFunction("__bolt_instr_ind_call_handler_func",
617                            BC.MIB->createInstrumentedIndCallHandlerEntryBB(
618                                Summary->IndCallCounterFuncPtr,
619                                IndCallHandlerExitBB->getSymbol(), &*BC.Ctx));
620 
621   BinaryFunction *IndTailCallHandlerExitBB = createSimpleFunction(
622       "__bolt_instr_ind_tail_call_handler",
623       BC.MIB->createInstrumentedIndTailCallHandlerExitBB());
624 
625   IndTailCallHandlerExitBBFunction = createSimpleFunction(
626       "__bolt_instr_ind_tailcall_handler_func",
627       BC.MIB->createInstrumentedIndCallHandlerEntryBB(
628           Summary->IndTailCallCounterFuncPtr,
629           IndTailCallHandlerExitBB->getSymbol(), &*BC.Ctx));
630 
631   createSimpleFunction("__bolt_num_counters_getter",
632                        BC.MIB->createNumCountersGetter(BC.Ctx.get()));
633   createSimpleFunction("__bolt_instr_locations_getter",
634                        BC.MIB->createInstrLocationsGetter(BC.Ctx.get()));
635   createSimpleFunction("__bolt_instr_tables_getter",
636                        BC.MIB->createInstrTablesGetter(BC.Ctx.get()));
637   createSimpleFunction("__bolt_instr_num_funcs_getter",
638                        BC.MIB->createInstrNumFuncsGetter(BC.Ctx.get()));
639 
640   if (BC.isELF()) {
641     if (BC.StartFunctionAddress) {
642       BinaryFunction *Start =
643           BC.getBinaryFunctionAtAddress(*BC.StartFunctionAddress);
644       assert(Start && "Entry point function not found");
645       const MCSymbol *StartSym = Start->getSymbol();
646       createSimpleFunction(
647           "__bolt_start_trampoline",
648           BC.MIB->createSymbolTrampoline(StartSym, BC.Ctx.get()));
649     }
650     if (BC.FiniFunctionAddress) {
651       BinaryFunction *Fini =
652           BC.getBinaryFunctionAtAddress(*BC.FiniFunctionAddress);
653       assert(Fini && "Finalization function not found");
654       const MCSymbol *FiniSym = Fini->getSymbol();
655       createSimpleFunction(
656           "__bolt_fini_trampoline",
657           BC.MIB->createSymbolTrampoline(FiniSym, BC.Ctx.get()));
658     } else {
659       // Create dummy return function for trampoline to avoid issues
660       // with unknown symbol in runtime library. E.g. for static PIE
661       // executable
662       createSimpleFunction("__bolt_fini_trampoline",
663                            BC.MIB->createDummyReturnFunction(BC.Ctx.get()));
664     }
665   }
666 }
667 
668 void Instrumentation::setupRuntimeLibrary(BinaryContext &BC) {
669   uint32_t FuncDescSize = Summary->getFDSize();
670 
671   outs() << "BOLT-INSTRUMENTER: Number of indirect call site descriptors: "
672          << Summary->IndCallDescriptions.size() << "\n";
673   outs() << "BOLT-INSTRUMENTER: Number of indirect call target descriptors: "
674          << Summary->IndCallTargetDescriptions.size() << "\n";
675   outs() << "BOLT-INSTRUMENTER: Number of function descriptors: "
676          << Summary->FunctionDescriptions.size() << "\n";
677   outs() << "BOLT-INSTRUMENTER: Number of branch counters: " << BranchCounters
678          << "\n";
679   outs() << "BOLT-INSTRUMENTER: Number of ST leaf node counters: "
680          << LeafNodeCounters << "\n";
681   outs() << "BOLT-INSTRUMENTER: Number of direct call counters: "
682          << DirectCallCounters << "\n";
683   outs() << "BOLT-INSTRUMENTER: Total number of counters: "
684          << Summary->Counters.size() << "\n";
685   outs() << "BOLT-INSTRUMENTER: Total size of counters: "
686          << (Summary->Counters.size() * 8) << " bytes (static alloc memory)\n";
687   outs() << "BOLT-INSTRUMENTER: Total size of string table emitted: "
688          << Summary->StringTable.size() << " bytes in file\n";
689   outs() << "BOLT-INSTRUMENTER: Total size of descriptors: "
690          << (FuncDescSize +
691              Summary->IndCallDescriptions.size() * sizeof(IndCallDescription) +
692              Summary->IndCallTargetDescriptions.size() *
693                  sizeof(IndCallTargetDescription))
694          << " bytes in file\n";
695   outs() << "BOLT-INSTRUMENTER: Profile will be saved to file "
696          << opts::InstrumentationFilename << "\n";
697 
698   InstrumentationRuntimeLibrary *RtLibrary =
699       static_cast<InstrumentationRuntimeLibrary *>(BC.getRuntimeLibrary());
700   assert(RtLibrary && "instrumentation runtime library object must be set");
701   RtLibrary->setSummary(std::move(Summary));
702 }
703 } // namespace bolt
704 } // namespace llvm
705