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 22 #include "llvm/Analysis/DemandedBits.h" 23 #include "llvm/ADT/DepthFirstIterator.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/Analysis/AssumptionCache.h" 28 #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/KnownBits.h" 41 #include "llvm/Support/raw_ostream.h" 42 using namespace llvm; 43 44 #define DEBUG_TYPE "demanded-bits" 45 46 char DemandedBitsWrapperPass::ID = 0; 47 INITIALIZE_PASS_BEGIN(DemandedBitsWrapperPass, "demanded-bits", 48 "Demanded bits analysis", false, false) 49 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 50 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 51 INITIALIZE_PASS_END(DemandedBitsWrapperPass, "demanded-bits", 52 "Demanded bits analysis", false, false) 53 54 DemandedBitsWrapperPass::DemandedBitsWrapperPass() : FunctionPass(ID) { 55 initializeDemandedBitsWrapperPassPass(*PassRegistry::getPassRegistry()); 56 } 57 58 void DemandedBitsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 59 AU.setPreservesCFG(); 60 AU.addRequired<AssumptionCacheTracker>(); 61 AU.addRequired<DominatorTreeWrapperPass>(); 62 AU.setPreservesAll(); 63 } 64 65 void DemandedBitsWrapperPass::print(raw_ostream &OS, const Module *M) const { 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 (ConstantInt *CI = 147 dyn_cast<ConstantInt>(UserI->getOperand(1))) { 148 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1); 149 AB = AOut.lshr(ShiftAmt); 150 151 // If the shift is nuw/nsw, then the high bits are not dead 152 // (because we've promised that they *must* be zero). 153 const ShlOperator *S = cast<ShlOperator>(UserI); 154 if (S->hasNoSignedWrap()) 155 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1); 156 else if (S->hasNoUnsignedWrap()) 157 AB |= APInt::getHighBitsSet(BitWidth, ShiftAmt); 158 } 159 break; 160 case Instruction::LShr: 161 if (OperandNo == 0) 162 if (ConstantInt *CI = 163 dyn_cast<ConstantInt>(UserI->getOperand(1))) { 164 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1); 165 AB = AOut.shl(ShiftAmt); 166 167 // If the shift is exact, then the low bits are not dead 168 // (they must be zero). 169 if (cast<LShrOperator>(UserI)->isExact()) 170 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt); 171 } 172 break; 173 case Instruction::AShr: 174 if (OperandNo == 0) 175 if (ConstantInt *CI = 176 dyn_cast<ConstantInt>(UserI->getOperand(1))) { 177 uint64_t ShiftAmt = CI->getLimitedValue(BitWidth-1); 178 AB = AOut.shl(ShiftAmt); 179 // Because the high input bit is replicated into the 180 // high-order bits of the result, if we need any of those 181 // bits, then we must keep the highest input bit. 182 if ((AOut & APInt::getHighBitsSet(BitWidth, ShiftAmt)) 183 .getBoolValue()) 184 AB.setSignBit(); 185 186 // If the shift is exact, then the low bits are not dead 187 // (they must be zero). 188 if (cast<AShrOperator>(UserI)->isExact()) 189 AB |= APInt::getLowBitsSet(BitWidth, ShiftAmt); 190 } 191 break; 192 case Instruction::And: 193 AB = AOut; 194 195 // For bits that are known zero, the corresponding bits in the 196 // other operand are dead (unless they're both zero, in which 197 // case they can't both be dead, so just mark the LHS bits as 198 // dead). 199 if (OperandNo == 0) { 200 ComputeKnownBits(BitWidth, I, UserI->getOperand(1)); 201 AB &= ~Known2.Zero; 202 } else { 203 if (!isa<Instruction>(UserI->getOperand(0))) 204 ComputeKnownBits(BitWidth, UserI->getOperand(0), I); 205 AB &= ~(Known.Zero & ~Known2.Zero); 206 } 207 break; 208 case Instruction::Or: 209 AB = AOut; 210 211 // For bits that are known one, the corresponding bits in the 212 // other operand are dead (unless they're both one, in which 213 // case they can't both be dead, so just mark the LHS bits as 214 // dead). 215 if (OperandNo == 0) { 216 ComputeKnownBits(BitWidth, I, UserI->getOperand(1)); 217 AB &= ~Known2.One; 218 } else { 219 if (!isa<Instruction>(UserI->getOperand(0))) 220 ComputeKnownBits(BitWidth, UserI->getOperand(0), I); 221 AB &= ~(Known.One & ~Known2.One); 222 } 223 break; 224 case Instruction::Xor: 225 case Instruction::PHI: 226 AB = AOut; 227 break; 228 case Instruction::Trunc: 229 AB = AOut.zext(BitWidth); 230 break; 231 case Instruction::ZExt: 232 AB = AOut.trunc(BitWidth); 233 break; 234 case Instruction::SExt: 235 AB = AOut.trunc(BitWidth); 236 // Because the high input bit is replicated into the 237 // high-order bits of the result, if we need any of those 238 // bits, then we must keep the highest input bit. 239 if ((AOut & APInt::getHighBitsSet(AOut.getBitWidth(), 240 AOut.getBitWidth() - BitWidth)) 241 .getBoolValue()) 242 AB.setSignBit(); 243 break; 244 case Instruction::Select: 245 if (OperandNo != 0) 246 AB = AOut; 247 break; 248 } 249 } 250 251 bool DemandedBitsWrapperPass::runOnFunction(Function &F) { 252 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 253 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 254 DB.emplace(F, AC, DT); 255 return false; 256 } 257 258 void DemandedBitsWrapperPass::releaseMemory() { 259 DB.reset(); 260 } 261 262 void DemandedBits::performAnalysis() { 263 if (Analyzed) 264 // Analysis already completed for this function. 265 return; 266 Analyzed = true; 267 268 Visited.clear(); 269 AliveBits.clear(); 270 271 SmallVector<Instruction*, 128> Worklist; 272 273 // Collect the set of "root" instructions that are known live. 274 for (Instruction &I : instructions(F)) { 275 if (!isAlwaysLive(&I)) 276 continue; 277 278 DEBUG(dbgs() << "DemandedBits: Root: " << I << "\n"); 279 // For integer-valued instructions, set up an initial empty set of alive 280 // bits and add the instruction to the work list. For other instructions 281 // add their operands to the work list (for integer values operands, mark 282 // all bits as live). 283 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) { 284 if (AliveBits.try_emplace(&I, IT->getBitWidth(), 0).second) 285 Worklist.push_back(&I); 286 287 continue; 288 } 289 290 // Non-integer-typed instructions... 291 for (Use &OI : I.operands()) { 292 if (Instruction *J = dyn_cast<Instruction>(OI)) { 293 if (IntegerType *IT = dyn_cast<IntegerType>(J->getType())) 294 AliveBits[J] = APInt::getAllOnesValue(IT->getBitWidth()); 295 Worklist.push_back(J); 296 } 297 } 298 // To save memory, we don't add I to the Visited set here. Instead, we 299 // check isAlwaysLive on every instruction when searching for dead 300 // instructions later (we need to check isAlwaysLive for the 301 // integer-typed instructions anyway). 302 } 303 304 // Propagate liveness backwards to operands. 305 while (!Worklist.empty()) { 306 Instruction *UserI = Worklist.pop_back_val(); 307 308 DEBUG(dbgs() << "DemandedBits: Visiting: " << *UserI); 309 APInt AOut; 310 if (UserI->getType()->isIntegerTy()) { 311 AOut = AliveBits[UserI]; 312 DEBUG(dbgs() << " Alive Out: " << AOut); 313 } 314 DEBUG(dbgs() << "\n"); 315 316 if (!UserI->getType()->isIntegerTy()) 317 Visited.insert(UserI); 318 319 KnownBits Known, Known2; 320 // Compute the set of alive bits for each operand. These are anded into the 321 // existing set, if any, and if that changes the set of alive bits, the 322 // operand is added to the work-list. 323 for (Use &OI : UserI->operands()) { 324 if (Instruction *I = dyn_cast<Instruction>(OI)) { 325 if (IntegerType *IT = dyn_cast<IntegerType>(I->getType())) { 326 unsigned BitWidth = IT->getBitWidth(); 327 APInt AB = APInt::getAllOnesValue(BitWidth); 328 if (UserI->getType()->isIntegerTy() && !AOut && 329 !isAlwaysLive(UserI)) { 330 AB = APInt(BitWidth, 0); 331 } else { 332 // If all bits of the output are dead, then all bits of the input 333 // Bits of each operand that are used to compute alive bits of the 334 // output are alive, all others are dead. 335 determineLiveOperandBits(UserI, I, OI.getOperandNo(), AOut, AB, 336 Known, Known2); 337 } 338 339 // If we've added to the set of alive bits (or the operand has not 340 // been previously visited), then re-queue the operand to be visited 341 // again. 342 APInt ABPrev(BitWidth, 0); 343 auto ABI = AliveBits.find(I); 344 if (ABI != AliveBits.end()) 345 ABPrev = ABI->second; 346 347 APInt ABNew = AB | ABPrev; 348 if (ABNew != ABPrev || ABI == AliveBits.end()) { 349 AliveBits[I] = std::move(ABNew); 350 Worklist.push_back(I); 351 } 352 } else if (!Visited.count(I)) { 353 Worklist.push_back(I); 354 } 355 } 356 } 357 } 358 } 359 360 APInt DemandedBits::getDemandedBits(Instruction *I) { 361 performAnalysis(); 362 363 const DataLayout &DL = I->getParent()->getModule()->getDataLayout(); 364 auto Found = AliveBits.find(I); 365 if (Found != AliveBits.end()) 366 return Found->second; 367 return APInt::getAllOnesValue(DL.getTypeSizeInBits(I->getType())); 368 } 369 370 bool DemandedBits::isInstructionDead(Instruction *I) { 371 performAnalysis(); 372 373 return !Visited.count(I) && AliveBits.find(I) == AliveBits.end() && 374 !isAlwaysLive(I); 375 } 376 377 void DemandedBits::print(raw_ostream &OS) { 378 performAnalysis(); 379 for (auto &KV : AliveBits) { 380 OS << "DemandedBits: 0x" << utohexstr(KV.second.getLimitedValue()) << " for " 381 << *KV.first << "\n"; 382 } 383 } 384 385 FunctionPass *llvm::createDemandedBitsWrapperPass() { 386 return new DemandedBitsWrapperPass(); 387 } 388 389 AnalysisKey DemandedBitsAnalysis::Key; 390 391 DemandedBits DemandedBitsAnalysis::run(Function &F, 392 FunctionAnalysisManager &AM) { 393 auto &AC = AM.getResult<AssumptionAnalysis>(F); 394 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 395 return DemandedBits(F, AC, DT); 396 } 397 398 PreservedAnalyses DemandedBitsPrinterPass::run(Function &F, 399 FunctionAnalysisManager &AM) { 400 AM.getResult<DemandedBitsAnalysis>(F).print(OS); 401 return PreservedAnalyses::all(); 402 } 403