xref: /llvm-project/bolt/lib/Passes/Instrumentation.cpp (revision 1e1dfbb94a20d81693176d885b5f773072bf0786)
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;
178   Label = BC.Ctx->createNamedTempSymbol("InstrEntry");
179   Summary->Counters.emplace_back(Label);
180   InstructionListType CounterInstrs;
181   BC.MIB->createInstrIncMemory(CounterInstrs, Label, &*BC.Ctx, IsLeaf);
182   return CounterInstrs;
183 }
184 
185 // Helper instruction sequence insertion function
186 static BinaryBasicBlock::iterator
187 insertInstructions(InstructionListType &Instrs, BinaryBasicBlock &BB,
188                    BinaryBasicBlock::iterator Iter) {
189   for (MCInst &NewInst : Instrs) {
190     Iter = BB.insertInstruction(Iter, NewInst);
191     ++Iter;
192   }
193   return Iter;
194 }
195 
196 void Instrumentation::instrumentLeafNode(BinaryBasicBlock &BB,
197                                          BinaryBasicBlock::iterator Iter,
198                                          bool IsLeaf,
199                                          FunctionDescription &FuncDesc,
200                                          uint32_t Node) {
201   createLeafNodeDescription(FuncDesc, Node);
202   InstructionListType CounterInstrs = createInstrumentationSnippet(
203       BB.getFunction()->getBinaryContext(), IsLeaf);
204   insertInstructions(CounterInstrs, BB, Iter);
205 }
206 
207 void Instrumentation::instrumentIndirectTarget(BinaryBasicBlock &BB,
208                                                BinaryBasicBlock::iterator &Iter,
209                                                BinaryFunction &FromFunction,
210                                                uint32_t From) {
211   auto L = FromFunction.getBinaryContext().scopeLock();
212   const size_t IndCallSiteID = Summary->IndCallDescriptions.size();
213   createIndCallDescription(FromFunction, From);
214 
215   BinaryContext &BC = FromFunction.getBinaryContext();
216   bool IsTailCall = BC.MIB->isTailCall(*Iter);
217   InstructionListType CounterInstrs = BC.MIB->createInstrumentedIndirectCall(
218       std::move(*Iter),
219       IsTailCall ? IndTailCallHandlerExitBBFunction->getSymbol()
220                  : IndCallHandlerExitBBFunction->getSymbol(),
221       IndCallSiteID, &*BC.Ctx);
222 
223   Iter = BB.eraseInstruction(Iter);
224   Iter = insertInstructions(CounterInstrs, BB, Iter);
225   --Iter;
226 }
227 
228 bool Instrumentation::instrumentOneTarget(
229     SplitWorklistTy &SplitWorklist, SplitInstrsTy &SplitInstrs,
230     BinaryBasicBlock::iterator &Iter, BinaryFunction &FromFunction,
231     BinaryBasicBlock &FromBB, uint32_t From, BinaryFunction &ToFunc,
232     BinaryBasicBlock *TargetBB, uint32_t ToOffset, bool IsLeaf, bool IsInvoke,
233     FunctionDescription *FuncDesc, uint32_t FromNodeID, uint32_t ToNodeID) {
234   {
235     auto L = FromFunction.getBinaryContext().scopeLock();
236     bool Created = true;
237     if (!TargetBB)
238       Created = createCallDescription(*FuncDesc, FromFunction, From, FromNodeID,
239                                       ToFunc, ToOffset, IsInvoke);
240     else
241       Created = createEdgeDescription(*FuncDesc, FromFunction, From, FromNodeID,
242                                       ToFunc, ToOffset, ToNodeID,
243                                       /*Instrumented=*/true);
244     if (!Created)
245       return false;
246   }
247 
248   InstructionListType CounterInstrs =
249       createInstrumentationSnippet(FromFunction.getBinaryContext(), IsLeaf);
250 
251   BinaryContext &BC = FromFunction.getBinaryContext();
252   const MCInst &Inst = *Iter;
253   if (BC.MIB->isCall(Inst)) {
254     // This code handles both
255     // - (regular) inter-function calls (cross-function control transfer),
256     // - (rare) intra-function calls (function-local control transfer)
257     Iter = insertInstructions(CounterInstrs, FromBB, Iter);
258     return true;
259   }
260 
261   if (!TargetBB || !FuncDesc)
262     return false;
263 
264   // Indirect branch, conditional branches or fall-throughs
265   // Regular cond branch, put counter at start of target block
266   //
267   // N.B.: (FromBB != TargetBBs) checks below handle conditional jumps where
268   // we can't put the instrumentation counter in this block because not all
269   // paths that reach it at this point will be taken and going to the target.
270   if (TargetBB->pred_size() == 1 && &FromBB != TargetBB &&
271       !TargetBB->isEntryPoint()) {
272     insertInstructions(CounterInstrs, *TargetBB, TargetBB->begin());
273     return true;
274   }
275   if (FromBB.succ_size() == 1 && &FromBB != TargetBB) {
276     Iter = insertInstructions(CounterInstrs, FromBB, Iter);
277     return true;
278   }
279   // Critical edge, create BB and put counter there
280   SplitWorklist.emplace_back(&FromBB, TargetBB);
281   SplitInstrs.emplace_back(std::move(CounterInstrs));
282   return true;
283 }
284 
285 void Instrumentation::instrumentFunction(BinaryFunction &Function,
286                                          MCPlusBuilder::AllocatorIdTy AllocId) {
287   if (Function.hasUnknownControlFlow())
288     return;
289 
290   BinaryContext &BC = Function.getBinaryContext();
291   if (BC.isMachO() && Function.hasName("___GLOBAL_init_65535/1"))
292     return;
293 
294   SplitWorklistTy SplitWorklist;
295   SplitInstrsTy SplitInstrs;
296 
297   FunctionDescription *FuncDesc = nullptr;
298   {
299     std::unique_lock<llvm::sys::RWMutex> L(FDMutex);
300     Summary->FunctionDescriptions.emplace_back();
301     FuncDesc = &Summary->FunctionDescriptions.back();
302   }
303 
304   FuncDesc->Function = &Function;
305   Function.disambiguateJumpTables(AllocId);
306   Function.deleteConservativeEdges();
307 
308   std::unordered_map<const BinaryBasicBlock *, uint32_t> BBToID;
309   uint32_t Id = 0;
310   for (auto BBI = Function.begin(); BBI != Function.end(); ++BBI) {
311     BBToID[&*BBI] = Id++;
312   }
313   std::unordered_set<const BinaryBasicBlock *> VisitedSet;
314   // DFS to establish edges we will use for a spanning tree. Edges in the
315   // spanning tree can be instrumentation-free since their count can be
316   // inferred by solving flow equations on a bottom-up traversal of the tree.
317   // Exit basic blocks are always instrumented so we start the traversal with
318   // a minimum number of defined variables to make the equation solvable.
319   std::stack<std::pair<const BinaryBasicBlock *, BinaryBasicBlock *>> Stack;
320   std::unordered_map<const BinaryBasicBlock *,
321                      std::set<const BinaryBasicBlock *>>
322       STOutSet;
323   for (auto BBI = Function.getLayout().block_rbegin();
324        BBI != Function.getLayout().block_rend(); ++BBI) {
325     if ((*BBI)->isEntryPoint() || (*BBI)->isLandingPad()) {
326       Stack.push(std::make_pair(nullptr, *BBI));
327       if (opts::InstrumentCalls && (*BBI)->isEntryPoint()) {
328         EntryNode E;
329         E.Node = BBToID[&**BBI];
330         E.Address = (*BBI)->getInputOffset();
331         FuncDesc->EntryNodes.emplace_back(E);
332         createIndCallTargetDescription(Function, (*BBI)->getInputOffset());
333       }
334     }
335   }
336 
337   // Modified version of BinaryFunction::dfs() to build a spanning tree
338   if (!opts::ConservativeInstrumentation) {
339     while (!Stack.empty()) {
340       BinaryBasicBlock *BB;
341       const BinaryBasicBlock *Pred;
342       std::tie(Pred, BB) = Stack.top();
343       Stack.pop();
344       if (VisitedSet.find(BB) != VisitedSet.end())
345         continue;
346 
347       VisitedSet.insert(BB);
348       if (Pred)
349         STOutSet[Pred].insert(BB);
350 
351       for (BinaryBasicBlock *SuccBB : BB->successors())
352         Stack.push(std::make_pair(BB, SuccBB));
353     }
354   }
355 
356   // Determine whether this is a leaf function, which needs special
357   // instructions to protect the red zone
358   bool IsLeafFunction = true;
359   DenseSet<const BinaryBasicBlock *> InvokeBlocks;
360   for (const BinaryBasicBlock &BB : Function) {
361     for (const MCInst &Inst : BB) {
362       if (BC.MIB->isCall(Inst)) {
363         if (BC.MIB->isInvoke(Inst))
364           InvokeBlocks.insert(&BB);
365         if (!BC.MIB->isTailCall(Inst))
366           IsLeafFunction = false;
367       }
368     }
369   }
370 
371   for (auto BBI = Function.begin(), BBE = Function.end(); BBI != BBE; ++BBI) {
372     BinaryBasicBlock &BB = *BBI;
373     bool HasUnconditionalBranch = false;
374     bool HasJumpTable = false;
375     bool IsInvokeBlock = InvokeBlocks.count(&BB) > 0;
376 
377     for (auto I = BB.begin(); I != BB.end(); ++I) {
378       const MCInst &Inst = *I;
379       if (!BC.MIB->getOffset(Inst))
380         continue;
381 
382       const bool IsJumpTable = Function.getJumpTable(Inst);
383       if (IsJumpTable)
384         HasJumpTable = true;
385       else if (BC.MIB->isUnconditionalBranch(Inst))
386         HasUnconditionalBranch = true;
387       else if ((!BC.MIB->isCall(Inst) && !BC.MIB->isConditionalBranch(Inst)) ||
388                BC.MIB->isUnsupportedBranch(Inst.getOpcode()))
389         continue;
390 
391       const uint32_t FromOffset = *BC.MIB->getOffset(Inst);
392       const MCSymbol *Target = BC.MIB->getTargetSymbol(Inst);
393       BinaryBasicBlock *TargetBB = Function.getBasicBlockForLabel(Target);
394       uint32_t ToOffset = TargetBB ? TargetBB->getInputOffset() : 0;
395       BinaryFunction *TargetFunc =
396           TargetBB ? &Function : BC.getFunctionForSymbol(Target);
397       if (TargetFunc && BC.MIB->isCall(Inst)) {
398         if (opts::InstrumentCalls) {
399           const BinaryBasicBlock *ForeignBB =
400               TargetFunc->getBasicBlockForLabel(Target);
401           if (ForeignBB)
402             ToOffset = ForeignBB->getInputOffset();
403           instrumentOneTarget(SplitWorklist, SplitInstrs, I, Function, BB,
404                               FromOffset, *TargetFunc, TargetBB, ToOffset,
405                               IsLeafFunction, IsInvokeBlock, FuncDesc,
406                               BBToID[&BB]);
407         }
408         continue;
409       }
410       if (TargetFunc) {
411         // Do not instrument edges in the spanning tree
412         if (STOutSet[&BB].find(TargetBB) != STOutSet[&BB].end()) {
413           auto L = BC.scopeLock();
414           createEdgeDescription(*FuncDesc, Function, FromOffset, BBToID[&BB],
415                                 Function, ToOffset, BBToID[TargetBB],
416                                 /*Instrumented=*/false);
417           continue;
418         }
419         instrumentOneTarget(SplitWorklist, SplitInstrs, I, Function, BB,
420                             FromOffset, *TargetFunc, TargetBB, ToOffset,
421                             IsLeafFunction, IsInvokeBlock, FuncDesc,
422                             BBToID[&BB], BBToID[TargetBB]);
423         continue;
424       }
425 
426       if (IsJumpTable) {
427         for (BinaryBasicBlock *&Succ : BB.successors()) {
428           // Do not instrument edges in the spanning tree
429           if (STOutSet[&BB].find(&*Succ) != STOutSet[&BB].end()) {
430             auto L = BC.scopeLock();
431             createEdgeDescription(*FuncDesc, Function, FromOffset, BBToID[&BB],
432                                   Function, Succ->getInputOffset(),
433                                   BBToID[&*Succ], /*Instrumented=*/false);
434             continue;
435           }
436           instrumentOneTarget(
437               SplitWorklist, SplitInstrs, I, Function, BB, FromOffset, Function,
438               &*Succ, Succ->getInputOffset(), IsLeafFunction, IsInvokeBlock,
439               FuncDesc, BBToID[&BB], BBToID[&*Succ]);
440         }
441         continue;
442       }
443 
444       // Handle indirect calls -- could be direct calls with unknown targets
445       // or secondary entry points of known functions, so check it is indirect
446       // to be sure.
447       if (opts::InstrumentCalls && BC.MIB->isIndirectCall(*I))
448         instrumentIndirectTarget(BB, I, Function, FromOffset);
449 
450     } // End of instructions loop
451 
452     // Instrument fallthroughs (when the direct jump instruction is missing)
453     if (!HasUnconditionalBranch && !HasJumpTable && BB.succ_size() > 0 &&
454         BB.size() > 0) {
455       BinaryBasicBlock *FTBB = BB.getFallthrough();
456       assert(FTBB && "expected valid fall-through basic block");
457       auto I = BB.begin();
458       auto LastInstr = BB.end();
459       --LastInstr;
460       while (LastInstr != I && BC.MIB->isPseudo(*LastInstr))
461         --LastInstr;
462       uint32_t FromOffset = 0;
463       // The last instruction in the BB should have an annotation, except
464       // if it was branching to the end of the function as a result of
465       // __builtin_unreachable(), in which case it was deleted by fixBranches.
466       // Ignore this case. FIXME: force fixBranches() to preserve the offset.
467       if (!BC.MIB->getOffset(*LastInstr))
468         continue;
469       FromOffset = *BC.MIB->getOffset(*LastInstr);
470 
471       // Do not instrument edges in the spanning tree
472       if (STOutSet[&BB].find(FTBB) != STOutSet[&BB].end()) {
473         auto L = BC.scopeLock();
474         createEdgeDescription(*FuncDesc, Function, FromOffset, BBToID[&BB],
475                               Function, FTBB->getInputOffset(), BBToID[FTBB],
476                               /*Instrumented=*/false);
477         continue;
478       }
479       instrumentOneTarget(SplitWorklist, SplitInstrs, I, Function, BB,
480                           FromOffset, Function, FTBB, FTBB->getInputOffset(),
481                           IsLeafFunction, IsInvokeBlock, FuncDesc, BBToID[&BB],
482                           BBToID[FTBB]);
483     }
484   } // End of BBs loop
485 
486   // Instrument spanning tree leaves
487   if (!opts::ConservativeInstrumentation) {
488     for (auto BBI = Function.begin(), BBE = Function.end(); BBI != BBE; ++BBI) {
489       BinaryBasicBlock &BB = *BBI;
490       if (STOutSet[&BB].size() == 0)
491         instrumentLeafNode(BB, BB.begin(), IsLeafFunction, *FuncDesc,
492                            BBToID[&BB]);
493     }
494   }
495 
496   // Consume list of critical edges: split them and add instrumentation to the
497   // newly created BBs
498   auto Iter = SplitInstrs.begin();
499   for (std::pair<BinaryBasicBlock *, BinaryBasicBlock *> &BBPair :
500        SplitWorklist) {
501     BinaryBasicBlock *NewBB = Function.splitEdge(BBPair.first, BBPair.second);
502     NewBB->addInstructions(Iter->begin(), Iter->end());
503     ++Iter;
504   }
505 
506   // Unused now
507   FuncDesc->EdgesSet.clear();
508 }
509 
510 void Instrumentation::runOnFunctions(BinaryContext &BC) {
511   if (!BC.isX86())
512     return;
513 
514   const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/false,
515                                                  /*IsText=*/false,
516                                                  /*IsAllocatable=*/true);
517   BC.registerOrUpdateSection(".bolt.instr.counters", ELF::SHT_PROGBITS, Flags,
518                              nullptr, 0, 1);
519 
520   BC.registerOrUpdateNoteSection(".bolt.instr.tables", nullptr, 0,
521                                  /*Alignment=*/1,
522                                  /*IsReadOnly=*/true, ELF::SHT_NOTE);
523 
524   Summary->IndCallCounterFuncPtr =
525       BC.Ctx->getOrCreateSymbol("__bolt_ind_call_counter_func_pointer");
526   Summary->IndTailCallCounterFuncPtr =
527       BC.Ctx->getOrCreateSymbol("__bolt_ind_tailcall_counter_func_pointer");
528 
529   createAuxiliaryFunctions(BC);
530 
531   ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
532     return (!BF.isSimple() || BF.isIgnored() ||
533             (opts::InstrumentHotOnly && !BF.getKnownExecutionCount()));
534   };
535 
536   ParallelUtilities::WorkFuncWithAllocTy WorkFun =
537       [&](BinaryFunction &BF, MCPlusBuilder::AllocatorIdTy AllocatorId) {
538         instrumentFunction(BF, AllocatorId);
539       };
540 
541   ParallelUtilities::runOnEachFunctionWithUniqueAllocId(
542       BC, ParallelUtilities::SchedulingPolicy::SP_INST_QUADRATIC, WorkFun,
543       SkipPredicate, "instrumentation", /* ForceSequential=*/true);
544 
545   if (BC.isMachO()) {
546     if (BC.StartFunctionAddress) {
547       BinaryFunction *Main =
548           BC.getBinaryFunctionAtAddress(*BC.StartFunctionAddress);
549       assert(Main && "Entry point function not found");
550       BinaryBasicBlock &BB = Main->front();
551 
552       ErrorOr<BinarySection &> SetupSection =
553           BC.getUniqueSectionByName("I__setup");
554       if (!SetupSection) {
555         llvm::errs() << "Cannot find I__setup section\n";
556         exit(1);
557       }
558       MCSymbol *Target = BC.registerNameAtAddress(
559           "__bolt_instr_setup", SetupSection->getAddress(), 0, 0);
560       MCInst NewInst;
561       BC.MIB->createCall(NewInst, Target, BC.Ctx.get());
562       BB.insertInstruction(BB.begin(), std::move(NewInst));
563     } else {
564       llvm::errs() << "BOLT-WARNING: Entry point not found\n";
565     }
566 
567     if (BinaryData *BD = BC.getBinaryDataByName("___GLOBAL_init_65535/1")) {
568       BinaryFunction *Ctor = BC.getBinaryFunctionAtAddress(BD->getAddress());
569       assert(Ctor && "___GLOBAL_init_65535 function not found");
570       BinaryBasicBlock &BB = Ctor->front();
571       ErrorOr<BinarySection &> FiniSection =
572           BC.getUniqueSectionByName("I__fini");
573       if (!FiniSection) {
574         llvm::errs() << "Cannot find I__fini section\n";
575         exit(1);
576       }
577       MCSymbol *Target = BC.registerNameAtAddress(
578           "__bolt_instr_fini", FiniSection->getAddress(), 0, 0);
579       auto IsLEA = [&BC](const MCInst &Inst) { return BC.MIB->isLEA64r(Inst); };
580       const auto LEA = std::find_if(
581           std::next(llvm::find_if(reverse(BB), IsLEA)), BB.rend(), IsLEA);
582       LEA->getOperand(4).setExpr(
583           MCSymbolRefExpr::create(Target, MCSymbolRefExpr::VK_None, *BC.Ctx));
584     } else {
585       llvm::errs() << "BOLT-WARNING: ___GLOBAL_init_65535 not found\n";
586     }
587   }
588 
589   setupRuntimeLibrary(BC);
590 }
591 
592 void Instrumentation::createAuxiliaryFunctions(BinaryContext &BC) {
593   auto createSimpleFunction =
594       [&](StringRef Title, InstructionListType Instrs) -> BinaryFunction * {
595     BinaryFunction *Func = BC.createInjectedBinaryFunction(std::string(Title));
596 
597     std::vector<std::unique_ptr<BinaryBasicBlock>> BBs;
598     BBs.emplace_back(Func->createBasicBlock());
599     BBs.back()->addInstructions(Instrs.begin(), Instrs.end());
600     BBs.back()->setCFIState(0);
601     Func->insertBasicBlocks(nullptr, std::move(BBs),
602                             /*UpdateLayout=*/true,
603                             /*UpdateCFIState=*/false);
604     Func->updateState(BinaryFunction::State::CFG_Finalized);
605     return Func;
606   };
607 
608   // Here we are creating a set of functions to handle BB entry/exit.
609   // IndCallHandlerExitBB contains instructions to finish handling traffic to an
610   // indirect call. We pass it to createInstrumentedIndCallHandlerEntryBB(),
611   // which will check if a pointer to runtime library traffic accounting
612   // function was initialized (it is done during initialization of runtime
613   // library). If it is so - calls it. Then this routine returns to normal
614   // execution by jumping to exit BB.
615   BinaryFunction *IndCallHandlerExitBB =
616       createSimpleFunction("__bolt_instr_ind_call_handler",
617                            BC.MIB->createInstrumentedIndCallHandlerExitBB());
618 
619   IndCallHandlerExitBBFunction =
620       createSimpleFunction("__bolt_instr_ind_call_handler_func",
621                            BC.MIB->createInstrumentedIndCallHandlerEntryBB(
622                                Summary->IndCallCounterFuncPtr,
623                                IndCallHandlerExitBB->getSymbol(), &*BC.Ctx));
624 
625   BinaryFunction *IndTailCallHandlerExitBB = createSimpleFunction(
626       "__bolt_instr_ind_tail_call_handler",
627       BC.MIB->createInstrumentedIndTailCallHandlerExitBB());
628 
629   IndTailCallHandlerExitBBFunction = createSimpleFunction(
630       "__bolt_instr_ind_tailcall_handler_func",
631       BC.MIB->createInstrumentedIndCallHandlerEntryBB(
632           Summary->IndTailCallCounterFuncPtr,
633           IndTailCallHandlerExitBB->getSymbol(), &*BC.Ctx));
634 
635   createSimpleFunction("__bolt_num_counters_getter",
636                        BC.MIB->createNumCountersGetter(BC.Ctx.get()));
637   createSimpleFunction("__bolt_instr_locations_getter",
638                        BC.MIB->createInstrLocationsGetter(BC.Ctx.get()));
639   createSimpleFunction("__bolt_instr_tables_getter",
640                        BC.MIB->createInstrTablesGetter(BC.Ctx.get()));
641   createSimpleFunction("__bolt_instr_num_funcs_getter",
642                        BC.MIB->createInstrNumFuncsGetter(BC.Ctx.get()));
643 
644   if (BC.isELF()) {
645     if (BC.StartFunctionAddress) {
646       BinaryFunction *Start =
647           BC.getBinaryFunctionAtAddress(*BC.StartFunctionAddress);
648       assert(Start && "Entry point function not found");
649       const MCSymbol *StartSym = Start->getSymbol();
650       createSimpleFunction(
651           "__bolt_start_trampoline",
652           BC.MIB->createSymbolTrampoline(StartSym, BC.Ctx.get()));
653     }
654     if (BC.FiniFunctionAddress) {
655       BinaryFunction *Fini =
656           BC.getBinaryFunctionAtAddress(*BC.FiniFunctionAddress);
657       assert(Fini && "Finalization function not found");
658       const MCSymbol *FiniSym = Fini->getSymbol();
659       createSimpleFunction(
660           "__bolt_fini_trampoline",
661           BC.MIB->createSymbolTrampoline(FiniSym, BC.Ctx.get()));
662     } else {
663       // Create dummy return function for trampoline to avoid issues
664       // with unknown symbol in runtime library. E.g. for static PIE
665       // executable
666       createSimpleFunction("__bolt_fini_trampoline",
667                            BC.MIB->createDummyReturnFunction(BC.Ctx.get()));
668     }
669   }
670 }
671 
672 void Instrumentation::setupRuntimeLibrary(BinaryContext &BC) {
673   uint32_t FuncDescSize = Summary->getFDSize();
674 
675   outs() << "BOLT-INSTRUMENTER: Number of indirect call site descriptors: "
676          << Summary->IndCallDescriptions.size() << "\n";
677   outs() << "BOLT-INSTRUMENTER: Number of indirect call target descriptors: "
678          << Summary->IndCallTargetDescriptions.size() << "\n";
679   outs() << "BOLT-INSTRUMENTER: Number of function descriptors: "
680          << Summary->FunctionDescriptions.size() << "\n";
681   outs() << "BOLT-INSTRUMENTER: Number of branch counters: " << BranchCounters
682          << "\n";
683   outs() << "BOLT-INSTRUMENTER: Number of ST leaf node counters: "
684          << LeafNodeCounters << "\n";
685   outs() << "BOLT-INSTRUMENTER: Number of direct call counters: "
686          << DirectCallCounters << "\n";
687   outs() << "BOLT-INSTRUMENTER: Total number of counters: "
688          << Summary->Counters.size() << "\n";
689   outs() << "BOLT-INSTRUMENTER: Total size of counters: "
690          << (Summary->Counters.size() * 8) << " bytes (static alloc memory)\n";
691   outs() << "BOLT-INSTRUMENTER: Total size of string table emitted: "
692          << Summary->StringTable.size() << " bytes in file\n";
693   outs() << "BOLT-INSTRUMENTER: Total size of descriptors: "
694          << (FuncDescSize +
695              Summary->IndCallDescriptions.size() * sizeof(IndCallDescription) +
696              Summary->IndCallTargetDescriptions.size() *
697                  sizeof(IndCallTargetDescription))
698          << " bytes in file\n";
699   outs() << "BOLT-INSTRUMENTER: Profile will be saved to file "
700          << opts::InstrumentationFilename << "\n";
701 
702   InstrumentationRuntimeLibrary *RtLibrary =
703       static_cast<InstrumentationRuntimeLibrary *>(BC.getRuntimeLibrary());
704   assert(RtLibrary && "instrumentation runtime library object must be set");
705   RtLibrary->setSummary(std::move(Summary));
706 }
707 } // namespace bolt
708 } // namespace llvm
709