1 //===---- DemandedBits.cpp - Determine demanded bits ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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:
14 // %1 = add i32 %x, %y
15 // %2 = trunc i32 %1 to i16
17 // Only the lowest 16 bits of %1 are demanded; the rest are removed by the
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Analysis/DemandedBits.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
44 #define DEBUG_TYPE "demanded-bits"
46 char DemandedBits::ID = 0;
47 INITIALIZE_PASS_BEGIN(DemandedBits, "demanded-bits", "Demanded bits analysis",
49 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
50 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
51 INITIALIZE_PASS_END(DemandedBits, "demanded-bits", "Demanded bits analysis",
54 DemandedBits::DemandedBits() : FunctionPass(ID) {
55 initializeDemandedBitsPass(*PassRegistry::getPassRegistry());
58 void DemandedBits::getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<AssumptionCacheTracker>();
61 AU.addRequired<DominatorTreeWrapperPass>();
65 static bool isAlwaysLive(Instruction *I) {
66 return isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
67 I->isEHPad() || I->mayHaveSideEffects();
70 void DemandedBits::determineLiveOperandBits(
71 const Instruction *UserI, const Instruction *I, unsigned OperandNo,
72 const APInt &AOut, APInt &AB, APInt &KnownZero, APInt &KnownOne,
73 APInt &KnownZero2, APInt &KnownOne2) {
74 unsigned BitWidth = AB.getBitWidth();
76 // We're called once per operand, but for some instructions, we need to
77 // compute known bits of both operands in order to determine the live bits of
78 // either (when both operands are instructions themselves). We don't,
79 // however, want to do this twice, so we cache the result in APInts that live
80 // in the caller. For the two-relevant-operands case, both operand values are
82 auto ComputeKnownBits =
83 [&](unsigned BitWidth, const Value *V1, const Value *V2) {
84 const DataLayout &DL = I->getModule()->getDataLayout();
85 KnownZero = APInt(BitWidth, 0);
86 KnownOne = APInt(BitWidth, 0);
87 computeKnownBits(const_cast<Value *>(V1), KnownZero, KnownOne, DL, 0,
91 KnownZero2 = APInt(BitWidth, 0);
92 KnownOne2 = APInt(BitWidth, 0);
93 computeKnownBits(const_cast<Value *>(V2), KnownZero2, KnownOne2, DL,
98 switch (UserI->getOpcode()) {
100 case Instruction::Call:
101 case Instruction::Invoke:
102 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
103 switch (II->getIntrinsicID()) {
105 case Intrinsic::bswap:
106 // The alive bits of the input are the swapped alive bits of
108 AB = AOut.byteSwap();
110 case Intrinsic::ctlz:
111 if (OperandNo == 0) {
112 // We need some output bits, so we need all bits of the
113 // input to the left of, and including, the leftmost bit
115 ComputeKnownBits(BitWidth, I, nullptr);
116 AB = APInt::getHighBitsSet(BitWidth,
117 std::min(BitWidth, KnownOne.countLeadingZeros()+1));
120 case Intrinsic::cttz:
121 if (OperandNo == 0) {
122 // We need some output bits, so we need all bits of the
123 // input to the right of, and including, the rightmost bit
125 ComputeKnownBits(BitWidth, I, nullptr);
126 AB = APInt::getLowBitsSet(BitWidth,
127 std::min(BitWidth, KnownOne.countTrailingZeros()+1));
132 case Instruction::Add:
133 case Instruction::Sub:
134 // Find the highest live output bit. We don't need any more input
135 // bits than that (adds, and thus subtracts, ripple only to the
137 AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
139 case Instruction::Shl:
141 if (ConstantInt *CI =
142 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
143 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
144 AB = AOut.lshr(ShiftAmt);
146 // If the shift is nuw/nsw, then the high bits are not dead
147 // (because we've promised that they *must* be zero).
148 const ShlOperator *S = cast<ShlOperator>(UserI);
149 if (S->hasNoSignedWrap())
150 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
151 else if (S->hasNoUnsignedWrap())
152 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
155 case Instruction::LShr:
157 if (ConstantInt *CI =
158 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
159 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
160 AB = AOut.shl(ShiftAmt);
162 // If the shift is exact, then the low bits are not dead
163 // (they must be zero).
164 if (cast<LShrOperator>(UserI)->isExact())
165 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
168 case Instruction::AShr:
170 if (ConstantInt *CI =
171 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
172 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
173 AB = AOut.shl(ShiftAmt);
174 // Because the high input bit is replicated into the
175 // high-order bits of the result, if we need any of those
176 // bits, then we must keep the highest input bit.
177 if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
179 AB.setBit(BitWidth-1);
181 // If the shift is exact, then the low bits are not dead
182 // (they must be zero).
183 if (cast<AShrOperator>(UserI)->isExact())
184 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
187 case Instruction::And:
190 // For bits that are known zero, the corresponding bits in the
191 // other operand are dead (unless they're both zero, in which
192 // case they can't both be dead, so just mark the LHS bits as
194 if (OperandNo == 0) {
195 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
198 if (!isa<Instruction>(UserI->getOperand(0)))
199 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
200 AB &= ~(KnownZero & ~KnownZero2);
203 case Instruction::Or:
206 // For bits that are known one, the corresponding bits in the
207 // other operand are dead (unless they're both one, in which
208 // case they can't both be dead, so just mark the LHS bits as
210 if (OperandNo == 0) {
211 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
214 if (!isa<Instruction>(UserI->getOperand(0)))
215 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
216 AB &= ~(KnownOne & ~KnownOne2);
219 case Instruction::Xor:
220 case Instruction::PHI:
223 case Instruction::Trunc:
224 AB = AOut.zext(BitWidth);
226 case Instruction::ZExt:
227 AB = AOut.trunc(BitWidth);
229 case Instruction::SExt:
230 AB = AOut.trunc(BitWidth);
231 // Because the high input bit is replicated into the
232 // high-order bits of the result, if we need any of those
233 // bits, then we must keep the highest input bit.
234 if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
235 AOut.getBitWidth() - BitWidth))
237 AB.setBit(BitWidth-1);
239 case Instruction::Select:
246 bool DemandedBits::runOnFunction(Function& F) {
247 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
248 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
253 SmallVector<Instruction*, 128> Worklist;
255 // Collect the set of "root" instructions that are known live.
256 for (Instruction &I : instructions(F)) {
257 if (!isAlwaysLive(&I))
260 DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
261 // For integer-valued instructions, set up an initial empty set of alive
262 // bits and add the instruction to the work list. For other instructions
263 // add their operands to the work list (for integer values operands, mark
264 // all bits as live).
265 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
266 if (!AliveBits.count(&I)) {
267 AliveBits[&I] = APInt(IT->getBitWidth(), 0);
268 Worklist.push_back(&I);
274 // Non-integer-typed instructions...
275 for (Use &OI : I.operands()) {
276 if (Instruction *J = dyn_cast<Instruction>(OI)) {
277 if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
278 AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
279 Worklist.push_back(J);
282 // To save memory, we don't add I to the Visited set here. Instead, we
283 // check isAlwaysLive on every instruction when searching for dead
284 // instructions later (we need to check isAlwaysLive for the
285 // integer-typed instructions anyway).
288 // Propagate liveness backwards to operands.
289 while (!Worklist.empty()) {
290 Instruction *UserI = Worklist.pop_back_val();
292 DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
294 if (UserI->getType()->isIntegerTy()) {
295 AOut = AliveBits[UserI];
296 DEBUG(dbgs() << " Alive Out: " << AOut);
298 DEBUG(dbgs() << "\n");
300 if (!UserI->getType()->isIntegerTy())
301 Visited.insert(UserI);
303 APInt KnownZero, KnownOne, KnownZero2, KnownOne2;
304 // Compute the set of alive bits for each operand. These are anded into the
305 // existing set, if any, and if that changes the set of alive bits, the
306 // operand is added to the work-list.
307 for (Use &OI : UserI->operands()) {
308 if (Instruction *I = dyn_cast<Instruction>(OI)) {
309 if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
310 unsigned BitWidth = IT->getBitWidth();
311 APInt AB = APInt::getAllOnesValue(BitWidth);
312 if (UserI->getType()->isIntegerTy() && !AOut &&
313 !isAlwaysLive(UserI)) {
314 AB = APInt(BitWidth, 0);
316 // If all bits of the output are dead, then all bits of the input
317 // Bits of each operand that are used to compute alive bits of the
318 // output are alive, all others are dead.
319 determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
321 KnownZero2, KnownOne2);
324 // If we've added to the set of alive bits (or the operand has not
325 // been previously visited), then re-queue the operand to be visited
327 APInt ABPrev(BitWidth, 0);
328 auto ABI = AliveBits.find(I);
329 if (ABI != AliveBits.end())
330 ABPrev = ABI->second;
332 APInt ABNew = AB | ABPrev;
333 if (ABNew != ABPrev || ABI == AliveBits.end()) {
334 AliveBits[I] = std::move(ABNew);
335 Worklist.push_back(I);
337 } else if (!Visited.count(I)) {
338 Worklist.push_back(I);
347 APInt DemandedBits::getDemandedBits(Instruction *I) {
348 const DataLayout &DL = I->getParent()->getModule()->getDataLayout();
349 if (AliveBits.count(I))
351 return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType()));
354 bool DemandedBits::isInstructionDead(Instruction *I) {
355 return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
359 FunctionPass *llvm::createDemandedBitsPass() {
360 return new DemandedBits();