1 //===--- CodeGenPGO.h - PGO Instrumentation for LLVM CodeGen ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Instrumentation-based profile-guided optimization
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENPGO_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENPGO_H
16 
17 #include "CGBuilder.h"
18 #include "CodeGenModule.h"
19 #include "CodeGenTypes.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include <memory>
24 
25 namespace clang {
26 namespace CodeGen {
27 class RegionCounter;
28 
29 /// Per-function PGO state. This class should generally not be used directly,
30 /// but instead through the CodeGenFunction and RegionCounter types.
31 class CodeGenPGO {
32 private:
33   CodeGenModule &CGM;
34   std::string FuncName;
35   llvm::GlobalValue::LinkageTypes VarLinkage;
36 
37   unsigned NumRegionCounters;
38   uint64_t FunctionHash;
39   llvm::GlobalVariable *RegionCounters;
40   std::unique_ptr<llvm::DenseMap<const Stmt *, unsigned>> RegionCounterMap;
41   std::unique_ptr<llvm::DenseMap<const Stmt *, uint64_t>> StmtCountMap;
42   std::vector<uint64_t> RegionCounts;
43   uint64_t CurrentRegionCount;
44   std::string CoverageMapping;
45   /// \brief A flag that is set to true when this function doesn't need
46   /// to have coverage mapping data.
47   bool SkipCoverageMapping;
48 
49 public:
50   CodeGenPGO(CodeGenModule &CGM)
51       : CGM(CGM), NumRegionCounters(0), FunctionHash(0),
52         RegionCounters(nullptr), CurrentRegionCount(0),
53         SkipCoverageMapping(false) {}
54 
55   /// Whether or not we have PGO region data for the current function. This is
56   /// false both when we have no data at all and when our data has been
57   /// discarded.
58   bool haveRegionCounts() const { return !RegionCounts.empty(); }
59 
60   /// Get the string used to identify this function in the profile data.
61   /// For functions with local linkage, this includes the main file name.
62   StringRef getFuncName() const { return StringRef(FuncName); }
63   std::string getFuncVarName(StringRef VarName) const {
64     return ("__llvm_profile_" + VarName + "_" + FuncName).str();
65   }
66 
67   /// Return the counter value of the current region.
68   uint64_t getCurrentRegionCount() const { return CurrentRegionCount; }
69 
70   /// Set the counter value for the current region. This is used to keep track
71   /// of changes to the most recent counter from control flow and non-local
72   /// exits.
73   void setCurrentRegionCount(uint64_t Count) { CurrentRegionCount = Count; }
74 
75   /// Indicate that the current region is never reached, and thus should have a
76   /// counter value of zero. This is important so that subsequent regions can
77   /// correctly track their parent counts.
78   void setCurrentRegionUnreachable() { setCurrentRegionCount(0); }
79 
80   /// Check if an execution count is known for a given statement. If so, return
81   /// true and put the value in Count; else return false.
82   bool getStmtCount(const Stmt *S, uint64_t &Count) {
83     if (!StmtCountMap)
84       return false;
85     llvm::DenseMap<const Stmt*, uint64_t>::const_iterator
86       I = StmtCountMap->find(S);
87     if (I == StmtCountMap->end())
88       return false;
89     Count = I->second;
90     return true;
91   }
92 
93   /// If the execution count for the current statement is known, record that
94   /// as the current count.
95   void setCurrentStmt(const Stmt *S) {
96     uint64_t Count;
97     if (getStmtCount(S, Count))
98       setCurrentRegionCount(Count);
99   }
100 
101   /// Calculate branch weights appropriate for PGO data
102   llvm::MDNode *createBranchWeights(uint64_t TrueCount, uint64_t FalseCount);
103   llvm::MDNode *createBranchWeights(ArrayRef<uint64_t> Weights);
104   llvm::MDNode *createLoopWeights(const Stmt *Cond, RegionCounter &Cnt);
105 
106   /// Check if we need to emit coverage mapping for a given declaration
107   void checkGlobalDecl(GlobalDecl GD);
108   /// Assign counters to regions and configure them for PGO of a given
109   /// function. Does nothing if instrumentation is not enabled and either
110   /// generates global variables or associates PGO data with each of the
111   /// counters depending on whether we are generating or using instrumentation.
112   void assignRegionCounters(const Decl *D, llvm::Function *Fn);
113   /// Emit static data structures for instrumentation data.
114   void emitInstrumentationData();
115   /// Clean up region counter state. Must be called if assignRegionCounters is
116   /// used.
117   void destroyRegionCounters();
118   /// Emit static initialization code, if any.
119   static llvm::Function *emitInitialization(CodeGenModule &CGM);
120   /// Emit a coverage mapping range with a counter zero
121   /// for an unused declaration.
122   void emitEmptyCounterMapping(const Decl *D, StringRef FuncName,
123                                llvm::GlobalValue::LinkageTypes Linkage);
124 private:
125   void setFuncName(llvm::Function *Fn);
126   void setFuncName(StringRef Name, llvm::GlobalValue::LinkageTypes Linkage);
127   void setVarLinkage(llvm::GlobalValue::LinkageTypes Linkage);
128   void mapRegionCounters(const Decl *D);
129   void computeRegionCounts(const Decl *D);
130   void applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
131                                llvm::Function *Fn);
132   void loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
133                         bool IsInMainFile);
134   void emitCounterVariables();
135   llvm::GlobalVariable *buildDataVar();
136   void emitCounterRegionMapping(const Decl *D);
137 
138   /// Emit code to increment the counter at the given index
139   void emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter);
140 
141   /// Return the region counter for the given statement. This should only be
142   /// called on statements that have a dedicated counter.
143   unsigned getRegionCounter(const Stmt *S) {
144     if (!RegionCounterMap)
145       return 0;
146     return (*RegionCounterMap)[S];
147   }
148 
149   /// Return the region count for the counter at the given index.
150   uint64_t getRegionCount(unsigned Counter) {
151     if (!haveRegionCounts())
152       return 0;
153     return RegionCounts[Counter];
154   }
155 
156   friend class RegionCounter;
157 };
158 
159 /// A counter for a particular region. This is the primary interface through
160 /// which clients manage PGO counters and their values.
161 class RegionCounter {
162   CodeGenPGO *PGO;
163   unsigned Counter;
164   uint64_t Count;
165   uint64_t ParentCount;
166   uint64_t RegionCount;
167   int64_t Adjust;
168 
169   RegionCounter(CodeGenPGO &PGO, unsigned CounterIndex)
170     : PGO(&PGO), Counter(CounterIndex), Count(PGO.getRegionCount(Counter)),
171       ParentCount(PGO.getCurrentRegionCount()), Adjust(0) {}
172 
173 public:
174   RegionCounter(CodeGenPGO &PGO, const Stmt *S)
175     : PGO(&PGO), Counter(PGO.getRegionCounter(S)),
176       Count(PGO.getRegionCount(Counter)),
177       ParentCount(PGO.getCurrentRegionCount()), Adjust(0) {}
178 
179   /// Get the value of the counter. In most cases this is the number of times
180   /// the region of the counter was entered, but for switch labels it's the
181   /// number of direct jumps to that label.
182   uint64_t getCount() const { return Count; }
183 
184   /// Get the value of the counter with adjustments applied. Adjustments occur
185   /// when control enters or leaves the region abnormally; i.e., if there is a
186   /// jump to a label within the region, or if the function can return from
187   /// within the region. The adjusted count, then, is the value of the counter
188   /// at the end of the region.
189   uint64_t getAdjustedCount() const {
190     return Count + Adjust;
191   }
192 
193   /// Get the value of the counter in this region's parent, i.e., the region
194   /// that was active when this region began. This is useful for deriving
195   /// counts in implicitly counted regions, like the false case of a condition
196   /// or the normal exits of a loop.
197   uint64_t getParentCount() const { return ParentCount; }
198 
199   /// Activate the counter by emitting an increment and starting to track
200   /// adjustments. If AddIncomingFallThrough is true, the current region count
201   /// will be added to the counter for the purposes of tracking the region.
202   void beginRegion(CGBuilderTy &Builder, bool AddIncomingFallThrough=false) {
203     beginRegion(AddIncomingFallThrough);
204     PGO->emitCounterIncrement(Builder, Counter);
205   }
206   void beginRegion(bool AddIncomingFallThrough=false) {
207     RegionCount = Count;
208     if (AddIncomingFallThrough)
209       RegionCount += PGO->getCurrentRegionCount();
210     PGO->setCurrentRegionCount(RegionCount);
211   }
212 
213   /// For counters on boolean branches, begins tracking adjustments for the
214   /// uncounted path.
215   void beginElseRegion() {
216     RegionCount = ParentCount - Count;
217     PGO->setCurrentRegionCount(RegionCount);
218   }
219 
220   /// Reset the current region count.
221   void setCurrentRegionCount(uint64_t CurrentCount) {
222     RegionCount = CurrentCount;
223     PGO->setCurrentRegionCount(RegionCount);
224   }
225 
226   /// Adjust for non-local control flow after emitting a subexpression or
227   /// substatement. This must be called to account for constructs such as gotos,
228   /// labels, and returns, so that we can ensure that our region's count is
229   /// correct in the code that follows.
230   void adjustForControlFlow() {
231     Adjust += PGO->getCurrentRegionCount() - RegionCount;
232     // Reset the region count in case this is called again later.
233     RegionCount = PGO->getCurrentRegionCount();
234   }
235 
236   /// Commit all adjustments to the current region. If the region is a loop,
237   /// the LoopAdjust value should be the count of all the breaks and continues
238   /// from the loop, to compensate for those counts being deducted from the
239   /// adjustments for the body of the loop.
240   void applyAdjustmentsToRegion(uint64_t LoopAdjust) {
241     PGO->setCurrentRegionCount(ParentCount + Adjust + LoopAdjust);
242   }
243 };
244 
245 }  // end namespace CodeGen
246 }  // end namespace clang
247 
248 #endif
249