blob: 151c0b0e6c9331dace41cf43b46b8c68dd2a6440 [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"
James Molloy87405c72015-08-14 11:09:09 +000023#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
James Molloybcd7f0a2015-10-08 12:39:59 +000026#include "llvm/ADT/StringExtras.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000027#include "llvm/Analysis/AssumptionCache.h"
James Molloy87405c72015-08-14 11:09:09 +000028#include "llvm/Analysis/ValueTracking.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/raw_ostream.h"
41using namespace llvm;
42
43#define DEBUG_TYPE "demanded-bits"
44
Michael Kupersteinde16b442016-04-18 23:55:01 +000045char DemandedBitsWrapperPass::ID = 0;
46INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass, "demanded-bits",
47 "Demanded bits analysis", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000048INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
James Molloy87405c72015-08-14 11:09:09 +000049INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Michael Kupersteinde16b442016-04-18 23:55:01 +000050INITIALIZE_PASS_END(DemandedBitsWrapperPass, "demanded-bits",
51 "Demanded bits analysis", false, false)
James Molloy87405c72015-08-14 11:09:09 +000052
Michael Kupersteinde16b442016-04-18 23:55:01 +000053DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) {
54 initializeDemandedBitsWrapperPassPass(*PassRegistry::getPassRegistry());
James Molloy87405c72015-08-14 11:09:09 +000055}
56
Michael Kupersteinde16b442016-04-18 23:55:01 +000057void DemandedBitsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
James Molloy87405c72015-08-14 11:09:09 +000058 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +000059 AU.addRequired<AssumptionCacheTracker>();
James Molloy87405c72015-08-14 11:09:09 +000060 AU.addRequired<DominatorTreeWrapperPass>();
61 AU.setPreservesAll();
62}
63
Michael Kupersteinde16b442016-04-18 23:55:01 +000064void DemandedBitsWrapperPass::print(raw_ostream &OS, const Module *M) const {
65 DB->print(OS);
66}
67
James Molloy87405c72015-08-14 11:09:09 +000068static bool isAlwaysLive(Instruction *I) {
69 return isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
70 I->isEHPad() || I->mayHaveSideEffects();
71}
72
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +000073void DemandedBits::determineLiveOperandBits(
74 const Instruction *UserI, const Instruction *I, unsigned OperandNo,
75 const APInt &AOut, APInt &AB, APInt &KnownZero, APInt &KnownOne,
76 APInt &KnownZero2, APInt &KnownOne2) {
James Molloy87405c72015-08-14 11:09:09 +000077 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 KnownZero = APInt(BitWidth, 0);
89 KnownOne = APInt(BitWidth, 0);
90 computeKnownBits(const_cast<Value *>(V1), KnownZero, KnownOne, DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000091 &AC, UserI, &DT);
James Molloy87405c72015-08-14 11:09:09 +000092
93 if (V2) {
94 KnownZero2 = APInt(BitWidth, 0);
95 KnownOne2 = APInt(BitWidth, 0);
96 computeKnownBits(const_cast<Value *>(V2), KnownZero2, KnownOne2, DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000097 0, &AC, UserI, &DT);
James Molloy87405c72015-08-14 11:09:09 +000098 }
99 };
100
101 switch (UserI->getOpcode()) {
102 default: break;
103 case Instruction::Call:
104 case Instruction::Invoke:
105 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(UserI))
106 switch (II->getIntrinsicID()) {
107 default: break;
108 case Intrinsic::bswap:
109 // The alive bits of the input are the swapped alive bits of
110 // the output.
111 AB = AOut.byteSwap();
112 break;
Brian Gesiak0a7894d2017-04-13 16:44:25 +0000113 case Intrinsic::bitreverse:
114 AB = AOut.reverseBits();
115 break;
James Molloy87405c72015-08-14 11:09:09 +0000116 case Intrinsic::ctlz:
117 if (OperandNo == 0) {
118 // We need some output bits, so we need all bits of the
119 // input to the left of, and including, the leftmost bit
120 // known to be one.
121 ComputeKnownBits(BitWidth, I, nullptr);
122 AB = APInt::getHighBitsSet(BitWidth,
123 std::min(BitWidth, KnownOne.countLeadingZeros()+1));
124 }
125 break;
126 case Intrinsic::cttz:
127 if (OperandNo == 0) {
128 // We need some output bits, so we need all bits of the
129 // input to the right of, and including, the rightmost bit
130 // known to be one.
131 ComputeKnownBits(BitWidth, I, nullptr);
132 AB = APInt::getLowBitsSet(BitWidth,
133 std::min(BitWidth, KnownOne.countTrailingZeros()+1));
134 }
135 break;
136 }
137 break;
138 case Instruction::Add:
139 case Instruction::Sub:
James Molloybcd7f0a2015-10-08 12:39:59 +0000140 case Instruction::Mul:
James Molloy87405c72015-08-14 11:09:09 +0000141 // Find the highest live output bit. We don't need any more input
142 // bits than that (adds, and thus subtracts, ripple only to the
143 // left).
144 AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
145 break;
146 case Instruction::Shl:
147 if (OperandNo == 0)
148 if (ConstantInt *CI =
149 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
150 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
151 AB = AOut.lshr(ShiftAmt);
152
153 // If the shift is nuw/nsw, then the high bits are not dead
154 // (because we've promised that they *must* be zero).
155 const ShlOperator *S = cast<ShlOperator>(UserI);
156 if (S->hasNoSignedWrap())
157 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
158 else if (S->hasNoUnsignedWrap())
159 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
160 }
161 break;
162 case Instruction::LShr:
163 if (OperandNo == 0)
164 if (ConstantInt *CI =
165 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
166 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
167 AB = AOut.shl(ShiftAmt);
168
169 // If the shift is exact, then the low bits are not dead
170 // (they must be zero).
171 if (cast<LShrOperator>(UserI)->isExact())
172 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
173 }
174 break;
175 case Instruction::AShr:
176 if (OperandNo == 0)
177 if (ConstantInt *CI =
178 dyn_cast<ConstantInt>(UserI->getOperand(1))) {
179 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1);
180 AB = AOut.shl(ShiftAmt);
181 // Because the high input bit is replicated into the
182 // high-order bits of the result, if we need any of those
183 // bits, then we must keep the highest input bit.
184 if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
185 .getBoolValue())
186 AB.setBit(BitWidth-1);
187
188 // If the shift is exact, then the low bits are not dead
189 // (they must be zero).
190 if (cast<AShrOperator>(UserI)->isExact())
191 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
192 }
193 break;
194 case Instruction::And:
195 AB = AOut;
196
197 // For bits that are known zero, the corresponding bits in the
198 // other operand are dead (unless they're both zero, in which
199 // case they can't both be dead, so just mark the LHS bits as
200 // dead).
201 if (OperandNo == 0) {
202 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
203 AB &= ~KnownZero2;
204 } else {
205 if (!isa<Instruction>(UserI->getOperand(0)))
206 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
207 AB &= ~(KnownZero & ~KnownZero2);
208 }
209 break;
210 case Instruction::Or:
211 AB = AOut;
212
213 // For bits that are known one, the corresponding bits in the
214 // other operand are dead (unless they're both one, in which
215 // case they can't both be dead, so just mark the LHS bits as
216 // dead).
217 if (OperandNo == 0) {
218 ComputeKnownBits(BitWidth, I, UserI->getOperand(1));
219 AB &= ~KnownOne2;
220 } else {
221 if (!isa<Instruction>(UserI->getOperand(0)))
222 ComputeKnownBits(BitWidth, UserI->getOperand(0), I);
223 AB &= ~(KnownOne & ~KnownOne2);
224 }
225 break;
226 case Instruction::Xor:
227 case Instruction::PHI:
228 AB = AOut;
229 break;
230 case Instruction::Trunc:
231 AB = AOut.zext(BitWidth);
232 break;
233 case Instruction::ZExt:
234 AB = AOut.trunc(BitWidth);
235 break;
236 case Instruction::SExt:
237 AB = AOut.trunc(BitWidth);
238 // Because the high input bit is replicated into the
239 // high-order bits of the result, if we need any of those
240 // bits, then we must keep the highest input bit.
241 if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
242 AOut.getBitWidth() - BitWidth))
243 .getBoolValue())
244 AB.setBit(BitWidth-1);
245 break;
246 case Instruction::Select:
247 if (OperandNo != 0)
248 AB = AOut;
249 break;
250 }
251}
252
Michael Kupersteinde16b442016-04-18 23:55:01 +0000253bool DemandedBitsWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000254 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000255 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000256 DB.emplace(F, AC, DT);
James Molloyab9fdb92015-10-08 12:39:50 +0000257 return false;
258}
James Molloy87405c72015-08-14 11:09:09 +0000259
Michael Kupersteinde16b442016-04-18 23:55:01 +0000260void DemandedBitsWrapperPass::releaseMemory() {
261 DB.reset();
262}
263
James Molloyab9fdb92015-10-08 12:39:50 +0000264void DemandedBits::performAnalysis() {
265 if (Analyzed)
266 // Analysis already completed for this function.
267 return;
268 Analyzed = true;
James Molloyab9fdb92015-10-08 12:39:50 +0000269
James Molloy87405c72015-08-14 11:09:09 +0000270 Visited.clear();
271 AliveBits.clear();
272
273 SmallVector<Instruction*, 128> Worklist;
274
275 // Collect the set of "root" instructions that are known live.
Michael Kupersteinde16b442016-04-18 23:55:01 +0000276 for (Instruction &I : instructions(F)) {
James Molloy87405c72015-08-14 11:09:09 +0000277 if (!isAlwaysLive(&I))
278 continue;
279
280 DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
281 // For integer-valued instructions, set up an initial empty set of alive
282 // bits and add the instruction to the work list. For other instructions
283 // add their operands to the work list (for integer values operands, mark
284 // all bits as live).
285 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
Benjamin Kramera9e477b2016-07-21 13:37:55 +0000286 if (AliveBits.try_emplace(&I, IT->getBitWidth(), 0).second)
James Molloy87405c72015-08-14 11:09:09 +0000287 Worklist.push_back(&I);
James Molloy87405c72015-08-14 11:09:09 +0000288
289 continue;
290 }
291
292 // Non-integer-typed instructions...
293 for (Use &OI : I.operands()) {
294 if (Instruction *J = dyn_cast<Instruction>(OI)) {
295 if (IntegerType *IT = dyn_cast<IntegerType>(J->getType()))
296 AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth());
297 Worklist.push_back(J);
298 }
299 }
300 // To save memory, we don't add I to the Visited set here. Instead, we
301 // check isAlwaysLive on every instruction when searching for dead
302 // instructions later (we need to check isAlwaysLive for the
303 // integer-typed instructions anyway).
304 }
305
306 // Propagate liveness backwards to operands.
307 while (!Worklist.empty()) {
308 Instruction *UserI = Worklist.pop_back_val();
309
310 DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
311 APInt AOut;
312 if (UserI->getType()->isIntegerTy()) {
313 AOut = AliveBits[UserI];
314 DEBUG(dbgs() << " Alive Out: " << AOut);
315 }
316 DEBUG(dbgs() << "\n");
317
318 if (!UserI->getType()->isIntegerTy())
319 Visited.insert(UserI);
320
321 APInt KnownZero, KnownOne, KnownZero2, KnownOne2;
322 // Compute the set of alive bits for each operand. These are anded into the
323 // existing set, if any, and if that changes the set of alive bits, the
324 // operand is added to the work-list.
325 for (Use &OI : UserI->operands()) {
326 if (Instruction *I = dyn_cast<Instruction>(OI)) {
327 if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) {
328 unsigned BitWidth = IT->getBitWidth();
329 APInt AB = APInt::getAllOnesValue(BitWidth);
330 if (UserI->getType()->isIntegerTy() && !AOut &&
331 !isAlwaysLive(UserI)) {
332 AB = APInt(BitWidth, 0);
333 } else {
NAKAMURA Takumi84965032015-09-22 11:14:12 +0000334 // If all bits of the output are dead, then all bits of the input
James Molloy87405c72015-08-14 11:09:09 +0000335 // Bits of each operand that are used to compute alive bits of the
336 // output are alive, all others are dead.
337 determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB,
338 KnownZero, KnownOne,
339 KnownZero2, KnownOne2);
340 }
341
342 // If we've added to the set of alive bits (or the operand has not
343 // been previously visited), then re-queue the operand to be visited
344 // again.
345 APInt ABPrev(BitWidth, 0);
346 auto ABI = AliveBits.find(I);
347 if (ABI != AliveBits.end())
348 ABPrev = ABI->second;
349
350 APInt ABNew = AB | ABPrev;
351 if (ABNew != ABPrev || ABI == AliveBits.end()) {
352 AliveBits[I] = std::move(ABNew);
353 Worklist.push_back(I);
354 }
355 } else if (!Visited.count(I)) {
356 Worklist.push_back(I);
357 }
358 }
359 }
360 }
James Molloy87405c72015-08-14 11:09:09 +0000361}
362
363APInt DemandedBits::getDemandedBits(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000364 performAnalysis();
365
James Molloy87405c72015-08-14 11:09:09 +0000366 const DataLayout &DL = I->getParent()->getModule()->getDataLayout();
Benjamin Kramera9e477b2016-07-21 13:37:55 +0000367 auto Found = AliveBits.find(I);
368 if (Found != AliveBits.end())
369 return Found->second;
James Molloy87405c72015-08-14 11:09:09 +0000370 return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType()));
371}
372
373bool DemandedBits::isInstructionDead(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000374 performAnalysis();
375
James Molloy87405c72015-08-14 11:09:09 +0000376 return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() &&
377 !isAlwaysLive(I);
378}
379
Michael Kupersteinde16b442016-04-18 23:55:01 +0000380void DemandedBits::print(raw_ostream &OS) {
381 performAnalysis();
James Molloybcd7f0a2015-10-08 12:39:59 +0000382 for (auto &KV : AliveBits) {
383 OS << "DemandedBits: 0x" << utohexstr(KV.second.getLimitedValue()) << " for "
384 << *KV.first << "\n";
385 }
386}
387
Michael Kupersteinde16b442016-04-18 23:55:01 +0000388FunctionPass *llvm::createDemandedBitsWrapperPass() {
389 return new DemandedBitsWrapperPass();
390}
391
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000392AnalysisKey DemandedBitsAnalysis::Key;
Michael Kupersteinde16b442016-04-18 23:55:01 +0000393
394DemandedBits DemandedBitsAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000395 FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000396 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000397 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000398 return DemandedBits(F, AC, DT);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000399}
400
401PreservedAnalyses DemandedBitsPrinterPass::run(Function &F,
402 FunctionAnalysisManager &AM) {
403 AM.getResult<DemandedBitsAnalysis>(F).print(OS);
404 return PreservedAnalyses::all();
James Molloy87405c72015-08-14 11:09:09 +0000405}