1 //===- AggressiveInstCombine.cpp ------------------------------------------===// 2 // 3 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the aggressive expression pattern combiner classes. 10 // Currently, it handles expression patterns for: 11 // * Truncate instruction 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 16 #include "AggressiveInstCombineInternal.h" 17 #include "llvm-c/Initialization.h" 18 #include "llvm-c/Transforms/AggressiveInstCombine.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BasicAliasAnalysis.h" 22 #include "llvm/Analysis/GlobalsModRef.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/LegacyPassManager.h" 29 #include "llvm/IR/PatternMatch.h" 30 #include "llvm/InitializePasses.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Transforms/Utils/Local.h" 33 34 using namespace llvm; 35 using namespace PatternMatch; 36 37 #define DEBUG_TYPE "aggressive-instcombine" 38 39 STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded"); 40 STATISTIC(NumGuardedRotates, 41 "Number of guarded rotates transformed into funnel shifts"); 42 STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized"); 43 44 namespace { 45 /// Contains expression pattern combiner logic. 46 /// This class provides both the logic to combine expression patterns and 47 /// combine them. It differs from InstCombiner class in that each pattern 48 /// combiner runs only once as opposed to InstCombine's multi-iteration, 49 /// which allows pattern combiner to have higher complexity than the O(1) 50 /// required by the instruction combiner. 51 class AggressiveInstCombinerLegacyPass : public FunctionPass { 52 public: 53 static char ID; // Pass identification, replacement for typeid 54 55 AggressiveInstCombinerLegacyPass() : FunctionPass(ID) { 56 initializeAggressiveInstCombinerLegacyPassPass( 57 *PassRegistry::getPassRegistry()); 58 } 59 60 void getAnalysisUsage(AnalysisUsage &AU) const override; 61 62 /// Run all expression pattern optimizations on the given /p F function. 63 /// 64 /// \param F function to optimize. 65 /// \returns true if the IR is changed. 66 bool runOnFunction(Function &F) override; 67 }; 68 } // namespace 69 70 /// Match a pattern for a bitwise rotate operation that partially guards 71 /// against undefined behavior by branching around the rotation when the shift 72 /// amount is 0. 73 static bool foldGuardedRotateToFunnelShift(Instruction &I) { 74 if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2) 75 return false; 76 77 // As with the one-use checks below, this is not strictly necessary, but we 78 // are being cautious to avoid potential perf regressions on targets that 79 // do not actually have a rotate instruction (where the funnel shift would be 80 // expanded back into math/shift/logic ops). 81 if (!isPowerOf2_32(I.getType()->getScalarSizeInBits())) 82 return false; 83 84 // Match V to funnel shift left/right and capture the source operands and 85 // shift amount. 86 auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1, 87 Value *&ShAmt) { 88 Value *SubAmt; 89 unsigned Width = V->getType()->getScalarSizeInBits(); 90 91 // fshl(ShVal0, ShVal1, ShAmt) 92 // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt)) 93 if (match(V, m_OneUse(m_c_Or( 94 m_Shl(m_Value(ShVal0), m_Value(ShAmt)), 95 m_LShr(m_Value(ShVal1), 96 m_Sub(m_SpecificInt(Width), m_Value(SubAmt))))))) { 97 if (ShAmt == SubAmt) // TODO: Use m_Specific 98 return Intrinsic::fshl; 99 } 100 101 // fshr(ShVal0, ShVal1, ShAmt) 102 // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt)) 103 if (match(V, 104 m_OneUse(m_c_Or(m_Shl(m_Value(ShVal0), m_Sub(m_SpecificInt(Width), 105 m_Value(SubAmt))), 106 m_LShr(m_Value(ShVal1), m_Value(ShAmt)))))) { 107 if (ShAmt == SubAmt) // TODO: Use m_Specific 108 return Intrinsic::fshr; 109 } 110 111 return Intrinsic::not_intrinsic; 112 }; 113 114 // One phi operand must be a rotate operation, and the other phi operand must 115 // be the source value of that rotate operation: 116 // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ] 117 PHINode &Phi = cast<PHINode>(I); 118 unsigned FunnelOp = 0, GuardOp = 1; 119 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1); 120 Value *ShVal0, *ShVal1, *ShAmt; 121 Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt); 122 if (IID == Intrinsic::not_intrinsic || ShVal0 != ShVal1 || ShVal0 != P1) { 123 IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt); 124 if (IID == Intrinsic::not_intrinsic || ShVal0 != ShVal1 || ShVal0 != P0) 125 return false; 126 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) && 127 "Pattern must match funnel shift left or right"); 128 std::swap(FunnelOp, GuardOp); 129 } 130 assert(ShVal0 == ShVal1 && "Rotation funnel shift pattern expected"); 131 132 // The incoming block with our source operand must be the "guard" block. 133 // That must contain a cmp+branch to avoid the rotate when the shift amount 134 // is equal to 0. The other incoming block is the block with the rotate. 135 BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp); 136 BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp); 137 Instruction *TermI = GuardBB->getTerminator(); 138 ICmpInst::Predicate Pred; 139 BasicBlock *PhiBB = Phi.getParent(); 140 if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()), 141 m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB)))) 142 return false; 143 144 if (Pred != CmpInst::ICMP_EQ) 145 return false; 146 147 // We matched a variation of this IR pattern: 148 // GuardBB: 149 // %cmp = icmp eq i32 %ShAmt, 0 150 // br i1 %cmp, label %PhiBB, label %FunnelBB 151 // FunnelBB: 152 // %sub = sub i32 32, %ShAmt 153 // %shr = lshr i32 %RotSrc, %sub 154 // %shl = shl i32 %RotSrc, %ShAmt 155 // %rot = or i32 %shr, %shl 156 // br label %PhiBB 157 // PhiBB: 158 // %cond = phi i32 [ %RotSrc, %FunnelBB ], [ %RotSrc, %GuardBB ] 159 // --> 160 // llvm.fshl.i32(i32 %RotSrc, i32 %RotSrc, i32 %ShAmt) 161 IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt()); 162 Function *F = Intrinsic::getDeclaration(Phi.getModule(), IID, Phi.getType()); 163 Phi.replaceAllUsesWith(Builder.CreateCall(F, {ShVal0, ShVal1, ShAmt})); 164 ++NumGuardedRotates; 165 return true; 166 } 167 168 /// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and 169 /// the bit indexes (Mask) needed by a masked compare. If we're matching a chain 170 /// of 'and' ops, then we also need to capture the fact that we saw an 171 /// "and X, 1", so that's an extra return value for that case. 172 struct MaskOps { 173 Value *Root; 174 APInt Mask; 175 bool MatchAndChain; 176 bool FoundAnd1; 177 178 MaskOps(unsigned BitWidth, bool MatchAnds) 179 : Root(nullptr), Mask(APInt::getNullValue(BitWidth)), 180 MatchAndChain(MatchAnds), FoundAnd1(false) {} 181 }; 182 183 /// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a 184 /// chain of 'and' or 'or' instructions looking for shift ops of a common source 185 /// value. Examples: 186 /// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8) 187 /// returns { X, 0x129 } 188 /// and (and (X >> 1), 1), (X >> 4) 189 /// returns { X, 0x12 } 190 static bool matchAndOrChain(Value *V, MaskOps &MOps) { 191 Value *Op0, *Op1; 192 if (MOps.MatchAndChain) { 193 // Recurse through a chain of 'and' operands. This requires an extra check 194 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere 195 // in the chain to know that all of the high bits are cleared. 196 if (match(V, m_And(m_Value(Op0), m_One()))) { 197 MOps.FoundAnd1 = true; 198 return matchAndOrChain(Op0, MOps); 199 } 200 if (match(V, m_And(m_Value(Op0), m_Value(Op1)))) 201 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps); 202 } else { 203 // Recurse through a chain of 'or' operands. 204 if (match(V, m_Or(m_Value(Op0), m_Value(Op1)))) 205 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps); 206 } 207 208 // We need a shift-right or a bare value representing a compare of bit 0 of 209 // the original source operand. 210 Value *Candidate; 211 const APInt *BitIndex = nullptr; 212 if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex)))) 213 Candidate = V; 214 215 // Initialize result source operand. 216 if (!MOps.Root) 217 MOps.Root = Candidate; 218 219 // The shift constant is out-of-range? This code hasn't been simplified. 220 if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth())) 221 return false; 222 223 // Fill in the mask bit derived from the shift constant. 224 MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0); 225 return MOps.Root == Candidate; 226 } 227 228 /// Match patterns that correspond to "any-bits-set" and "all-bits-set". 229 /// These will include a chain of 'or' or 'and'-shifted bits from a 230 /// common source value: 231 /// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0 232 /// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask 233 /// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns 234 /// that differ only with a final 'not' of the result. We expect that final 235 /// 'not' to be folded with the compare that we create here (invert predicate). 236 static bool foldAnyOrAllBitsSet(Instruction &I) { 237 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the 238 // final "and X, 1" instruction must be the final op in the sequence. 239 bool MatchAllBitsSet; 240 if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value()))) 241 MatchAllBitsSet = true; 242 else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One()))) 243 MatchAllBitsSet = false; 244 else 245 return false; 246 247 MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet); 248 if (MatchAllBitsSet) { 249 if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1) 250 return false; 251 } else { 252 if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps)) 253 return false; 254 } 255 256 // The pattern was found. Create a masked compare that replaces all of the 257 // shift and logic ops. 258 IRBuilder<> Builder(&I); 259 Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask); 260 Value *And = Builder.CreateAnd(MOps.Root, Mask); 261 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask) 262 : Builder.CreateIsNotNull(And); 263 Value *Zext = Builder.CreateZExt(Cmp, I.getType()); 264 I.replaceAllUsesWith(Zext); 265 ++NumAnyOrAllBitsSet; 266 return true; 267 } 268 269 // Try to recognize below function as popcount intrinsic. 270 // This is the "best" algorithm from 271 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 272 // Also used in TargetLowering::expandCTPOP(). 273 // 274 // int popcount(unsigned int i) { 275 // i = i - ((i >> 1) & 0x55555555); 276 // i = (i & 0x33333333) + ((i >> 2) & 0x33333333); 277 // i = ((i + (i >> 4)) & 0x0F0F0F0F); 278 // return (i * 0x01010101) >> 24; 279 // } 280 static bool tryToRecognizePopCount(Instruction &I) { 281 if (I.getOpcode() != Instruction::LShr) 282 return false; 283 284 Type *Ty = I.getType(); 285 if (!Ty->isIntOrIntVectorTy()) 286 return false; 287 288 unsigned Len = Ty->getScalarSizeInBits(); 289 // FIXME: fix Len == 8 and other irregular type lengths. 290 if (!(Len <= 128 && Len > 8 && Len % 8 == 0)) 291 return false; 292 293 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55)); 294 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33)); 295 APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F)); 296 APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01)); 297 APInt MaskShift = APInt(Len, Len - 8); 298 299 Value *Op0 = I.getOperand(0); 300 Value *Op1 = I.getOperand(1); 301 Value *MulOp0; 302 // Matching "(i * 0x01010101...) >> 24". 303 if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) && 304 match(Op1, m_SpecificInt(MaskShift))) { 305 Value *ShiftOp0; 306 // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)". 307 if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)), 308 m_Deferred(ShiftOp0)), 309 m_SpecificInt(Mask0F)))) { 310 Value *AndOp0; 311 // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)". 312 if (match(ShiftOp0, 313 m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)), 314 m_And(m_LShr(m_Deferred(AndOp0), m_SpecificInt(2)), 315 m_SpecificInt(Mask33))))) { 316 Value *Root, *SubOp1; 317 // Matching "i - ((i >> 1) & 0x55555555...)". 318 if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) && 319 match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)), 320 m_SpecificInt(Mask55)))) { 321 LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n"); 322 IRBuilder<> Builder(&I); 323 Function *Func = Intrinsic::getDeclaration( 324 I.getModule(), Intrinsic::ctpop, I.getType()); 325 I.replaceAllUsesWith(Builder.CreateCall(Func, {Root})); 326 ++NumPopCountRecognized; 327 return true; 328 } 329 } 330 } 331 } 332 333 return false; 334 } 335 336 /// This is the entry point for folds that could be implemented in regular 337 /// InstCombine, but they are separated because they are not expected to 338 /// occur frequently and/or have more than a constant-length pattern match. 339 static bool foldUnusualPatterns(Function &F, DominatorTree &DT) { 340 bool MadeChange = false; 341 for (BasicBlock &BB : F) { 342 // Ignore unreachable basic blocks. 343 if (!DT.isReachableFromEntry(&BB)) 344 continue; 345 // Do not delete instructions under here and invalidate the iterator. 346 // Walk the block backwards for efficiency. We're matching a chain of 347 // use->defs, so we're more likely to succeed by starting from the bottom. 348 // Also, we want to avoid matching partial patterns. 349 // TODO: It would be more efficient if we removed dead instructions 350 // iteratively in this loop rather than waiting until the end. 351 for (Instruction &I : make_range(BB.rbegin(), BB.rend())) { 352 MadeChange |= foldAnyOrAllBitsSet(I); 353 MadeChange |= foldGuardedRotateToFunnelShift(I); 354 MadeChange |= tryToRecognizePopCount(I); 355 } 356 } 357 358 // We're done with transforms, so remove dead instructions. 359 if (MadeChange) 360 for (BasicBlock &BB : F) 361 SimplifyInstructionsInBlock(&BB); 362 363 return MadeChange; 364 } 365 366 /// This is the entry point for all transforms. Pass manager differences are 367 /// handled in the callers of this function. 368 static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT) { 369 bool MadeChange = false; 370 const DataLayout &DL = F.getParent()->getDataLayout(); 371 TruncInstCombine TIC(TLI, DL, DT); 372 MadeChange |= TIC.run(F); 373 MadeChange |= foldUnusualPatterns(F, DT); 374 return MadeChange; 375 } 376 377 void AggressiveInstCombinerLegacyPass::getAnalysisUsage( 378 AnalysisUsage &AU) const { 379 AU.setPreservesCFG(); 380 AU.addRequired<DominatorTreeWrapperPass>(); 381 AU.addRequired<TargetLibraryInfoWrapperPass>(); 382 AU.addPreserved<AAResultsWrapperPass>(); 383 AU.addPreserved<BasicAAWrapperPass>(); 384 AU.addPreserved<DominatorTreeWrapperPass>(); 385 AU.addPreserved<GlobalsAAWrapperPass>(); 386 } 387 388 bool AggressiveInstCombinerLegacyPass::runOnFunction(Function &F) { 389 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 390 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 391 return runImpl(F, TLI, DT); 392 } 393 394 PreservedAnalyses AggressiveInstCombinePass::run(Function &F, 395 FunctionAnalysisManager &AM) { 396 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 397 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 398 if (!runImpl(F, TLI, DT)) { 399 // No changes, all analyses are preserved. 400 return PreservedAnalyses::all(); 401 } 402 // Mark all the analyses that instcombine updates as preserved. 403 PreservedAnalyses PA; 404 PA.preserveSet<CFGAnalyses>(); 405 PA.preserve<AAManager>(); 406 PA.preserve<GlobalsAA>(); 407 return PA; 408 } 409 410 char AggressiveInstCombinerLegacyPass::ID = 0; 411 INITIALIZE_PASS_BEGIN(AggressiveInstCombinerLegacyPass, 412 "aggressive-instcombine", 413 "Combine pattern based expressions", false, false) 414 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 415 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 416 INITIALIZE_PASS_END(AggressiveInstCombinerLegacyPass, "aggressive-instcombine", 417 "Combine pattern based expressions", false, false) 418 419 // Initialization Routines 420 void llvm::initializeAggressiveInstCombine(PassRegistry &Registry) { 421 initializeAggressiveInstCombinerLegacyPassPass(Registry); 422 } 423 424 void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R) { 425 initializeAggressiveInstCombinerLegacyPassPass(*unwrap(R)); 426 } 427 428 FunctionPass *llvm::createAggressiveInstCombinerPass() { 429 return new AggressiveInstCombinerLegacyPass(); 430 } 431 432 void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM) { 433 unwrap(PM)->add(createAggressiveInstCombinerPass()); 434 } 435