LLVM  5.0.0
DemandedBits.cpp
Go to the documentation of this file.
1 //===---- DemandedBits.cpp - Determine demanded bits ----------------------===//
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 // This pass implements a demanded bits analysis. A demanded bit is one that
11 // contributes to a result; bits that are not demanded can be either zero or
12 // one without affecting control or data flow. For example in this sequence:
13 //
14 // %1 = add i32 %x, %y
15 // %2 = trunc i32 %1 to i16
16 //
17 // Only the lowest 16 bits of %1 are demanded; the rest are removed by the
18 // trunc.
19 //
20 //===----------------------------------------------------------------------===//
21 
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/InstIterator.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/KnownBits.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "demanded-bits"
45 
48  "Demanded bits analysis", false, false)
52  "Demanded bits analysis", false, false)
53 
54 DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) {
56 }
57 
59  AU.setPreservesCFG();
62  AU.setPreservesAll();
63 }
64 
66  DB->print(OS);
67 }
68 
69 static bool isAlwaysLive(Instruction *I) {
70  return isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
71  I->isEHPad() || I->mayHaveSideEffects();
72 }
73 
74 void DemandedBits::determineLiveOperandBits(
75  const Instruction *UserI, const Instruction *I, unsigned OperandNo,
76  const APInt &AOut, APInt &AB, KnownBits &Known, KnownBits &Known2) {
77  unsigned BitWidth = AB.getBitWidth();
78 
79  // We're called once per operand, but for some instructions, we need to
80  // compute known bits of both operands in order to determine the live bits of
81  // either (when both operands are instructions themselves). We don't,
82  // however, want to do this twice, so we cache the result in APInts that live
83  // in the caller. For the two-relevant-operands case, both operand values are
84  // provided here.
85  auto ComputeKnownBits =
86  [&](unsigned BitWidth, const Value *V1, const Value *V2) {
87  const DataLayout &DL = I->getModule()->getDataLayout();
88  Known = KnownBits(BitWidth);
89  computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT);
90 
91  if (V2) {
92  Known2 = KnownBits(BitWidth);
93  computeKnownBits(V2, Known2, DL, 0, &AC, UserI, &DT);
94  }
95  };
96 
97  switch (UserI->getOpcode()) {
98  default: break;
99  case Instruction::Call:
100  case Instruction::Invoke:
101  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
102  switch (II->getIntrinsicID()) {
103  default: break;
104  case Intrinsic::bswap:
105  // The alive bits of the input are the swapped alive bits of
106  // the output.
107  AB = AOut.byteSwap();
108  break;
109  case Intrinsic::bitreverse:
110  // The alive bits of the input are the reversed alive bits of
111  // the output.
112  AB = AOut.reverseBits();
113  break;
114  case Intrinsic::ctlz:
115  if (OperandNo == 0) {
116  // We need some output bits, so we need all bits of the
117  // input to the left of, and including, the leftmost bit
118  // known to be one.
119  ComputeKnownBits(BitWidth, I, nullptr);
120  AB = APInt::getHighBitsSet(BitWidth,
121  std::min(BitWidth, Known.countMaxLeadingZeros()+1));
122  }
123  break;
124  case Intrinsic::cttz:
125  if (OperandNo == 0) {
126  // We need some output bits, so we need all bits of the
127  // input to the right of, and including, the rightmost bit
128  // known to be one.
129  ComputeKnownBits(BitWidth, I, nullptr);
130  AB = APInt::getLowBitsSet(BitWidth,
131  std::min(BitWidth, Known.countMaxTrailingZeros()+1));
132  }
133  break;
134  }
135  break;
136  case Instruction::Add:
137  case Instruction::Sub:
138  case Instruction::Mul:
139  // Find the highest live output bit. We don't need any more input
140  // bits than that (adds, and thus subtracts, ripple only to the
141  // left).
142  AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
143  break;
144  case Instruction::Shl:
145  if (OperandNo == 0)
146  if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
147  uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
148  AB = AOut.lshr(ShiftAmt);
149 
150  // If the shift is nuw/nsw, then the high bits are not dead
151  // (because we've promised that they *must* be zero).
152  const ShlOperator *S = cast<ShlOperator>(UserI);
153  if (S->hasNoSignedWrap())
154  AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
155  else if (S->hasNoUnsignedWrap())
156  AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
157  }
158  break;
159  case Instruction::LShr:
160  if (OperandNo == 0)
161  if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
162  uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
163  AB = AOut.shl(ShiftAmt);
164 
165  // If the shift is exact, then the low bits are not dead
166  // (they must be zero).
167  if (cast<LShrOperator>(UserI)->isExact())
168  AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
169  }
170  break;
171  case Instruction::AShr:
172  if (OperandNo == 0)
173  if (auto *ShiftAmtC = dyn_cast<ConstantInt>(UserI->getOperand(1))) {
174  uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
175  AB = AOut.shl(ShiftAmt);
176  // Because the high input bit is replicated into the
177  // high-order bits of the result, if we need any of those
178  // bits, then we must keep the highest input bit.
179  if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
180  .getBoolValue())
181  AB.setSignBit();
182 
183  // If the shift is exact, then the low bits are not dead
184  // (they must be zero).
185  if (cast<AShrOperator>(UserI)->isExact())
186  AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
187  }
188  break;
189  case Instruction::And:
190  AB = AOut;
191 
192  // For bits that are known zero, the corresponding bits in the
193  // other operand are dead (unless they're both zero, in which
194  // case they can't both be dead, so just mark the LHS bits as
195  // dead).
196  if (OperandNo == 0) {
197  ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
198  AB &= ~Known2.Zero;
199  } else {
200  if (!isa<Instruction>(UserI->getOperand(0)))
201  ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
202  AB &= ~(Known.Zero & ~Known2.Zero);
203  }
204  break;
205  case Instruction::Or:
206  AB = AOut;
207 
208  // For bits that are known one, the corresponding bits in the
209  // other operand are dead (unless they're both one, in which
210  // case they can't both be dead, so just mark the LHS bits as
211  // dead).
212  if (OperandNo == 0) {
213  ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
214  AB &= ~Known2.One;
215  } else {
216  if (!isa<Instruction>(UserI->getOperand(0)))
217  ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
218  AB &= ~(Known.One & ~Known2.One);
219  }
220  break;
221  case Instruction::Xor:
222  case Instruction::PHI:
223  AB = AOut;
224  break;
225  case Instruction::Trunc:
226  AB = AOut.zext(BitWidth);
227  break;
228  case Instruction::ZExt:
229  AB = AOut.trunc(BitWidth);
230  break;
231  case Instruction::SExt:
232  AB = AOut.trunc(BitWidth);
233  // Because the high input bit is replicated into the
234  // high-order bits of the result, if we need any of those
235  // bits, then we must keep the highest input bit.
236  if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
237  AOut.getBitWidth() - BitWidth))
238  .getBoolValue())
239  AB.setSignBit();
240  break;
241  case Instruction::Select:
242  if (OperandNo != 0)
243  AB = AOut;
244  break;
245  }
246 }
247 
249  auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
250  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
251  DB.emplace(F, AC, DT);
252  return false;
253 }
254 
256  DB.reset();
257 }
258 
259 void DemandedBits::performAnalysis() {
260  if (Analyzed)
261  // Analysis already completed for this function.
262  return;
263  Analyzed = true;
264 
265  Visited.clear();
266  AliveBits.clear();
267 
269 
270  // Collect the set of "root" instructions that are known live.
271  for (Instruction &I : instructions(F)) {
272  if (!isAlwaysLive(&I))
273  continue;
274 
275  DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
276  // For integer-valued instructions, set up an initial empty set of alive
277  // bits and add the instruction to the work list. For other instructions
278  // add their operands to the work list (for integer values operands, mark
279  // all bits as live).
280  if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
281  if (AliveBits.try_emplace(&I, IT->getBitWidth(), 0).second)
282  Worklist.push_back(&I);
283 
284  continue;
285  }
286 
287  // Non-integer-typed instructions...
288  for (Use &OI : I.operands()) {
289  if (Instruction *J = dyn_cast<Instruction>(OI)) {
290  if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
291  AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
292  Worklist.push_back(J);
293  }
294  }
295  // To save memory, we don't add I to the Visited set here. Instead, we
296  // check isAlwaysLive on every instruction when searching for dead
297  // instructions later (we need to check isAlwaysLive for the
298  // integer-typed instructions anyway).
299  }
300 
301  // Propagate liveness backwards to operands.
302  while (!Worklist.empty()) {
303  Instruction *UserI = Worklist.pop_back_val();
304 
305  DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
306  APInt AOut;
307  if (UserI->getType()->isIntegerTy()) {
308  AOut = AliveBits[UserI];
309  DEBUG(dbgs() << " Alive Out: " << AOut);
310  }
311  DEBUG(dbgs() << "\n");
312 
313  if (!UserI->getType()->isIntegerTy())
314  Visited.insert(UserI);
315 
316  KnownBits Known, Known2;
317  // Compute the set of alive bits for each operand. These are anded into the
318  // existing set, if any, and if that changes the set of alive bits, the
319  // operand is added to the work-list.
320  for (Use &OI : UserI->operands()) {
321  if (Instruction *I = dyn_cast<Instruction>(OI)) {
322  if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
323  unsigned BitWidth = IT->getBitWidth();
324  APInt AB = APInt::getAllOnesValue(BitWidth);
325  if (UserI->getType()->isIntegerTy() && !AOut &&
326  !isAlwaysLive(UserI)) {
327  AB = APInt(BitWidth, 0);
328  } else {
329  // If all bits of the output are dead, then all bits of the input
330  // Bits of each operand that are used to compute alive bits of the
331  // output are alive, all others are dead.
332  determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
333  Known, Known2);
334  }
335 
336  // If we've added to the set of alive bits (or the operand has not
337  // been previously visited), then re-queue the operand to be visited
338  // again.
339  APInt ABPrev(BitWidth, 0);
340  auto ABI = AliveBits.find(I);
341  if (ABI != AliveBits.end())
342  ABPrev = ABI->second;
343 
344  APInt ABNew = AB | ABPrev;
345  if (ABNew != ABPrev || ABI == AliveBits.end()) {
346  AliveBits[I] = std::move(ABNew);
347  Worklist.push_back(I);
348  }
349  } else if (!Visited.count(I)) {
350  Worklist.push_back(I);
351  }
352  }
353  }
354  }
355 }
356 
358  performAnalysis();
359 
360  const DataLayout &DL = I->getParent()->getModule()->getDataLayout();
361  auto Found = AliveBits.find(I);
362  if (Found != AliveBits.end())
363  return Found->second;
365 }
366 
368  performAnalysis();
369 
370  return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
371  !isAlwaysLive(I);
372 }
373 
375  performAnalysis();
376  for (auto &KV : AliveBits) {
377  OS << "DemandedBits: 0x" << utohexstr(KV.second.getLimitedValue()) << " for "
378  << *KV.first << "\n";
379  }
380 }
381 
383  return new DemandedBitsWrapperPass();
384 }
385 
386 AnalysisKey DemandedBitsAnalysis::Key;
387 
390  auto &AC = AM.getResult<AssumptionAnalysis>(F);
391  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
392  return DemandedBits(F, AC, DT);
393 }
394 
397  AM.getResult<DemandedBitsAnalysis>(F).print(OS);
398  return PreservedAnalyses::all();
399 }
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT,"arm-default-it","Generate IT block based on arch"), clEnumValN(RestrictedIT,"arm-restrict-it","Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT,"arm-no-restrict-it","Allow IT blocks based on ARMv7")))
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
void initializeDemandedBitsWrapperPassPass(PassRegistry &)
void setSignBit()
Set the sign bit to 1.
Definition: APInt.h:1392
APInt byteSwap() const
Definition: APInt.cpp:617
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:555
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
APInt reverseBits() const
Definition: APInt.cpp:643
bool isInstructionDead(Instruction *I)
Return true if, during analysis, I could not be reached.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
Definition: Operator.h:96
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition: KnownBits.h:178
DataLayout DL
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:641
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:500
demanded bits
unsigned second
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:232
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
Definition: BasicBlock.cpp:116
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Definition: APInt.h:475
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
An analysis that produces DemandedBits for a function.
Definition: DemandedBits.h:90
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:981
#define F(x, y, z)
Definition: MD5.cpp:55
demanded Demanded bits false
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1512
DemandedBits run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce demanded bits information.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
Definition: APInt.h:629
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:818
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1488
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Value * getOperand(unsigned i) const
Definition: User.h:154
op_range operands()
Definition: User.h:222
Class to represent integer types.
Definition: DerivedTypes.h:40
demanded Demanded bits analysis
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
A function analysis which provides an AssumptionCache.
INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass,"demanded-bits","Demanded bits analysis", false, false) INITIALIZE_PASS_END(DemandedBitsWrapperPass
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
APInt getDemandedBits(Instruction *I)
Return the bits demanded from instruction I.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Class for arbitrary precision integers.
Definition: APInt.h:69
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:503
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:361
void print(raw_ostream &OS, const Module *M) const override
print - Print out the internal state of the pass.
#define I(x, y, z)
Definition: MD5.cpp:58
static std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:62
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition: KnownBits.h:168
LLVM Value Representation.
Definition: Value.h:73
static bool isAlwaysLive(Instruction *I)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:121
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:532
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:118
inst_range instructions(Function *F)
Definition: InstIterator.h:134
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:865
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:261
FunctionPass * createDemandedBitsWrapperPass()
Create a demanded bits analysis pass.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:959
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
const BasicBlock * getParent() const
Definition: Instruction.h:66
void releaseMemory() override
Clean up memory in between runs.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...
Definition: Operator.h:90
void print(raw_ostream &OS)
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44