blob: 775cbac4c53ed4089761e92b042b8a9c4ee463fa [file] [log] [blame]
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001//===---- DemandedBits.cpp - Determine demanded bits ----------------------===//
James Molloy87405c72015-08-14 11:09:09 +00002//
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
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"
42using namespace llvm;
43
44#define DEBUG_TYPE "demanded-bits"
45
46char DemandedBits::ID = 0;
47INITIALIZE_PASS_BEGIN(DemandedBits, "demanded-bits", "Demanded bits analysis",
48 false, false)
49INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
50INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
51INITIALIZE_PASS_END(DemandedBits, "demanded-bits", "Demanded bits analysis",
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +000052 false, false)
James Molloy87405c72015-08-14 11:09:09 +000053
James Molloyab9fdb92015-10-08 12:39:50 +000054DemandedBits::DemandedBits() : FunctionPass(ID), F(nullptr), Analyzed(false) {
James Molloy87405c72015-08-14 11:09:09 +000055 initializeDemandedBitsPass(*PassRegistry::getPassRegistry());
56}
57
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +000058void DemandedBits::getAnalysisUsage(AnalysisUsage &AU) const {
James Molloy87405c72015-08-14 11:09:09 +000059 AU.setPreservesCFG();
60 AU.addRequired<AssumptionCacheTracker>();
61 AU.addRequired<DominatorTreeWrapperPass>();
62 AU.setPreservesAll();
63}
64
65static bool isAlwaysLive(Instruction *I) {
66 return isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
67 I->isEHPad() || I->mayHaveSideEffects();
68}
69
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +000070void 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) {
James Molloy87405c72015-08-14 11:09:09 +000074 unsigned BitWidth = AB.getBitWidth();
75
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
81 // provided here.
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,
88 AC, UserI, DT);
89
90 if (V2) {
91 KnownZero2 = APInt(BitWidth, 0);
92 KnownOne2 = APInt(BitWidth, 0);
93 computeKnownBits(const_cast<Value *>(V2), KnownZero2, KnownOne2, DL,
94 0, AC, UserI, DT);
95 }
96 };
97
98 switch (UserI->getOpcode()) {
99 default: break;
100 case Instruction::Call:
101 case Instruction::Invoke:
102 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
103 switch (II->getIntrinsicID()) {
104 default: break;
105 case Intrinsic::bswap:
106 // The alive bits of the input are the swapped alive bits of
107 // the output.
108 AB = AOut.byteSwap();
109 break;
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
114 // known to be one.
115 ComputeKnownBits(BitWidth, I, nullptr);
116 AB = APInt::getHighBitsSet(BitWidth,
117 std::min(BitWidth, KnownOne.countLeadingZeros()+1));
118 }
119 break;
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
124 // known to be one.
125 ComputeKnownBits(BitWidth, I, nullptr);
126 AB = APInt::getLowBitsSet(BitWidth,
127 std::min(BitWidth, KnownOne.countTrailingZeros()+1));
128 }
129 break;
130 }
131 break;
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
136 // left).
137 AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
138 break;
139 case Instruction::Shl:
140 if (OperandNo == 0)
141 if (ConstantInt *CI =
142 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
143 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
144 AB = AOut.lshr(ShiftAmt);
145
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);
153 }
154 break;
155 case Instruction::LShr:
156 if (OperandNo == 0)
157 if (ConstantInt *CI =
158 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
159 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
160 AB = AOut.shl(ShiftAmt);
161
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);
166 }
167 break;
168 case Instruction::AShr:
169 if (OperandNo == 0)
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))
178 .getBoolValue())
179 AB.setBit(BitWidth-1);
180
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);
185 }
186 break;
187 case Instruction::And:
188 AB = AOut;
189
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
193 // dead).
194 if (OperandNo == 0) {
195 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
196 AB &= ~KnownZero2;
197 } else {
198 if (!isa<Instruction>(UserI->getOperand(0)))
199 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
200 AB &= ~(KnownZero & ~KnownZero2);
201 }
202 break;
203 case Instruction::Or:
204 AB = AOut;
205
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
209 // dead).
210 if (OperandNo == 0) {
211 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
212 AB &= ~KnownOne2;
213 } else {
214 if (!isa<Instruction>(UserI->getOperand(0)))
215 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
216 AB &= ~(KnownOne & ~KnownOne2);
217 }
218 break;
219 case Instruction::Xor:
220 case Instruction::PHI:
221 AB = AOut;
222 break;
223 case Instruction::Trunc:
224 AB = AOut.zext(BitWidth);
225 break;
226 case Instruction::ZExt:
227 AB = AOut.trunc(BitWidth);
228 break;
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))
236 .getBoolValue())
237 AB.setBit(BitWidth-1);
238 break;
239 case Instruction::Select:
240 if (OperandNo != 0)
241 AB = AOut;
242 break;
243 }
244}
245
James Molloyab9fdb92015-10-08 12:39:50 +0000246bool DemandedBits::runOnFunction(Function& Fn) {
247 F = &Fn;
248 Analyzed = false;
249 return false;
250}
James Molloy87405c72015-08-14 11:09:09 +0000251
James Molloyab9fdb92015-10-08 12:39:50 +0000252void DemandedBits::performAnalysis() {
253 if (Analyzed)
254 // Analysis already completed for this function.
255 return;
256 Analyzed = true;
257 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
258 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
259
James Molloy87405c72015-08-14 11:09:09 +0000260 Visited.clear();
261 AliveBits.clear();
262
263 SmallVector<Instruction*, 128> Worklist;
264
265 // Collect the set of "root" instructions that are known live.
James Molloyab9fdb92015-10-08 12:39:50 +0000266 for (Instruction &I : instructions(*F)) {
James Molloy87405c72015-08-14 11:09:09 +0000267 if (!isAlwaysLive(&I))
268 continue;
269
270 DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
271 // For integer-valued instructions, set up an initial empty set of alive
272 // bits and add the instruction to the work list. For other instructions
273 // add their operands to the work list (for integer values operands, mark
274 // all bits as live).
275 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
276 if (!AliveBits.count(&I)) {
277 AliveBits[&I] = APInt(IT->getBitWidth(), 0);
278 Worklist.push_back(&I);
279 }
280
281 continue;
282 }
283
284 // Non-integer-typed instructions...
285 for (Use &OI : I.operands()) {
286 if (Instruction *J = dyn_cast<Instruction>(OI)) {
287 if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
288 AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
289 Worklist.push_back(J);
290 }
291 }
292 // To save memory, we don't add I to the Visited set here. Instead, we
293 // check isAlwaysLive on every instruction when searching for dead
294 // instructions later (we need to check isAlwaysLive for the
295 // integer-typed instructions anyway).
296 }
297
298 // Propagate liveness backwards to operands.
299 while (!Worklist.empty()) {
300 Instruction *UserI = Worklist.pop_back_val();
301
302 DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
303 APInt AOut;
304 if (UserI->getType()->isIntegerTy()) {
305 AOut = AliveBits[UserI];
306 DEBUG(dbgs() << " Alive Out: " << AOut);
307 }
308 DEBUG(dbgs() << "\n");
309
310 if (!UserI->getType()->isIntegerTy())
311 Visited.insert(UserI);
312
313 APInt KnownZero, KnownOne, KnownZero2, KnownOne2;
314 // Compute the set of alive bits for each operand. These are anded into the
315 // existing set, if any, and if that changes the set of alive bits, the
316 // operand is added to the work-list.
317 for (Use &OI : UserI->operands()) {
318 if (Instruction *I = dyn_cast<Instruction>(OI)) {
319 if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
320 unsigned BitWidth = IT->getBitWidth();
321 APInt AB = APInt::getAllOnesValue(BitWidth);
322 if (UserI->getType()->isIntegerTy() && !AOut &&
323 !isAlwaysLive(UserI)) {
324 AB = APInt(BitWidth, 0);
325 } else {
NAKAMURA Takumi84965032015-09-22 11:14:12 +0000326 // If all bits of the output are dead, then all bits of the input
James Molloy87405c72015-08-14 11:09:09 +0000327 // Bits of each operand that are used to compute alive bits of the
328 // output are alive, all others are dead.
329 determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
330 KnownZero, KnownOne,
331 KnownZero2, KnownOne2);
332 }
333
334 // If we've added to the set of alive bits (or the operand has not
335 // been previously visited), then re-queue the operand to be visited
336 // again.
337 APInt ABPrev(BitWidth, 0);
338 auto ABI = AliveBits.find(I);
339 if (ABI != AliveBits.end())
340 ABPrev = ABI->second;
341
342 APInt ABNew = AB | ABPrev;
343 if (ABNew != ABPrev || ABI == AliveBits.end()) {
344 AliveBits[I] = std::move(ABNew);
345 Worklist.push_back(I);
346 }
347 } else if (!Visited.count(I)) {
348 Worklist.push_back(I);
349 }
350 }
351 }
352 }
James Molloy87405c72015-08-14 11:09:09 +0000353}
354
355APInt DemandedBits::getDemandedBits(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000356 performAnalysis();
357
James Molloy87405c72015-08-14 11:09:09 +0000358 const DataLayout &DL = I->getParent()->getModule()->getDataLayout();
359 if (AliveBits.count(I))
360 return AliveBits[I];
361 return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType()));
362}
363
364bool DemandedBits::isInstructionDead(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000365 performAnalysis();
366
James Molloy87405c72015-08-14 11:09:09 +0000367 return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
368 !isAlwaysLive(I);
369}
370
371FunctionPass *llvm::createDemandedBitsPass() {
372 return new DemandedBits();
373}