18
18
#include " llvm/Analysis/ValueTracking.h"
19
19
#include " llvm/IR/Function.h"
20
20
#include " llvm/Support/Debug.h"
21
+ #include " llvm/Support/InstructionCost.h"
21
22
22
23
#define DEBUG_TYPE " code-metrics"
23
24
@@ -112,7 +113,14 @@ void CodeMetrics::analyzeBasicBlock(
112
113
const BasicBlock *BB, const TargetTransformInfo &TTI,
113
114
const SmallPtrSetImpl<const Value *> &EphValues, bool PrepareForLTO) {
114
115
++NumBlocks;
115
- unsigned NumInstsBeforeThisBB = NumInsts;
116
+ // Use a proxy variable for NumInsts of type InstructionCost, so that it can
117
+ // use InstructionCost's arithmetic properties such as saturation when this
118
+ // feature is added to InstructionCost.
119
+ // When storing the value back to NumInsts, we can assume all costs are Valid
120
+ // because the IR should not contain any nodes that cannot be costed. If that
121
+ // happens the cost-model is broken.
122
+ InstructionCost NumInstsProxy = NumInsts;
123
+ InstructionCost NumInstsBeforeThisBB = NumInsts;
116
124
for (const Instruction &I : *BB) {
117
125
// Skip ephemeral values.
118
126
if (EphValues.count (&I))
@@ -171,7 +179,8 @@ void CodeMetrics::analyzeBasicBlock(
171
179
if (InvI->cannotDuplicate ())
172
180
notDuplicatable = true ;
173
181
174
- NumInsts += TTI.getUserCost (&I, TargetTransformInfo::TCK_CodeSize);
182
+ NumInstsProxy += TTI.getUserCost (&I, TargetTransformInfo::TCK_CodeSize);
183
+ NumInsts = *NumInstsProxy.getValue ();
175
184
}
176
185
177
186
if (isa<ReturnInst>(BB->getTerminator ()))
@@ -191,5 +200,6 @@ void CodeMetrics::analyzeBasicBlock(
191
200
notDuplicatable |= isa<IndirectBrInst>(BB->getTerminator ());
192
201
193
202
// Remember NumInsts for this BB.
194
- NumBBInsts[BB] = NumInsts - NumInstsBeforeThisBB;
203
+ InstructionCost NumInstsThisBB = NumInstsProxy - NumInstsBeforeThisBB;
204
+ NumBBInsts[BB] = *NumInstsThisBB.getValue ();
195
205
}
0 commit comments