LLVM 24.0.0git
MIRFSDiscriminator.cpp
Go to the documentation of this file.
1//===-------- MIRFSDiscriminator.cpp: Flow Sensitive Discriminator --------===//
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 provides the implementation of a machine pass that adds the flow
10// sensitive discriminator to the instruction debug information.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/IR/Analysis.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/PseudoProbe.h"
28#include "llvm/Support/Debug.h"
31
32using namespace llvm;
33using namespace sampleprof;
34using namespace sampleprofutil;
35
36#define DEBUG_TYPE "mir-fs-discriminators"
37
38// TODO(xur): Remove this option and related code once we make true as the
39// default.
41 "improved-fs-discriminator", cl::Hidden, cl::init(false),
42 cl::desc("New FS discriminators encoding (incompatible with the original "
43 "encoding)"));
45
47 "Add MIR Flow Sensitive Discriminators",
48 /* cfg = */ false, /* is_analysis = */ false)
49
51
55}
56
57// TODO(xur): Remove this once we switch to ImprovedFSDiscriminator.
58// Compute a hash value using debug line number, and the line numbers from the
59// inline stack.
61 const MachineInstr &MI,
62 const DILocation *DIL) {
63 auto updateHash = [](const StringRef &Str) -> uint64_t {
64 if (Str.empty())
65 return 0;
66 return MD5Hash(Str);
67 };
68 uint64_t Ret = updateHash(std::to_string(DIL->getLine()));
69 Ret ^= updateHash(BB.getName());
70 Ret ^= updateHash(DIL->getScope()->getSubprogram()->getLinkageName());
71 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
72 Ret ^= updateHash(std::to_string(DIL->getLine()));
73 Ret ^= updateHash(DIL->getScope()->getSubprogram()->getLinkageName());
74 }
75 return Ret;
76}
77
79 auto hashCombine = [](const uint64_t Seed, const uint64_t Val) {
80 std::hash<uint64_t> Hasher;
81 return Seed ^ (Hasher(Val) + 0x9e3779b9 + (Seed << 6) + (Seed >> 2));
82 };
83 uint64_t Ret = 0;
84 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
85 Ret = hashCombine(Ret, xxh3_64bits(ArrayRef<uint8_t>(DIL->getLine())));
86 Ret = hashCombine(Ret, xxh3_64bits(DIL->getSubprogramLinkageName()));
87 }
88 return Ret;
89}
90
91// Traverse the CFG and assign FD discriminators. If two instructions
92// have the same lineno and discriminator, but residing in different BBs,
93// the latter instruction will get a new discriminator value. The new
94// discriminator keeps the existing discriminator value but sets new bits
95// b/w LowBit and HighBit.
98 return false;
99
100 bool HasPseudoProbe = MF.getFunction().getParent()->getNamedMetadata(
102
103 if (!HasPseudoProbe && !MF.getFunction().shouldEmitDebugInfoForProfiling())
104 return false;
105
106 const unsigned LowBit = getFSPassBitBegin(Pass);
107 const unsigned HighBit = getFSPassBitEnd(Pass);
108
109 assert(LowBit < HighBit && "HighBit needs to be greater than Lowbit");
110 bool Changed = false;
111 bool ProbeLocationChanged = false;
112 using LocationDiscriminator =
113 std::tuple<StringRef, unsigned, unsigned, uint64_t>;
115 using LocationDiscriminatorBBMap = DenseMap<LocationDiscriminator, BBSet>;
116 using LocationDiscriminatorCurrPassMap =
118
119 LocationDiscriminatorBBMap LDBM;
120 LocationDiscriminatorCurrPassMap LDCM;
121
122 // Mask of discriminators before this pass.
123 // TODO(xur): simplify this once we switch to ImprovedFSDiscriminator.
124 unsigned LowBitTemp = LowBit;
125 assert(LowBit > 0 && "LowBit in FSDiscriminator cannot be 0");
127 LowBitTemp -= 1;
128 unsigned BitMaskBefore = getN1Bits(LowBitTemp);
129 // Mask of discriminators including this pass.
130 unsigned BitMaskNow = getN1Bits(HighBit);
131 // Mask of discriminators for bits specific to this pass.
132 unsigned BitMaskThisPass = BitMaskNow ^ BitMaskBefore;
133 unsigned NumNewD = 0;
134
135 LLVM_DEBUG(dbgs() << "MIRAddFSDiscriminators working on Func: "
136 << MF.getFunction().getName() << " Highbit=" << HighBit
137 << "\n");
138
139 for (MachineBasicBlock &BB : MF) {
140 for (MachineInstr &I : BB) {
141 if (HasPseudoProbe) {
142 // Only assign discriminators to pseudo probe instructions. Call
143 // instructions are excluded since their dwarf discriminators are used
144 // for other purposes, i.e, storing probe ids.
145 if (!I.isPseudoProbe())
146 continue;
147 } else if (ImprovedFSDiscriminator && I.isMetaInstruction()) {
148 continue;
149 }
150 const DILocation *DIL = I.getDebugLoc().get();
151 if (!DIL)
152 continue;
153
154 // Use the id of pseudo probe to compute the discriminator.
155 unsigned LineNo =
156 I.isPseudoProbe() ? I.getOperand(1).getImm() : DIL->getLine();
157 if (LineNo == 0)
158 continue;
159 unsigned Discriminator = DIL->getDiscriminator();
160 // Clean up discriminators for pseudo probes at the first FS discriminator
161 // pass as their discriminators should not ever be used.
162 if ((Pass == FSDiscriminatorPass::Pass1) && I.isPseudoProbe()) {
163 Discriminator = 0;
164 const DILocation *ResetDIL = DIL->cloneWithDiscriminator(0);
165 ProbeLocationChanged |= DIL != ResetDIL;
166 I.setDebugLoc(ResetDIL);
167 }
168 uint64_t CallStackHashVal = 0;
170 CallStackHashVal = getCallStackHash(DIL);
171
172 LocationDiscriminator LD{DIL->getFilename(), LineNo, Discriminator,
173 CallStackHashVal};
174 auto &BBMap = LDBM[LD];
175 auto R = BBMap.insert(&BB);
176 if (BBMap.size() == 1)
177 continue;
178
179 unsigned DiscriminatorCurrPass;
180 DiscriminatorCurrPass = R.second ? ++LDCM[LD] : LDCM[LD];
181 DiscriminatorCurrPass = DiscriminatorCurrPass << LowBit;
183 DiscriminatorCurrPass += getCallStackHashV0(BB, I, DIL);
184 DiscriminatorCurrPass &= BitMaskThisPass;
185 unsigned NewD = Discriminator | DiscriminatorCurrPass;
186 const auto *const NewDIL = DIL->cloneWithDiscriminator(NewD);
187 if (!NewDIL) {
188 LLVM_DEBUG(dbgs() << "Could not encode discriminator: "
189 << DIL->getFilename() << ":" << DIL->getLine() << ":"
190 << DIL->getColumn() << ":" << Discriminator << " "
191 << I << "\n");
192 continue;
193 }
194
195 I.setDebugLoc(NewDIL);
196 NumNewD++;
197 LLVM_DEBUG(dbgs() << DIL->getFilename() << ":" << DIL->getLine() << ":"
198 << DIL->getColumn() << ": add FS discriminator, from "
199 << Discriminator << " -> " << NewD << "\n");
200 Changed = true;
201 }
202 }
203
204 if (Changed) {
206 LLVM_DEBUG(dbgs() << "Num of FS Discriminators: " << NumNewD << "\n");
207 (void) NumNewD;
208 }
209
210 return Changed || ProbeLocationChanged;
211}
212
213bool MIRAddFSDiscriminatorsLegacy::runOnMachineFunction(MachineFunction &MF) {
214 return addFSDiscriminators(MF, Pass);
215}
216
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition MD5.cpp:57
static uint64_t getCallStackHashV0(const MachineBasicBlock &BB, const MachineInstr &MI, const DILocation *DIL)
static bool addFSDiscriminators(MachineFunction &MF, FSDiscriminatorPass Pass)
static uint64_t getCallStackHash(const DILocation *DIL)
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static ManagedStatic< cl::opt< uint64_t >, CreateSeed > Seed
This file provides the utility functions for the sampled PGO loader base implementation.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
const DILocation * cloneWithDiscriminator(unsigned Discriminator) const
Returns a new DILocation with updated Discriminator.
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool shouldEmitDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MachineFunctionAM)
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:320
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
Pass manager infrastructure for declaring and invalidating analyses.
initializer< Ty > init(const Ty &Val)
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
LLVM_ABI void createFSDiscriminatorVariable(Module *M)
Create a global variable to flag FSDiscriminators are used.
This is an optimization pass for GlobalISel generic memory operations.
static unsigned getFSPassBitBegin(sampleprof::FSDiscriminatorPass P)
LLVM_ABI char & MIRAddFSDiscriminatorsID
This pass adds flow sensitive discriminators.
LLVM_ABI cl::opt< bool > ImprovedFSDiscriminator
uint64_t xxh3_64bits(ArrayRef< uint8_t > data)
Inline ArrayRef overloads of the xxhash entry points declared out-of-line in llvm/Support/xxhash....
Definition ArrayRef.h:558
LLVM_ABI cl::opt< bool > EnableFSDiscriminator
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
static unsigned getFSPassBitEnd(sampleprof::FSDiscriminatorPass P)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI FunctionPass * createMIRAddFSDiscriminatorsLegacyPass(sampleprof::FSDiscriminatorPass P)
Add Flow Sensitive Discriminators.
static unsigned getN1Bits(int N)
constexpr const char * PseudoProbeDescMetadataName
Definition PseudoProbe.h:26