blob: b538e16f258595e13af72251578e74dde2fd1709 [file] [log] [blame]
Eugene Zelenko38c02bc2017-07-21 21:37:46 +00001//===- DemandedBits.cpp - Determine demanded bits -------------------------===//
James Molloy87405c72015-08-14 11:09:09 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
James Molloy87405c72015-08-14 11:09:09 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements a demanded bits analysis. A demanded bit is one that
10// contributes to a result; bits that are not demanded can be either zero or
11// one without affecting control or data flow. For example in this sequence:
12//
13// %1 = add i32 %x, %y
14// %2 = trunc i32 %1 to i16
15//
16// Only the lowest 16 bits of %1 are demanded; the rest are removed by the
17// trunc.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Analysis/DemandedBits.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000022#include "llvm/ADT/APInt.h"
Nikita Popov5f393eb2019-01-12 09:09:15 +000023#include "llvm/ADT/SetVector.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000024#include "llvm/Analysis/AssumptionCache.h"
James Molloy87405c72015-08-14 11:09:09 +000025#include "llvm/Analysis/ValueTracking.h"
James Molloy87405c72015-08-14 11:09:09 +000026#include "llvm/IR/DataLayout.h"
James Molloy87405c72015-08-14 11:09:09 +000027#include "llvm/IR/Dominators.h"
28#include "llvm/IR/InstIterator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000029#include "llvm/IR/Instruction.h"
James Molloy87405c72015-08-14 11:09:09 +000030#include "llvm/IR/IntrinsicInst.h"
James Molloy87405c72015-08-14 11:09:09 +000031#include "llvm/IR/Operator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000032#include "llvm/IR/PassManager.h"
Nikita Popov110cf052018-12-07 15:38:13 +000033#include "llvm/IR/PatternMatch.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000034#include "llvm/IR/Type.h"
35#include "llvm/IR/Use.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000036#include "llvm/Support/Casting.h"
James Molloy87405c72015-08-14 11:09:09 +000037#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000038#include "llvm/Support/KnownBits.h"
James Molloy87405c72015-08-14 11:09:09 +000039#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000040#include <algorithm>
41#include <cstdint>
42
James Molloy87405c72015-08-14 11:09:09 +000043using namespace llvm;
Nikita Popov110cf052018-12-07 15:38:13 +000044using namespace llvm::PatternMatch;
James Molloy87405c72015-08-14 11:09:09 +000045
46#define DEBUG_TYPE "demanded-bits"
47
James Molloy87405c72015-08-14 11:09:09 +000048static bool isAlwaysLive(Instruction *I) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +000049 return I->isTerminator() || isa<DbgInfoIntrinsic>(I) || I->isEHPad() ||
Nikita Popov33146852021-07-21 21:23:38 +020050 I->mayHaveSideEffects();
James Molloy87405c72015-08-14 11:09:09 +000051}
52
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +000053void DemandedBits::determineLiveOperandBits(
Nikita Popov6658fce2019-01-04 21:21:43 +000054 const Instruction *UserI, const Value *Val, unsigned OperandNo,
55 const APInt &AOut, APInt &AB, KnownBits &Known, KnownBits &Known2,
56 bool &KnownBitsComputed) {
James Molloy87405c72015-08-14 11:09:09 +000057 unsigned BitWidth = AB.getBitWidth();
58
59 // We're called once per operand, but for some instructions, we need to
60 // compute known bits of both operands in order to determine the live bits of
61 // either (when both operands are instructions themselves). We don't,
62 // however, want to do this twice, so we cache the result in APInts that live
63 // in the caller. For the two-relevant-operands case, both operand values are
64 // provided here.
65 auto ComputeKnownBits =
66 [&](unsigned BitWidth, const Value *V1, const Value *V2) {
Nikita Popov6658fce2019-01-04 21:21:43 +000067 if (KnownBitsComputed)
68 return;
69 KnownBitsComputed = true;
70
Nikita Popov2d209d92024-06-27 16:38:15 +020071 const DataLayout &DL = UserI->getDataLayout();
Nikita Popovd4300152023-10-16 14:03:06 +020072 Known = KnownBits(BitWidth);
73 computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT);
James Molloy87405c72015-08-14 11:09:09 +000074
Nikita Popovd4300152023-10-16 14:03:06 +020075 if (V2) {
76 Known2 = KnownBits(BitWidth);
77 computeKnownBits(V2, Known2, DL, 0, &AC, UserI, &DT);
78 }
James Molloy87405c72015-08-14 11:09:09 +000079 };
80
81 switch (UserI->getOpcode()) {
82 default: break;
83 case Instruction::Call:
84 case Instruction::Invoke:
Simon Pilgrim738370a2023-02-12 14:57:11 +000085 if (const auto *II = dyn_cast<IntrinsicInst>(UserI)) {
James Molloy87405c72015-08-14 11:09:09 +000086 switch (II->getIntrinsicID()) {
87 default: break;
88 case Intrinsic::bswap:
89 // The alive bits of the input are the swapped alive bits of
90 // the output.
91 AB = AOut.byteSwap();
92 break;
Brian Gesiak0a7894d2017-04-13 16:44:25 +000093 case Intrinsic::bitreverse:
Xin Tongbb8dbcf2017-06-19 20:10:41 +000094 // The alive bits of the input are the reversed alive bits of
95 // the output.
Brian Gesiak0a7894d2017-04-13 16:44:25 +000096 AB = AOut.reverseBits();
97 break;
James Molloy87405c72015-08-14 11:09:09 +000098 case Intrinsic::ctlz:
99 if (OperandNo == 0) {
100 // We need some output bits, so we need all bits of the
101 // input to the left of, and including, the leftmost bit
102 // known to be one.
Nikita Popov6658fce2019-01-04 21:21:43 +0000103 ComputeKnownBits(BitWidth, Val, nullptr);
James Molloy87405c72015-08-14 11:09:09 +0000104 AB = APInt::getHighBitsSet(BitWidth,
Craig Topper8df66c62017-05-12 17:20:30 +0000105 std::min(BitWidth, Known.countMaxLeadingZeros()+1));
James Molloy87405c72015-08-14 11:09:09 +0000106 }
107 break;
108 case Intrinsic::cttz:
109 if (OperandNo == 0) {
110 // We need some output bits, so we need all bits of the
111 // input to the right of, and including, the rightmost bit
112 // known to be one.
Nikita Popov6658fce2019-01-04 21:21:43 +0000113 ComputeKnownBits(BitWidth, Val, nullptr);
James Molloy87405c72015-08-14 11:09:09 +0000114 AB = APInt::getLowBitsSet(BitWidth,
Craig Topper8df66c62017-05-12 17:20:30 +0000115 std::min(BitWidth, Known.countMaxTrailingZeros()+1));
James Molloy87405c72015-08-14 11:09:09 +0000116 }
117 break;
Nikita Popovf94c8f02018-11-26 15:36:57 +0000118 case Intrinsic::fshl:
Nikita Popov110cf052018-12-07 15:38:13 +0000119 case Intrinsic::fshr: {
120 const APInt *SA;
Nikita Popovf94c8f02018-11-26 15:36:57 +0000121 if (OperandNo == 2) {
122 // Shift amount is modulo the bitwidth. For powers of two we have
123 // SA % BW == SA & (BW - 1).
124 if (isPowerOf2_32(BitWidth))
125 AB = BitWidth - 1;
Nikita Popov110cf052018-12-07 15:38:13 +0000126 } else if (match(II->getOperand(2), m_APInt(SA))) {
Nikita Popovf94c8f02018-11-26 15:36:57 +0000127 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
128 // defined, so no need to special-case zero shifts here.
Nikita Popov110cf052018-12-07 15:38:13 +0000129 uint64_t ShiftAmt = SA->urem(BitWidth);
Nikita Popovf94c8f02018-11-26 15:36:57 +0000130 if (II->getIntrinsicID() == Intrinsic::fshr)
131 ShiftAmt = BitWidth - ShiftAmt;
132
133 if (OperandNo == 0)
134 AB = AOut.lshr(ShiftAmt);
135 else if (OperandNo == 1)
136 AB = AOut.shl(BitWidth - ShiftAmt);
137 }
138 break;
James Molloy87405c72015-08-14 11:09:09 +0000139 }
Nikita Popova5168bd2020-09-04 22:40:46 +0200140 case Intrinsic::umax:
141 case Intrinsic::umin:
142 case Intrinsic::smax:
143 case Intrinsic::smin:
144 // If low bits of result are not demanded, they are also not demanded
145 // for the min/max operands.
Kazu Hirataf8f3db22023-02-19 22:04:47 -0800146 AB = APInt::getBitsSetFrom(BitWidth, AOut.countr_zero());
Nikita Popova5168bd2020-09-04 22:40:46 +0200147 break;
Nikita Popov110cf052018-12-07 15:38:13 +0000148 }
Nikita Popov99e78cb2020-09-10 22:11:04 +0200149 }
James Molloy87405c72015-08-14 11:09:09 +0000150 break;
151 case Instruction::Add:
Simon Pilgrimc1f6ce02020-08-17 12:53:52 +0100152 if (AOut.isMask()) {
153 AB = AOut;
154 } else {
155 ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
156 AB = determineLiveOperandBitsAdd(OperandNo, AOut, Known, Known2);
157 }
158 break;
James Molloy87405c72015-08-14 11:09:09 +0000159 case Instruction::Sub:
Simon Pilgrimc1f6ce02020-08-17 12:53:52 +0100160 if (AOut.isMask()) {
161 AB = AOut;
162 } else {
163 ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
164 AB = determineLiveOperandBitsSub(OperandNo, AOut, Known, Known2);
165 }
166 break;
James Molloybcd7f0a2015-10-08 12:39:59 +0000167 case Instruction::Mul:
James Molloy87405c72015-08-14 11:09:09 +0000168 // Find the highest live output bit. We don't need any more input
169 // bits than that (adds, and thus subtracts, ripple only to the
170 // left).
171 AB = APInt::getLowBitsSet(BitWidth, AOut.getActiveBits());
172 break;
173 case Instruction::Shl:
Nikita Popov110cf052018-12-07 15:38:13 +0000174 if (OperandNo == 0) {
175 const APInt *ShiftAmtC;
176 if (match(UserI->getOperand(1), m_APInt(ShiftAmtC))) {
Sanjay Patel1bbdf4e2017-07-07 14:39:26 +0000177 uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
James Molloy87405c72015-08-14 11:09:09 +0000178 AB = AOut.lshr(ShiftAmt);
179
180 // If the shift is nuw/nsw, then the high bits are not dead
181 // (because we've promised that they *must* be zero).
Simon Pilgrim738370a2023-02-12 14:57:11 +0000182 const auto *S = cast<ShlOperator>(UserI);
James Molloy87405c72015-08-14 11:09:09 +0000183 if (S->hasNoSignedWrap())
184 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
185 else if (S->hasNoUnsignedWrap())
186 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
187 }
Nikita Popov110cf052018-12-07 15:38:13 +0000188 }
James Molloy87405c72015-08-14 11:09:09 +0000189 break;
190 case Instruction::LShr:
Nikita Popov110cf052018-12-07 15:38:13 +0000191 if (OperandNo == 0) {
192 const APInt *ShiftAmtC;
193 if (match(UserI->getOperand(1), m_APInt(ShiftAmtC))) {
Sanjay Patel1bbdf4e2017-07-07 14:39:26 +0000194 uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
James Molloy87405c72015-08-14 11:09:09 +0000195 AB = AOut.shl(ShiftAmt);
196
197 // If the shift is exact, then the low bits are not dead
198 // (they must be zero).
199 if (cast<LShrOperator>(UserI)->isExact())
200 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
201 }
Nikita Popov110cf052018-12-07 15:38:13 +0000202 }
James Molloy87405c72015-08-14 11:09:09 +0000203 break;
204 case Instruction::AShr:
Nikita Popov110cf052018-12-07 15:38:13 +0000205 if (OperandNo == 0) {
206 const APInt *ShiftAmtC;
207 if (match(UserI->getOperand(1), m_APInt(ShiftAmtC))) {
Sanjay Patel1bbdf4e2017-07-07 14:39:26 +0000208 uint64_t ShiftAmt = ShiftAmtC->getLimitedValue(BitWidth - 1);
James Molloy87405c72015-08-14 11:09:09 +0000209 AB = AOut.shl(ShiftAmt);
210 // Because the high input bit is replicated into the
211 // high-order bits of the result, if we need any of those
212 // bits, then we must keep the highest input bit.
213 if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt))
214 .getBoolValue())
Craig Topper24db6b82017-04-28 16:58:05 +0000215 AB.setSignBit();
James Molloy87405c72015-08-14 11:09:09 +0000216
217 // If the shift is exact, then the low bits are not dead
218 // (they must be zero).
219 if (cast<AShrOperator>(UserI)->isExact())
220 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
221 }
Nikita Popov110cf052018-12-07 15:38:13 +0000222 }
James Molloy87405c72015-08-14 11:09:09 +0000223 break;
224 case Instruction::And:
225 AB = AOut;
226
227 // For bits that are known zero, the corresponding bits in the
228 // other operand are dead (unless they're both zero, in which
229 // case they can't both be dead, so just mark the LHS bits as
230 // dead).
Nikita Popov6658fce2019-01-04 21:21:43 +0000231 ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
232 if (OperandNo == 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000233 AB &= ~Known2.Zero;
Nikita Popov6658fce2019-01-04 21:21:43 +0000234 else
Craig Topperb45eabc2017-04-26 16:39:58 +0000235 AB &= ~(Known.Zero & ~Known2.Zero);
James Molloy87405c72015-08-14 11:09:09 +0000236 break;
237 case Instruction::Or:
238 AB = AOut;
239
240 // For bits that are known one, the corresponding bits in the
241 // other operand are dead (unless they're both one, in which
242 // case they can't both be dead, so just mark the LHS bits as
243 // dead).
Nikita Popov6658fce2019-01-04 21:21:43 +0000244 ComputeKnownBits(BitWidth, UserI->getOperand(0), UserI->getOperand(1));
245 if (OperandNo == 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000246 AB &= ~Known2.One;
Nikita Popov6658fce2019-01-04 21:21:43 +0000247 else
Craig Topperb45eabc2017-04-26 16:39:58 +0000248 AB &= ~(Known.One & ~Known2.One);
James Molloy87405c72015-08-14 11:09:09 +0000249 break;
250 case Instruction::Xor:
251 case Instruction::PHI:
252 AB = AOut;
253 break;
254 case Instruction::Trunc:
255 AB = AOut.zext(BitWidth);
256 break;
257 case Instruction::ZExt:
258 AB = AOut.trunc(BitWidth);
259 break;
260 case Instruction::SExt:
261 AB = AOut.trunc(BitWidth);
262 // Because the high input bit is replicated into the
263 // high-order bits of the result, if we need any of those
264 // bits, then we must keep the highest input bit.
265 if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(),
266 AOut.getBitWidth() - BitWidth))
267 .getBoolValue())
Craig Topper24db6b82017-04-28 16:58:05 +0000268 AB.setSignBit();
James Molloy87405c72015-08-14 11:09:09 +0000269 break;
270 case Instruction::Select:
271 if (OperandNo != 0)
272 AB = AOut;
273 break;
Nikita Popov110cf052018-12-07 15:38:13 +0000274 case Instruction::ExtractElement:
275 if (OperandNo == 0)
276 AB = AOut;
277 break;
278 case Instruction::InsertElement:
279 case Instruction::ShuffleVector:
280 if (OperandNo == 0 || OperandNo == 1)
281 AB = AOut;
282 break;
James Molloy87405c72015-08-14 11:09:09 +0000283 }
284}
285
James Molloyab9fdb92015-10-08 12:39:50 +0000286void DemandedBits::performAnalysis() {
287 if (Analyzed)
288 // Analysis already completed for this function.
289 return;
290 Analyzed = true;
Fangrui Songf78650a2018-07-30 19:41:25 +0000291
James Molloy87405c72015-08-14 11:09:09 +0000292 Visited.clear();
293 AliveBits.clear();
Nikita Popovbc9986e2019-01-01 10:05:26 +0000294 DeadUses.clear();
James Molloy87405c72015-08-14 11:09:09 +0000295
Nikita Popov5f393eb2019-01-12 09:09:15 +0000296 SmallSetVector<Instruction*, 16> Worklist;
James Molloy87405c72015-08-14 11:09:09 +0000297
298 // Collect the set of "root" instructions that are known live.
Michael Kupersteinde16b442016-04-18 23:55:01 +0000299 for (Instruction &I : instructions(F)) {
James Molloy87405c72015-08-14 11:09:09 +0000300 if (!isAlwaysLive(&I))
301 continue;
302
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000303 LLVM_DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n");
James Molloy87405c72015-08-14 11:09:09 +0000304 // For integer-valued instructions, set up an initial empty set of alive
305 // bits and add the instruction to the work list. For other instructions
306 // add their operands to the work list (for integer values operands, mark
307 // all bits as live).
Nikita Popov110cf052018-12-07 15:38:13 +0000308 Type *T = I.getType();
309 if (T->isIntOrIntVectorTy()) {
310 if (AliveBits.try_emplace(&I, T->getScalarSizeInBits(), 0).second)
Nikita Popov5f393eb2019-01-12 09:09:15 +0000311 Worklist.insert(&I);
James Molloy87405c72015-08-14 11:09:09 +0000312
313 continue;
314 }
315
316 // Non-integer-typed instructions...
317 for (Use &OI : I.operands()) {
Simon Pilgrim738370a2023-02-12 14:57:11 +0000318 if (auto *J = dyn_cast<Instruction>(OI)) {
Nikita Popov110cf052018-12-07 15:38:13 +0000319 Type *T = J->getType();
320 if (T->isIntOrIntVectorTy())
Chris Lattner735f4672021-09-08 22:13:13 -0700321 AliveBits[J] = APInt::getAllOnes(T->getScalarSizeInBits());
Fangrui Song5fa53d152019-03-03 14:50:01 +0000322 else
323 Visited.insert(J);
Nikita Popov5f393eb2019-01-12 09:09:15 +0000324 Worklist.insert(J);
James Molloy87405c72015-08-14 11:09:09 +0000325 }
326 }
327 // To save memory, we don't add I to the Visited set here. Instead, we
328 // check isAlwaysLive on every instruction when searching for dead
329 // instructions later (we need to check isAlwaysLive for the
330 // integer-typed instructions anyway).
331 }
332
333 // Propagate liveness backwards to operands.
334 while (!Worklist.empty()) {
335 Instruction *UserI = Worklist.pop_back_val();
336
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000337 LLVM_DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI);
James Molloy87405c72015-08-14 11:09:09 +0000338 APInt AOut;
Fangrui Song5fa53d152019-03-03 14:50:01 +0000339 bool InputIsKnownDead = false;
Nikita Popov110cf052018-12-07 15:38:13 +0000340 if (UserI->getType()->isIntOrIntVectorTy()) {
James Molloy87405c72015-08-14 11:09:09 +0000341 AOut = AliveBits[UserI];
Nikita Popovbc9986e2019-01-01 10:05:26 +0000342 LLVM_DEBUG(dbgs() << " Alive Out: 0x"
343 << Twine::utohexstr(AOut.getLimitedValue()));
Fangrui Song5fa53d152019-03-03 14:50:01 +0000344
345 // If all bits of the output are dead, then all bits of the input
346 // are also dead.
347 InputIsKnownDead = !AOut && !isAlwaysLive(UserI);
James Molloy87405c72015-08-14 11:09:09 +0000348 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000349 LLVM_DEBUG(dbgs() << "\n");
James Molloy87405c72015-08-14 11:09:09 +0000350
Craig Topperb45eabc2017-04-26 16:39:58 +0000351 KnownBits Known, Known2;
Nikita Popov6658fce2019-01-04 21:21:43 +0000352 bool KnownBitsComputed = false;
James Molloy87405c72015-08-14 11:09:09 +0000353 // Compute the set of alive bits for each operand. These are anded into the
354 // existing set, if any, and if that changes the set of alive bits, the
355 // operand is added to the work-list.
356 for (Use &OI : UserI->operands()) {
Nikita Popov6658fce2019-01-04 21:21:43 +0000357 // We also want to detect dead uses of arguments, but will only store
358 // demanded bits for instructions.
Simon Pilgrim738370a2023-02-12 14:57:11 +0000359 auto *I = dyn_cast<Instruction>(OI);
Nikita Popov6658fce2019-01-04 21:21:43 +0000360 if (!I && !isa<Argument>(OI))
361 continue;
Nikita Popovbc9986e2019-01-01 10:05:26 +0000362
Nikita Popov6658fce2019-01-04 21:21:43 +0000363 Type *T = OI->getType();
364 if (T->isIntOrIntVectorTy()) {
365 unsigned BitWidth = T->getScalarSizeInBits();
Chris Lattner735f4672021-09-08 22:13:13 -0700366 APInt AB = APInt::getAllOnes(BitWidth);
Fangrui Song5fa53d152019-03-03 14:50:01 +0000367 if (InputIsKnownDead) {
Nikita Popov6658fce2019-01-04 21:21:43 +0000368 AB = APInt(BitWidth, 0);
369 } else {
370 // Bits of each operand that are used to compute alive bits of the
371 // output are alive, all others are dead.
372 determineLiveOperandBits(UserI, OI, OI.getOperandNo(), AOut, AB,
373 Known, Known2, KnownBitsComputed);
Nikita Popov649e1252018-12-19 19:56:21 +0000374
Nikita Popov6658fce2019-01-04 21:21:43 +0000375 // Keep track of uses which have no demanded bits.
Chris Lattner735f4672021-09-08 22:13:13 -0700376 if (AB.isZero())
Nikita Popov6658fce2019-01-04 21:21:43 +0000377 DeadUses.insert(&OI);
378 else
379 DeadUses.erase(&OI);
380 }
381
382 if (I) {
Nikita Popov649e1252018-12-19 19:56:21 +0000383 // If we've added to the set of alive bits (or the operand has not
384 // been previously visited), then re-queue the operand to be visited
385 // again.
Fangrui Song981f2162019-03-03 11:12:57 +0000386 auto Res = AliveBits.try_emplace(I);
387 if (Res.second || (AB |= Res.first->second) != Res.first->second) {
388 Res.first->second = std::move(AB);
Nikita Popov5f393eb2019-01-12 09:09:15 +0000389 Worklist.insert(I);
James Molloy87405c72015-08-14 11:09:09 +0000390 }
James Molloy87405c72015-08-14 11:09:09 +0000391 }
Fangrui Song5fa53d152019-03-03 14:50:01 +0000392 } else if (I && Visited.insert(I).second) {
Nikita Popov5f393eb2019-01-12 09:09:15 +0000393 Worklist.insert(I);
James Molloy87405c72015-08-14 11:09:09 +0000394 }
395 }
396 }
James Molloy87405c72015-08-14 11:09:09 +0000397}
398
399APInt DemandedBits::getDemandedBits(Instruction *I) {
Nikita Popovcf65b922018-12-06 23:50:32 +0000400 performAnalysis();
Nikita Popov14ca9a82018-12-07 00:42:03 +0000401
Benjamin Kramera9e477b2016-07-21 13:37:55 +0000402 auto Found = AliveBits.find(I);
403 if (Found != AliveBits.end())
404 return Found->second;
Nikita Popov110cf052018-12-07 15:38:13 +0000405
Nikita Popov2d209d92024-06-27 16:38:15 +0200406 const DataLayout &DL = I->getDataLayout();
Chris Lattner735f4672021-09-08 22:13:13 -0700407 return APInt::getAllOnes(DL.getTypeSizeInBits(I->getType()->getScalarType()));
James Molloy87405c72015-08-14 11:09:09 +0000408}
409
Qunyan Manguscbde2482021-06-02 10:07:40 -0400410APInt DemandedBits::getDemandedBits(Use *U) {
411 Type *T = (*U)->getType();
Simon Pilgrim738370a2023-02-12 14:57:11 +0000412 auto *UserI = cast<Instruction>(U->getUser());
Nikita Popov2d209d92024-06-27 16:38:15 +0200413 const DataLayout &DL = UserI->getDataLayout();
Qunyan Manguscbde2482021-06-02 10:07:40 -0400414 unsigned BitWidth = DL.getTypeSizeInBits(T->getScalarType());
415
416 // We only track integer uses, everything else produces a mask with all bits
417 // set
418 if (!T->isIntOrIntVectorTy())
Chris Lattner735f4672021-09-08 22:13:13 -0700419 return APInt::getAllOnes(BitWidth);
Qunyan Manguscbde2482021-06-02 10:07:40 -0400420
421 if (isUseDead(U))
422 return APInt(BitWidth, 0);
423
424 performAnalysis();
425
426 APInt AOut = getDemandedBits(UserI);
Chris Lattner735f4672021-09-08 22:13:13 -0700427 APInt AB = APInt::getAllOnes(BitWidth);
Qunyan Manguscbde2482021-06-02 10:07:40 -0400428 KnownBits Known, Known2;
429 bool KnownBitsComputed = false;
430
431 determineLiveOperandBits(UserI, *U, U->getOperandNo(), AOut, AB, Known,
432 Known2, KnownBitsComputed);
433
434 return AB;
435}
436
James Molloy87405c72015-08-14 11:09:09 +0000437bool DemandedBits::isInstructionDead(Instruction *I) {
James Molloyab9fdb92015-10-08 12:39:50 +0000438 performAnalysis();
439
Kazu Hirata11efd1c2023-03-14 00:32:40 -0700440 return !Visited.count(I) && !AliveBits.contains(I) && !isAlwaysLive(I);
James Molloy87405c72015-08-14 11:09:09 +0000441}
442
Nikita Popovbc9986e2019-01-01 10:05:26 +0000443bool DemandedBits::isUseDead(Use *U) {
444 // We only track integer uses, everything else is assumed live.
445 if (!(*U)->getType()->isIntOrIntVectorTy())
446 return false;
447
448 // Uses by always-live instructions are never dead.
Simon Pilgrim738370a2023-02-12 14:57:11 +0000449 auto *UserI = cast<Instruction>(U->getUser());
Nikita Popovbc9986e2019-01-01 10:05:26 +0000450 if (isAlwaysLive(UserI))
451 return false;
452
453 performAnalysis();
454 if (DeadUses.count(U))
455 return true;
456
457 // If no output bits are demanded, no input bits are demanded and the use
458 // is dead. These uses might not be explicitly present in the DeadUses map.
459 if (UserI->getType()->isIntOrIntVectorTy()) {
460 auto Found = AliveBits.find(UserI);
Chris Lattner735f4672021-09-08 22:13:13 -0700461 if (Found != AliveBits.end() && Found->second.isZero())
Nikita Popovbc9986e2019-01-01 10:05:26 +0000462 return true;
463 }
464
465 return false;
466}
467
Michael Kupersteinde16b442016-04-18 23:55:01 +0000468void DemandedBits::print(raw_ostream &OS) {
Qunyan Manguscbde2482021-06-02 10:07:40 -0400469 auto PrintDB = [&](const Instruction *I, const APInt &A, Value *V = nullptr) {
470 OS << "DemandedBits: 0x" << Twine::utohexstr(A.getLimitedValue())
471 << " for ";
472 if (V) {
473 V->printAsOperand(OS, false);
474 OS << " in ";
475 }
476 OS << *I << '\n';
477 };
478
Florian Hahn99b3b8e2023-07-06 14:17:20 +0100479 OS << "Printing analysis 'Demanded Bits Analysis' for function '" << F.getName() << "':\n";
Michael Kupersteinde16b442016-04-18 23:55:01 +0000480 performAnalysis();
James Molloybcd7f0a2015-10-08 12:39:59 +0000481 for (auto &KV : AliveBits) {
Qunyan Manguscbde2482021-06-02 10:07:40 -0400482 Instruction *I = KV.first;
483 PrintDB(I, KV.second);
484
485 for (Use &OI : I->operands()) {
486 PrintDB(I, getDemandedBits(&OI), OI);
487 }
James Molloybcd7f0a2015-10-08 12:39:59 +0000488 }
489}
490
Simon Pilgrimc1f6ce02020-08-17 12:53:52 +0100491static APInt determineLiveOperandBitsAddCarry(unsigned OperandNo,
492 const APInt &AOut,
493 const KnownBits &LHS,
494 const KnownBits &RHS,
495 bool CarryZero, bool CarryOne) {
496 assert(!(CarryZero && CarryOne) &&
497 "Carry can't be zero and one at the same time");
498
499 // The following check should be done by the caller, as it also indicates
500 // that LHS and RHS don't need to be computed.
501 //
502 // if (AOut.isMask())
503 // return AOut;
504
505 // Boundary bits' carry out is unaffected by their carry in.
506 APInt Bound = (LHS.Zero & RHS.Zero) | (LHS.One & RHS.One);
507
508 // First, the alive carry bits are determined from the alive output bits:
509 // Let demand ripple to the right but only up to any set bit in Bound.
510 // AOut = -1----
511 // Bound = ----1-
512 // ACarry&~AOut = --111-
513 APInt RBound = Bound.reverseBits();
514 APInt RAOut = AOut.reverseBits();
515 APInt RProp = RAOut + (RAOut | ~RBound);
516 APInt RACarry = RProp ^ ~RBound;
517 APInt ACarry = RACarry.reverseBits();
518
519 // Then, the alive input bits are determined from the alive carry bits:
520 APInt NeededToMaintainCarryZero;
521 APInt NeededToMaintainCarryOne;
522 if (OperandNo == 0) {
523 NeededToMaintainCarryZero = LHS.Zero | ~RHS.Zero;
524 NeededToMaintainCarryOne = LHS.One | ~RHS.One;
525 } else {
526 NeededToMaintainCarryZero = RHS.Zero | ~LHS.Zero;
527 NeededToMaintainCarryOne = RHS.One | ~LHS.One;
528 }
529
530 // As in computeForAddCarry
531 APInt PossibleSumZero = ~LHS.Zero + ~RHS.Zero + !CarryZero;
532 APInt PossibleSumOne = LHS.One + RHS.One + CarryOne;
533
534 // The below is simplified from
535 //
536 // APInt CarryKnownZero = ~(PossibleSumZero ^ LHS.Zero ^ RHS.Zero);
537 // APInt CarryKnownOne = PossibleSumOne ^ LHS.One ^ RHS.One;
538 // APInt CarryUnknown = ~(CarryKnownZero | CarryKnownOne);
539 //
540 // APInt NeededToMaintainCarry =
541 // (CarryKnownZero & NeededToMaintainCarryZero) |
542 // (CarryKnownOne & NeededToMaintainCarryOne) |
543 // CarryUnknown;
544
545 APInt NeededToMaintainCarry = (~PossibleSumZero | NeededToMaintainCarryZero) &
546 (PossibleSumOne | NeededToMaintainCarryOne);
547
548 APInt AB = AOut | (ACarry & NeededToMaintainCarry);
549 return AB;
550}
551
552APInt DemandedBits::determineLiveOperandBitsAdd(unsigned OperandNo,
553 const APInt &AOut,
554 const KnownBits &LHS,
555 const KnownBits &RHS) {
556 return determineLiveOperandBitsAddCarry(OperandNo, AOut, LHS, RHS, true,
557 false);
558}
559
560APInt DemandedBits::determineLiveOperandBitsSub(unsigned OperandNo,
561 const APInt &AOut,
562 const KnownBits &LHS,
563 const KnownBits &RHS) {
564 KnownBits NRHS;
565 NRHS.Zero = RHS.One;
566 NRHS.One = RHS.Zero;
567 return determineLiveOperandBitsAddCarry(OperandNo, AOut, LHS, NRHS, false,
568 true);
569}
570
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000571AnalysisKey DemandedBitsAnalysis::Key;
Michael Kupersteinde16b442016-04-18 23:55:01 +0000572
573DemandedBits DemandedBitsAnalysis::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000574 FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000575 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000576 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000577 return DemandedBits(F, AC, DT);
Michael Kupersteinde16b442016-04-18 23:55:01 +0000578}
579
580PreservedAnalyses DemandedBitsPrinterPass::run(Function &F,
581 FunctionAnalysisManager &AM) {
582 AM.getResult<DemandedBitsAnalysis>(F).print(OS);
583 return PreservedAnalyses::all();
James Molloy87405c72015-08-14 11:09:09 +0000584}