| 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/ADT/Statistic.h" |
| 18 | #include "llvm/Analysis/AliasAnalysis.h" |
| 19 | #include "llvm/Analysis/AssumptionCache.h" |
| 20 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
| 21 | #include "llvm/Analysis/ConstantFolding.h" |
| 22 | #include "llvm/Analysis/DomTreeUpdater.h" |
| 23 | #include "llvm/Analysis/GlobalsModRef.h" |
| 24 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 25 | #include "llvm/Analysis/TargetTransformInfo.h" |
| 26 | #include "llvm/Analysis/ValueTracking.h" |
| 27 | #include "llvm/IR/DataLayout.h" |
| 28 | #include "llvm/IR/Dominators.h" |
| 29 | #include "llvm/IR/Function.h" |
| 30 | #include "llvm/IR/IRBuilder.h" |
| 31 | #include "llvm/IR/Instruction.h" |
| 32 | #include "llvm/IR/IntrinsicInst.h" |
| 33 | #include "llvm/IR/MDBuilder.h" |
| 34 | #include "llvm/IR/PatternMatch.h" |
| 35 | #include "llvm/IR/ProfDataUtils.h" |
| 36 | #include "llvm/ProfileData/InstrProf.h" |
| 37 | #include "llvm/Support/Casting.h" |
| 38 | #include "llvm/Support/CommandLine.h" |
| 39 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 40 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
| 41 | #include "llvm/Transforms/Utils/Local.h" |
| 42 | |
| 43 | using namespace llvm; |
| 44 | using namespace PatternMatch; |
| 45 | |
| 46 | #define DEBUG_TYPE "aggressive-instcombine" |
| 47 | |
| 48 | STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded" ); |
| 49 | STATISTIC(NumGuardedRotates, |
| 50 | "Number of guarded rotates transformed into funnel shifts" ); |
| 51 | STATISTIC(NumGuardedFunnelShifts, |
| 52 | "Number of guarded funnel shifts transformed into funnel shifts" ); |
| 53 | STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized" ); |
| 54 | STATISTIC(NumSelectCTTZFolded, |
| 55 | "Number of select-based split cttz patterns folded" ); |
| 56 | STATISTIC(NumSelectCTLZFolded, |
| 57 | "Number of select-based split ctlz patterns folded" ); |
| 58 | STATISTIC(NumMemSetsGuarded, "Number of memsets guarded for a zero length" ); |
| 59 | STATISTIC(NumTableBasedLowBitsMask, |
| 60 | "Number of low-bits mask table loads folded to (1 << i) - 1" ); |
| 61 | |
| 62 | static cl::opt<unsigned> MaxInstrsToScan( |
| 63 | "aggressive-instcombine-max-scan-instrs" , cl::init(Val: 64), cl::Hidden, |
| 64 | cl::desc("Max number of instructions to scan for aggressive instcombine." )); |
| 65 | |
| 66 | static cl::opt<unsigned> StrNCmpInlineThreshold( |
| 67 | "strncmp-inline-threshold" , cl::init(Val: 3), cl::Hidden, |
| 68 | cl::desc("The maximum length of a constant string for a builtin string cmp " |
| 69 | "call eligible for inlining. The default value is 3." )); |
| 70 | |
| 71 | static cl::opt<unsigned> |
| 72 | MemChrInlineThreshold("memchr-inline-threshold" , cl::init(Val: 3), cl::Hidden, |
| 73 | cl::desc("The maximum length of a constant string to " |
| 74 | "inline a memchr call." )); |
| 75 | |
| 76 | namespace llvm { |
| 77 | extern cl::opt<bool> ProfcheckDisableMetadataFixes; |
| 78 | } // namespace llvm |
| 79 | |
| 80 | /// Try to fold a select-based split cttz pattern into a single full-width cttz. |
| 81 | /// |
| 82 | /// %lo = trunc iN %val to i(N/2) |
| 83 | /// %cmp = icmp eq i(N/2) %lo, 0 |
| 84 | /// %shr = lshr iN %val, N/2 |
| 85 | /// %hi = trunc iN %shr to i(N/2) |
| 86 | /// %cttz_hi = call i(N/2) @llvm.cttz.i(N/2)(i(N/2) %hi, ...) |
| 87 | /// %hi_plus = add/or_disjoint i(N/2) %cttz_hi, N/2 |
| 88 | /// %cttz_lo = call i(N/2) @llvm.cttz.i(N/2)(i(N/2) %lo, ...) |
| 89 | /// %result = select i1 %cmp, i(N/2) %hi_plus, i(N/2) %cttz_lo |
| 90 | /// --> |
| 91 | /// %cttz_wide = call iN @llvm.cttz.iN(iN %val, i1 false) |
| 92 | /// %result = trunc iN %cttz_wide to i(N/2) |
| 93 | /// Alive proof (for i64/i32): https://alive2.llvm.org/ce/z/-s14-s |
| 94 | // TrueVal/FalseVal are pre-normalized by the caller to the EQ/NE cases. |
| 95 | static bool foldSelectSplitCTTZ(Instruction &I, Value *LoTrunc, Value *HiResult, |
| 96 | Value *LoResult, Type *HalfTy) { |
| 97 | unsigned HalfWidth = HalfTy->getIntegerBitWidth(); |
| 98 | unsigned FullWidth = HalfWidth * 2; |
| 99 | |
| 100 | // LoTrunc: trunc iN SrcVal to i(N/2) |
| 101 | Value *SrcVal; |
| 102 | if (!match(V: LoTrunc, P: m_Trunc(Op: m_Value(V&: SrcVal)))) |
| 103 | return false; |
| 104 | if (!SrcVal->getType()->isIntegerTy(BitWidth: FullWidth)) |
| 105 | return false; |
| 106 | |
| 107 | // LoResult: cttz(trunc(SrcVal), _), must use same truncated value |
| 108 | if (!match(V: LoResult, P: m_OneUse(SubPattern: m_Cttz(Op0: m_Specific(V: LoTrunc), Op1: m_Value())))) |
| 109 | return false; |
| 110 | |
| 111 | // HiResult: add/or_disjoint(cttz(trunc(lshr(SrcVal, N/2)), _), N/2) |
| 112 | Value *CttzHiCall; |
| 113 | if (!match(V: HiResult, P: m_OneUse(SubPattern: m_AddLike(L: m_Value(V&: CttzHiCall), |
| 114 | R: m_SpecificInt(V: HalfWidth))))) |
| 115 | return false; |
| 116 | |
| 117 | Value *HiCttzArg; |
| 118 | if (!match(V: CttzHiCall, P: m_OneUse(SubPattern: m_Cttz(Op0: m_Value(V&: HiCttzArg), Op1: m_Value())))) |
| 119 | return false; |
| 120 | |
| 121 | if (!match(V: HiCttzArg, |
| 122 | P: m_Trunc(Op: m_LShr(L: m_Specific(V: SrcVal), R: m_SpecificInt(V: HalfWidth))))) |
| 123 | return false; |
| 124 | |
| 125 | // Match successful. |
| 126 | IRBuilder<> Builder(&I); |
| 127 | Value *CttzWide = Builder.CreateIntrinsic( |
| 128 | ID: Intrinsic::cttz, OverloadTypes: {SrcVal->getType()}, Args: {SrcVal, Builder.getFalse()}); |
| 129 | Value *Trunc = Builder.CreateTrunc(V: CttzWide, DestTy: HalfTy); |
| 130 | |
| 131 | I.replaceAllUsesWith(V: Trunc); |
| 132 | ++NumSelectCTTZFolded; |
| 133 | return true; |
| 134 | } |
| 135 | |
| 136 | /// Same as foldSelectSplitCTTZ but for leading zeros (ctlz). |
| 137 | /// |
| 138 | /// %shr = lshr iN %val, N/2 |
| 139 | /// %hi = trunc iN %shr to i(N/2) |
| 140 | /// %cmp = icmp eq i(N/2) %hi, 0 (or icmp eq iN %shr, 0) |
| 141 | /// %lo = trunc iN %val to i(N/2) |
| 142 | /// %ctlz_lo = call i(N/2) @llvm.ctlz.i(N/2)(i(N/2) %lo, ...) |
| 143 | /// %lo_plus = add/or_disjoint i(N/2) %ctlz_lo, N/2 |
| 144 | /// %ctlz_hi = call i(N/2) @llvm.ctlz.i(N/2)(i(N/2) %hi, ...) |
| 145 | /// %result = select i1 %cmp, i(N/2) %lo_plus, i(N/2) %ctlz_hi |
| 146 | /// --> |
| 147 | /// %ctlz_wide = call iN @llvm.ctlz.iN(iN %val, i1 false) |
| 148 | /// %result = trunc iN %ctlz_wide to i(N/2) |
| 149 | /// |
| 150 | /// Alive proof (for i64/i32): https://alive2.llvm.org/ce/z/WfQepH |
| 151 | // TrueVal/FalseVal are pre-normalized by the caller to the EQ/NE cases. |
| 152 | static bool foldSelectSplitCTLZ(Instruction &I, Value *HiPart, Value *LoResult, |
| 153 | Value *HiResult, Type *HalfTy) { |
| 154 | unsigned HalfWidth = HalfTy->getIntegerBitWidth(); |
| 155 | unsigned FullWidth = HalfWidth * 2; |
| 156 | |
| 157 | // Extract SrcVal from HiPart: either trunc(lshr(SrcVal, N/2)) or |
| 158 | // lshr(SrcVal, N/2) |
| 159 | Value *SrcVal; |
| 160 | if (match(V: HiPart, P: m_Trunc(Op: m_Value(V&: SrcVal)))) |
| 161 | HiPart = SrcVal; |
| 162 | |
| 163 | if (!match(V: HiPart, P: m_LShr(L: m_Value(V&: SrcVal), R: m_SpecificInt(V: HalfWidth)))) |
| 164 | return false; |
| 165 | if (!SrcVal->getType()->isIntegerTy(BitWidth: FullWidth)) |
| 166 | return false; |
| 167 | |
| 168 | // HiResult: ctlz(trunc(lshr(SrcVal, N/2)), _) |
| 169 | Value *HiCtlzArg; |
| 170 | if (!match(V: HiResult, P: m_OneUse(SubPattern: m_Ctlz(Op0: m_Value(V&: HiCtlzArg), Op1: m_Value())))) |
| 171 | return false; |
| 172 | |
| 173 | if (!match(V: HiCtlzArg, |
| 174 | P: m_Trunc(Op: m_LShr(L: m_Specific(V: SrcVal), R: m_SpecificInt(V: HalfWidth))))) |
| 175 | return false; |
| 176 | |
| 177 | // LoResult: add/or_disjoint(ctlz(trunc(SrcVal), _), N/2) |
| 178 | Value *CtlzLoCall; |
| 179 | if (!match(V: LoResult, P: m_OneUse(SubPattern: m_AddLike(L: m_Value(V&: CtlzLoCall), |
| 180 | R: m_SpecificInt(V: HalfWidth))))) |
| 181 | return false; |
| 182 | |
| 183 | Value *LoCtlzArg; |
| 184 | if (!match(V: CtlzLoCall, P: m_OneUse(SubPattern: m_Ctlz(Op0: m_Value(V&: LoCtlzArg), Op1: m_Value())))) |
| 185 | return false; |
| 186 | |
| 187 | if (!match(V: LoCtlzArg, P: m_Trunc(Op: m_Specific(V: SrcVal)))) |
| 188 | return false; |
| 189 | |
| 190 | // Match successful. |
| 191 | IRBuilder<> Builder(&I); |
| 192 | Value *CtlzWide = Builder.CreateIntrinsic( |
| 193 | ID: Intrinsic::ctlz, OverloadTypes: {SrcVal->getType()}, Args: {SrcVal, Builder.getFalse()}); |
| 194 | Value *Trunc = Builder.CreateTrunc(V: CtlzWide, DestTy: HalfTy); |
| 195 | |
| 196 | I.replaceAllUsesWith(V: Trunc); |
| 197 | ++NumSelectCTLZFolded; |
| 198 | return true; |
| 199 | } |
| 200 | |
| 201 | /// Common entry point for folding select-based split cttz/ctlz patterns. |
| 202 | /// Performs the initial select and type matching shared by both transforms, |
| 203 | /// then delegates to foldSelectSplitCTTZ and foldSelectSplitCTLZ. |
| 204 | static bool foldSelectSplitCTLZCTTZ(Instruction &I) { |
| 205 | Value *Cond, *TrueVal, *FalseVal; |
| 206 | if (!match(V: &I, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TrueVal), R: m_Value(V&: FalseVal)))) |
| 207 | return false; |
| 208 | |
| 209 | Type *Ty = I.getType(); |
| 210 | if (!Ty->isIntegerTy()) |
| 211 | return false; |
| 212 | |
| 213 | // Bail out on very small types (i1, i2): the full-width cttz/ctlz can return |
| 214 | // values not representable in the half type (e.g., cttz.i4 can return 4, |
| 215 | // which doesn't fit in i2). |
| 216 | if (Ty->getIntegerBitWidth() <= 2) |
| 217 | return false; |
| 218 | |
| 219 | CmpPredicate Pred; |
| 220 | Value *CmpOp; |
| 221 | if (!match(V: Cond, P: m_ICmp(Pred, L: m_Value(V&: CmpOp), R: m_ZeroInt())) || |
| 222 | !ICmpInst::isEquality(P: Pred)) |
| 223 | return false; |
| 224 | |
| 225 | // Canonicalize select operands. |
| 226 | if (Pred == CmpInst::ICMP_NE) |
| 227 | std::swap(a&: TrueVal, b&: FalseVal); |
| 228 | |
| 229 | return foldSelectSplitCTTZ(I, LoTrunc: CmpOp, HiResult: TrueVal, LoResult: FalseVal, HalfTy: Ty) || |
| 230 | foldSelectSplitCTLZ(I, HiPart: CmpOp, LoResult: TrueVal, HiResult: FalseVal, HalfTy: Ty); |
| 231 | } |
| 232 | |
| 233 | /// Match a pattern for a bitwise funnel/rotate operation that partially guards |
| 234 | /// against undefined behavior by branching around the funnel-shift/rotation |
| 235 | /// when the shift amount is 0. |
| 236 | static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT) { |
| 237 | if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2) |
| 238 | return false; |
| 239 | |
| 240 | // As with the one-use checks below, this is not strictly necessary, but we |
| 241 | // are being cautious to avoid potential perf regressions on targets that |
| 242 | // do not actually have a funnel/rotate instruction (where the funnel shift |
| 243 | // would be expanded back into math/shift/logic ops). |
| 244 | if (!isPowerOf2_32(Value: I.getType()->getScalarSizeInBits())) |
| 245 | return false; |
| 246 | |
| 247 | // Match V to funnel shift left/right and capture the source operands and |
| 248 | // shift amount. |
| 249 | auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1, |
| 250 | Value *&ShAmt) { |
| 251 | unsigned Width = V->getType()->getScalarSizeInBits(); |
| 252 | |
| 253 | // fshl(ShVal0, ShVal1, ShAmt) |
| 254 | // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt)) |
| 255 | if (match(V, P: m_OneUse(SubPattern: m_c_Or( |
| 256 | L: m_Shl(L: m_Value(V&: ShVal0), R: m_Value(V&: ShAmt)), |
| 257 | R: m_LShr(L: m_Value(V&: ShVal1), R: m_Sub(L: m_SpecificInt(V: Width), |
| 258 | R: m_Deferred(V: ShAmt))))))) { |
| 259 | return Intrinsic::fshl; |
| 260 | } |
| 261 | |
| 262 | // fshr(ShVal0, ShVal1, ShAmt) |
| 263 | // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt)) |
| 264 | if (match(V, |
| 265 | P: m_OneUse(SubPattern: m_c_Or(L: m_Shl(L: m_Value(V&: ShVal0), R: m_Sub(L: m_SpecificInt(V: Width), |
| 266 | R: m_Value(V&: ShAmt))), |
| 267 | R: m_LShr(L: m_Value(V&: ShVal1), R: m_Deferred(V: ShAmt)))))) { |
| 268 | return Intrinsic::fshr; |
| 269 | } |
| 270 | |
| 271 | return Intrinsic::not_intrinsic; |
| 272 | }; |
| 273 | |
| 274 | // One phi operand must be a funnel/rotate operation, and the other phi |
| 275 | // operand must be the source value of that funnel/rotate operation: |
| 276 | // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ] |
| 277 | // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ] |
| 278 | // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ] |
| 279 | PHINode &Phi = cast<PHINode>(Val&: I); |
| 280 | unsigned FunnelOp = 0, GuardOp = 1; |
| 281 | Value *P0 = Phi.getOperand(i_nocapture: 0), *P1 = Phi.getOperand(i_nocapture: 1); |
| 282 | Value *ShVal0, *ShVal1, *ShAmt; |
| 283 | Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt); |
| 284 | if (IID == Intrinsic::not_intrinsic || |
| 285 | (IID == Intrinsic::fshl && ShVal0 != P1) || |
| 286 | (IID == Intrinsic::fshr && ShVal1 != P1)) { |
| 287 | IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt); |
| 288 | if (IID == Intrinsic::not_intrinsic || |
| 289 | (IID == Intrinsic::fshl && ShVal0 != P0) || |
| 290 | (IID == Intrinsic::fshr && ShVal1 != P0)) |
| 291 | return false; |
| 292 | assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) && |
| 293 | "Pattern must match funnel shift left or right" ); |
| 294 | std::swap(a&: FunnelOp, b&: GuardOp); |
| 295 | } |
| 296 | |
| 297 | // The incoming block with our source operand must be the "guard" block. |
| 298 | // That must contain a cmp+branch to avoid the funnel/rotate when the shift |
| 299 | // amount is equal to 0. The other incoming block is the block with the |
| 300 | // funnel/rotate. |
| 301 | BasicBlock *GuardBB = Phi.getIncomingBlock(i: GuardOp); |
| 302 | BasicBlock *FunnelBB = Phi.getIncomingBlock(i: FunnelOp); |
| 303 | Instruction *TermI = GuardBB->getTerminator(); |
| 304 | |
| 305 | // Ensure that the shift values dominate each block. |
| 306 | if (!DT.dominates(Def: ShVal0, User: TermI) || !DT.dominates(Def: ShVal1, User: TermI)) |
| 307 | return false; |
| 308 | |
| 309 | BasicBlock *PhiBB = Phi.getParent(); |
| 310 | if (!match(V: TermI, P: m_Br(C: m_SpecificICmp(MatchPred: CmpInst::ICMP_EQ, L: m_Specific(V: ShAmt), |
| 311 | R: m_ZeroInt()), |
| 312 | T: m_SpecificBB(BB: PhiBB), F: m_SpecificBB(BB: FunnelBB)))) |
| 313 | return false; |
| 314 | |
| 315 | IRBuilder<> Builder(PhiBB->getFirstInsertionPt()); |
| 316 | |
| 317 | if (ShVal0 == ShVal1) |
| 318 | ++NumGuardedRotates; |
| 319 | else |
| 320 | ++NumGuardedFunnelShifts; |
| 321 | |
| 322 | // If this is not a rotate then the select was blocking poison from the |
| 323 | // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it. |
| 324 | bool IsFshl = IID == Intrinsic::fshl; |
| 325 | if (ShVal0 != ShVal1) { |
| 326 | if (IsFshl && !llvm::isGuaranteedNotToBePoison(V: ShVal1)) |
| 327 | ShVal1 = Builder.CreateFreeze(V: ShVal1); |
| 328 | else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(V: ShVal0)) |
| 329 | ShVal0 = Builder.CreateFreeze(V: ShVal0); |
| 330 | } |
| 331 | |
| 332 | // We matched a variation of this IR pattern: |
| 333 | // GuardBB: |
| 334 | // %cmp = icmp eq i32 %ShAmt, 0 |
| 335 | // br i1 %cmp, label %PhiBB, label %FunnelBB |
| 336 | // FunnelBB: |
| 337 | // %sub = sub i32 32, %ShAmt |
| 338 | // %shr = lshr i32 %ShVal1, %sub |
| 339 | // %shl = shl i32 %ShVal0, %ShAmt |
| 340 | // %fsh = or i32 %shr, %shl |
| 341 | // br label %PhiBB |
| 342 | // PhiBB: |
| 343 | // %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ] |
| 344 | // --> |
| 345 | // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt) |
| 346 | Phi.replaceAllUsesWith( |
| 347 | V: Builder.CreateIntrinsic(ID: IID, OverloadTypes: Phi.getType(), Args: {ShVal0, ShVal1, ShAmt})); |
| 348 | return true; |
| 349 | } |
| 350 | |
| 351 | /// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and |
| 352 | /// the bit indexes (Mask) needed by a masked compare. If we're matching a chain |
| 353 | /// of 'and' ops, then we also need to capture the fact that we saw an |
| 354 | /// "and X, 1", so that's an extra return value for that case. |
| 355 | namespace { |
| 356 | struct MaskOps { |
| 357 | Value *Root = nullptr; |
| 358 | APInt Mask; |
| 359 | bool MatchAndChain; |
| 360 | bool FoundAnd1 = false; |
| 361 | |
| 362 | MaskOps(unsigned BitWidth, bool MatchAnds) |
| 363 | : Mask(APInt::getZero(numBits: BitWidth)), MatchAndChain(MatchAnds) {} |
| 364 | }; |
| 365 | } // namespace |
| 366 | |
| 367 | /// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a |
| 368 | /// chain of 'and' or 'or' instructions looking for shift ops of a common source |
| 369 | /// value. Examples: |
| 370 | /// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8) |
| 371 | /// returns { X, 0x129 } |
| 372 | /// and (and (X >> 1), 1), (X >> 4) |
| 373 | /// returns { X, 0x12 } |
| 374 | static bool matchAndOrChain(Value *V, MaskOps &MOps) { |
| 375 | Value *Op0, *Op1; |
| 376 | if (MOps.MatchAndChain) { |
| 377 | // Recurse through a chain of 'and' operands. This requires an extra check |
| 378 | // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere |
| 379 | // in the chain to know that all of the high bits are cleared. |
| 380 | if (match(V, P: m_And(L: m_Value(V&: Op0), R: m_One()))) { |
| 381 | MOps.FoundAnd1 = true; |
| 382 | return matchAndOrChain(V: Op0, MOps); |
| 383 | } |
| 384 | if (match(V, P: m_And(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))) |
| 385 | return matchAndOrChain(V: Op0, MOps) && matchAndOrChain(V: Op1, MOps); |
| 386 | } else { |
| 387 | // Recurse through a chain of 'or' operands. |
| 388 | if (match(V, P: m_Or(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))) |
| 389 | return matchAndOrChain(V: Op0, MOps) && matchAndOrChain(V: Op1, MOps); |
| 390 | } |
| 391 | |
| 392 | // We need a shift-right or a bare value representing a compare of bit 0 of |
| 393 | // the original source operand. |
| 394 | Value *Candidate; |
| 395 | const APInt *BitIndex = nullptr; |
| 396 | if (!match(V, P: m_LShr(L: m_Value(V&: Candidate), R: m_APInt(Res&: BitIndex)))) |
| 397 | Candidate = V; |
| 398 | |
| 399 | // Initialize result source operand. |
| 400 | if (!MOps.Root) |
| 401 | MOps.Root = Candidate; |
| 402 | |
| 403 | // The shift constant is out-of-range? This code hasn't been simplified. |
| 404 | if (BitIndex && BitIndex->uge(RHS: MOps.Mask.getBitWidth())) |
| 405 | return false; |
| 406 | |
| 407 | // Fill in the mask bit derived from the shift constant. |
| 408 | MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0); |
| 409 | return MOps.Root == Candidate; |
| 410 | } |
| 411 | |
| 412 | /// Match patterns that correspond to "any-bits-set" and "all-bits-set". |
| 413 | /// These will include a chain of 'or' or 'and'-shifted bits from a |
| 414 | /// common source value: |
| 415 | /// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0 |
| 416 | /// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask |
| 417 | /// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns |
| 418 | /// that differ only with a final 'not' of the result. We expect that final |
| 419 | /// 'not' to be folded with the compare that we create here (invert predicate). |
| 420 | static bool foldAnyOrAllBitsSet(Instruction &I) { |
| 421 | // The 'any-bits-set' ('or' chain) pattern is simpler to match because the |
| 422 | // final "and X, 1" instruction must be the final op in the sequence. |
| 423 | bool MatchAllBitsSet; |
| 424 | bool MatchTrunc; |
| 425 | Value *X; |
| 426 | if (I.getType()->isIntOrIntVectorTy(BitWidth: 1)) { |
| 427 | if (match(V: &I, P: m_Trunc(Op: m_OneUse(SubPattern: m_And(L: m_Value(), R: m_Value()))))) |
| 428 | MatchAllBitsSet = true; |
| 429 | else if (match(V: &I, P: m_Trunc(Op: m_OneUse(SubPattern: m_Or(L: m_Value(), R: m_Value()))))) |
| 430 | MatchAllBitsSet = false; |
| 431 | else |
| 432 | return false; |
| 433 | MatchTrunc = true; |
| 434 | X = I.getOperand(i: 0); |
| 435 | } else { |
| 436 | if (match(V: &I, P: m_c_And(L: m_OneUse(SubPattern: m_And(L: m_Value(), R: m_Value())), R: m_Value()))) { |
| 437 | X = &I; |
| 438 | MatchAllBitsSet = true; |
| 439 | } else if (match(V: &I, |
| 440 | P: m_And(L: m_OneUse(SubPattern: m_Or(L: m_Value(), R: m_Value())), R: m_One()))) { |
| 441 | X = I.getOperand(i: 0); |
| 442 | MatchAllBitsSet = false; |
| 443 | } else |
| 444 | return false; |
| 445 | MatchTrunc = false; |
| 446 | } |
| 447 | Type *Ty = X->getType(); |
| 448 | |
| 449 | MaskOps MOps(Ty->getScalarSizeInBits(), MatchAllBitsSet); |
| 450 | if (!matchAndOrChain(V: X, MOps) || |
| 451 | (MatchAllBitsSet && !MatchTrunc && !MOps.FoundAnd1)) |
| 452 | return false; |
| 453 | |
| 454 | // The pattern was found. Create a masked compare that replaces all of the |
| 455 | // shift and logic ops. |
| 456 | IRBuilder<> Builder(&I); |
| 457 | Constant *Mask = ConstantInt::get(Ty, V: MOps.Mask); |
| 458 | Value *And = Builder.CreateAnd(LHS: MOps.Root, RHS: Mask); |
| 459 | Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(LHS: And, RHS: Mask) |
| 460 | : Builder.CreateIsNotNull(Arg: And); |
| 461 | Value *Zext = MatchTrunc ? Cmp : Builder.CreateZExt(V: Cmp, DestTy: Ty); |
| 462 | I.replaceAllUsesWith(V: Zext); |
| 463 | ++NumAnyOrAllBitsSet; |
| 464 | return true; |
| 465 | } |
| 466 | |
| 467 | /// Helper function to replace an instruction with a popcount intrinsic. |
| 468 | /// This creates the ctpop intrinsic with an optional truncation appended at the |
| 469 | /// end, and replaces all uses of the instruction. |
| 470 | static void replaceWithPopCount(Instruction &I, Value *Root) { |
| 471 | LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n" ); |
| 472 | Type *RootTy = Root->getType(); |
| 473 | Type *OrigTy = I.getType(); |
| 474 | |
| 475 | IRBuilder<> Builder(&I); |
| 476 | Value *NewVal = Builder.CreateIntrinsic(ID: Intrinsic::ctpop, OverloadTypes: RootTy, Args: {Root}); |
| 477 | if (OrigTy != RootTy) { |
| 478 | assert(RootTy->getScalarSizeInBits() > OrigTy->getScalarSizeInBits() && |
| 479 | "Only truncation is supported for now" ); |
| 480 | NewVal = Builder.CreateTrunc(V: NewVal, DestTy: OrigTy); |
| 481 | } |
| 482 | I.replaceAllUsesWith(V: NewVal); |
| 483 | ++NumPopCountRecognized; |
| 484 | } |
| 485 | |
| 486 | // Matches the common innermost steps of the Hacker's Delight popcount idiom: |
| 487 | // V = ((x + (x >> 4)) & 0x0F...) |
| 488 | // x = (y & 0x33...) + ((y >> 2) & 0x33...) [or y - 3*((y>>2)&0x33...)] |
| 489 | // y = Root - ((Root >> 1) & 0x55...) |
| 490 | // This computes the popcount for each byte. |
| 491 | // Returns Root on success, nullptr on failure. |
| 492 | static Value *matchPopCountBytes(Value *V, unsigned Len, const DataLayout &DL) { |
| 493 | APInt Mask55 = APInt::getSplat(NewLen: Len, V: APInt(8, 0x55)); |
| 494 | APInt Mask33 = APInt::getSplat(NewLen: Len, V: APInt(8, 0x33)); |
| 495 | APInt Mask0F = APInt::getSplat(NewLen: Len, V: APInt(8, 0x0F)); |
| 496 | |
| 497 | Value *Add2; |
| 498 | // Matching "((x + (x >> 4)) & 0x0F...)". |
| 499 | if (!match(V, P: m_And(L: m_c_Add(L: m_LShr(L: m_Value(V&: Add2), R: m_SpecificInt(V: 4)), |
| 500 | R: m_Deferred(V: Add2)), |
| 501 | R: m_SpecificInt(V: Mask0F)))) |
| 502 | return nullptr; |
| 503 | |
| 504 | Value *Sub1; |
| 505 | APInt NegThree(Len, -3, /*isSigned=*/true); |
| 506 | // Match |
| 507 | // x = (x & 0x33333333) + ((x >> 2) & 0x33333333)" |
| 508 | // Or |
| 509 | // x = x - 3*((x >> 2) & 0x33333333) |
| 510 | if (!match(V: Add2, P: m_c_Add(L: m_And(L: m_LShr(L: m_Value(V&: Sub1), R: m_SpecificInt(V: 2)), |
| 511 | R: m_SpecificInt(V: Mask33)), |
| 512 | R: m_And(L: m_Deferred(V: Sub1), R: m_SpecificInt(V: Mask33)))) && |
| 513 | !match(V: Add2, P: m_Add(L: m_Mul(L: m_And(L: m_LShr(L: m_Value(V&: Sub1), R: m_SpecificInt(V: 2)), |
| 514 | R: m_SpecificInt(V: Mask33)), |
| 515 | R: m_SpecificInt(V: NegThree)), |
| 516 | R: m_Deferred(V: Sub1)))) |
| 517 | return nullptr; |
| 518 | |
| 519 | Value *Root, *LShr; |
| 520 | const APInt *AndMask; |
| 521 | // Matching "x - ((x >> 1) & 0x55...)". |
| 522 | if (!match(V: Sub1, |
| 523 | P: m_Sub(L: m_Value(V&: Root), R: m_And(L: m_Value(V&: LShr, P: m_LShr(L: m_Deferred(V: Root), |
| 524 | R: m_SpecificInt(V: 1))), |
| 525 | R: m_APInt(Res&: AndMask))))) |
| 526 | return nullptr; |
| 527 | |
| 528 | if (*AndMask != Mask55) { |
| 529 | // Accept a narrowed mask if missing bits are known zero in Root>>1. |
| 530 | if (!AndMask->isSubsetOf(RHS: Mask55)) |
| 531 | return nullptr; |
| 532 | APInt NeededMask = Mask55 & ~*AndMask; |
| 533 | if (!MaskedValueIsZero(V: LShr, Mask: NeededMask, SQ: SimplifyQuery(DL))) |
| 534 | return nullptr; |
| 535 | } |
| 536 | |
| 537 | return Root; |
| 538 | } |
| 539 | |
| 540 | // Try to recognize below function as popcount intrinsic. |
| 541 | // This is the "best" algorithm from |
| 542 | // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel |
| 543 | // Also used in TargetLowering::expandCTPOP(). |
| 544 | // |
| 545 | // int popcount(unsigned int i) { |
| 546 | // i = i - ((i >> 1) & 0x55555555); |
| 547 | // i = (i & 0x33333333) + ((i >> 2) & 0x33333333); |
| 548 | // i = ((i + (i >> 4)) & 0x0F0F0F0F); |
| 549 | // return (i * 0x01010101) >> 24; |
| 550 | // } |
| 551 | static bool tryToRecognizePopCount(Instruction &I) { |
| 552 | if (I.getOpcode() != Instruction::LShr) |
| 553 | return false; |
| 554 | |
| 555 | Type *Ty = I.getType(); |
| 556 | if (!Ty->isIntOrIntVectorTy()) |
| 557 | return false; |
| 558 | |
| 559 | unsigned Len = Ty->getScalarSizeInBits(); |
| 560 | // Len==8 is handled by tryToRecognizePopCount2n3. |
| 561 | // FIXME: other irregular type lengths. |
| 562 | if (Len > 128 || Len <= 8 || Len % 8 != 0) |
| 563 | return false; |
| 564 | |
| 565 | APInt Mask01 = APInt::getSplat(NewLen: Len, V: APInt(8, 0x01)); |
| 566 | |
| 567 | Value *Op0 = I.getOperand(i: 0); |
| 568 | Value *Op1 = I.getOperand(i: 1); |
| 569 | Value *MulOp0; |
| 570 | // Matching "(i * 0x01010101...) >> 24". |
| 571 | if (!match(V: Op0, P: m_Mul(L: m_Value(V&: MulOp0), R: m_SpecificInt(V: Mask01))) || |
| 572 | !match(V: Op1, P: m_SpecificInt(V: Len - 8))) |
| 573 | return false; |
| 574 | |
| 575 | Value *Root = matchPopCountBytes(V: MulOp0, Len, DL: I.getDataLayout()); |
| 576 | if (!Root) |
| 577 | return false; |
| 578 | |
| 579 | replaceWithPopCount(I, Root); |
| 580 | return true; |
| 581 | } |
| 582 | |
| 583 | // Try to recognize below function as popcount intrinsic. |
| 584 | // Ref. Hacker Delights |
| 585 | // int popcount32(unsigned int i) { |
| 586 | // uWord = (uWord & 0x55555555) + ((uWord>>1) & 0x55555555); |
| 587 | // uWord = (uWord & 0x33333333) + ((uWord>>2) & 0x33333333); |
| 588 | // uWord = (uWord & 0x0F0F0F0F) + ((uWord>>4) & 0x0F0F0F0F); |
| 589 | // uWord = (uWord & 0x00FF00FF) + ((uWord>>8) & 0x00FF00FF); |
| 590 | // return (uWord & 0x0000FFFF) + (uWord>>16); |
| 591 | // } |
| 592 | // int popcount64(unsigned long i) { |
| 593 | // uWord = (uWord & 0x5555555555555555) + ((uWord>>1) & 0x5555555555555555); |
| 594 | // uWord = (uWord & 0x3333333333333333) + ((uWord>>2) & 0x3333333333333333); |
| 595 | // uWord = (uWord & 0x0F0F0F0F0F0F0F0F) + ((uWord>>4) & 0x0F0F0F0F0F0F0F0F); |
| 596 | // uWord = (uWord & 0x00FF00FF00FF00FF) + ((uWord>>8) & 0x00FF00FF00FF00FF); |
| 597 | // uWord = (uWord & 0x0000FFFF0000FFFF) + ((uWord>>16) & 0x0000FFFF0000FFFF); |
| 598 | // return (uWord & 0x00000000FFFFFFFF) + (uWord>>32) & 0x00000000FFFFFFFF; |
| 599 | // } |
| 600 | // |
| 601 | // InstCombine may narrow AND masks when it can prove the removed bits are |
| 602 | // known zero (e.g. 0x0F0F0F0F -> 0x07070707). We accept such narrowed masks |
| 603 | // by checking they are subsets of the expected masks and verifying the missing |
| 604 | // bits are known zero via MaskedValueIsZero. |
| 605 | static bool tryToRecognizePopCount1(Instruction &I) { |
| 606 | if (I.getOpcode() != Instruction::Add) |
| 607 | return false; |
| 608 | |
| 609 | Type *Ty = I.getType(); |
| 610 | if (!Ty->isIntOrIntVectorTy()) |
| 611 | return false; |
| 612 | |
| 613 | unsigned Len = Ty->getScalarSizeInBits(); |
| 614 | if (Len > 64 || Len <= 8 || Len % 8 != 0) |
| 615 | return false; |
| 616 | |
| 617 | // Len should be a power of 2 for the loop to work correctly |
| 618 | if (!isPowerOf2_32(Value: Len)) |
| 619 | return false; |
| 620 | |
| 621 | APInt Mask55 = APInt::getSplat(NewLen: Len, V: APInt(8, 0x55)); |
| 622 | APInt Mask33 = APInt::getSplat(NewLen: Len, V: APInt(8, 0x33)); |
| 623 | |
| 624 | SimplifyQuery SQ(I.getDataLayout()); |
| 625 | |
| 626 | // Check if CapturedMask is a valid (possibly narrowed) version of |
| 627 | // ExpectedMask for the given Operand. Returns true if the masks match |
| 628 | // exactly, or if CapturedMask is a subset and the missing bits are |
| 629 | // known zero in the Operand. |
| 630 | auto isValidNarrowedMask = [&](const APInt &CapturedMask, |
| 631 | const APInt &ExpectedMask, |
| 632 | Value *Operand) -> bool { |
| 633 | if (CapturedMask == ExpectedMask) |
| 634 | return true; |
| 635 | if (!CapturedMask.isSubsetOf(RHS: ExpectedMask)) |
| 636 | return false; |
| 637 | APInt NeededMask = ExpectedMask & ~CapturedMask; |
| 638 | return MaskedValueIsZero(V: Operand, Mask: NeededMask, SQ); |
| 639 | }; |
| 640 | |
| 641 | // For "(x & M) + ((x >> S) & M)" patterns, both AND masks may be narrowed. |
| 642 | // Require subsets of BaseMask and prove any implied missing bits are zero. |
| 643 | auto narrowAddPairMasksOk = [&](const APInt &BaseMask, unsigned ShiftAmt, |
| 644 | Value *Val, const APInt &AndMask1, |
| 645 | const APInt &AndMask2) -> bool { |
| 646 | if (!AndMask1.isSubsetOf(RHS: BaseMask) || !AndMask2.isSubsetOf(RHS: BaseMask)) |
| 647 | return false; |
| 648 | APInt NeededShifted = (BaseMask & ~AndMask1).shl(shiftAmt: ShiftAmt); |
| 649 | APInt NeededUnshifted = BaseMask & ~AndMask2; |
| 650 | APInt AllNeeded = NeededShifted | NeededUnshifted; |
| 651 | return AllNeeded.isZero() || MaskedValueIsZero(V: Val, Mask: AllNeeded, SQ); |
| 652 | }; |
| 653 | |
| 654 | Value *ShiftOp; |
| 655 | Value *Start = &I; |
| 656 | for (unsigned I = Len; I >= 8; I = I / 2) { |
| 657 | APInt Mask = APInt::getSplat(NewLen: Len, V: APInt::getLowBitsSet(numBits: I, loBitsSet: I / 2)); |
| 658 | const APInt *AndMask1 = nullptr, *AndMask2 = nullptr; |
| 659 | |
| 660 | // Matching "(uWord & Mask) + ((uWord>>I/2) & Mask)". |
| 661 | // Both masks might have been narrowed by InstCombine. |
| 662 | if (match(V: Start, |
| 663 | P: m_c_Add(L: m_And(L: m_LShr(L: m_Value(V&: ShiftOp), R: m_SpecificInt(V: I / 2)), |
| 664 | R: m_APInt(Res&: AndMask1)), |
| 665 | R: m_And(L: m_Deferred(V: ShiftOp), R: m_APInt(Res&: AndMask2))))) { |
| 666 | if (!narrowAddPairMasksOk(Mask, I / 2, ShiftOp, *AndMask1, *AndMask2)) |
| 667 | return false; |
| 668 | } |
| 669 | // Matching "(uWord & Mask) + (uWord>>I/2)". |
| 670 | // The mask might have been narrowed by InstCombine. |
| 671 | else if (match(V: Start, |
| 672 | P: m_c_Add(L: m_LShr(L: m_Value(V&: ShiftOp), R: m_SpecificInt(V: I / 2)), |
| 673 | R: m_And(L: m_Deferred(V: ShiftOp), R: m_APInt(Res&: AndMask1))))) { |
| 674 | if (!isValidNarrowedMask(*AndMask1, Mask, ShiftOp)) |
| 675 | return false; |
| 676 | } else |
| 677 | return false; |
| 678 | Start = ShiftOp; |
| 679 | } |
| 680 | |
| 681 | // Matching "uWord = (uWord & Mask33) + ((uWord>>2) & Mask33)". |
| 682 | const APInt *AndMask1 = nullptr, *AndMask2 = nullptr; |
| 683 | if (!match(V: Start, P: m_c_Add(L: m_And(L: m_LShr(L: m_Value(V&: ShiftOp), R: m_SpecificInt(V: 2)), |
| 684 | R: m_APInt(Res&: AndMask1)), |
| 685 | R: m_And(L: m_Deferred(V: ShiftOp), R: m_APInt(Res&: AndMask2))))) |
| 686 | return false; |
| 687 | if (!narrowAddPairMasksOk(Mask33, 2, ShiftOp, *AndMask1, *AndMask2)) |
| 688 | return false; |
| 689 | |
| 690 | Start = ShiftOp; |
| 691 | Value *Root; |
| 692 | // Matching "uWord = (uWord & Mask55) + ((uWord>>1) & Mask55)". |
| 693 | AndMask1 = nullptr; |
| 694 | AndMask2 = nullptr; |
| 695 | if (!match(V: Start, P: m_c_Add(L: m_And(L: m_LShr(L: m_Value(V&: Root), R: m_SpecificInt(V: 1)), |
| 696 | R: m_APInt(Res&: AndMask1)), |
| 697 | R: m_And(L: m_Deferred(V: Root), R: m_APInt(Res&: AndMask2))))) |
| 698 | return false; |
| 699 | if (!narrowAddPairMasksOk(Mask55, 1, Root, *AndMask1, *AndMask2)) |
| 700 | return false; |
| 701 | |
| 702 | replaceWithPopCount(I, Root); |
| 703 | return true; |
| 704 | } |
| 705 | |
| 706 | // Try to recognize below function as popcount intrinsic. |
| 707 | // Ref. Hackers Delight |
| 708 | // int popcnt(unsigned x) { |
| 709 | // x = x - ((x >> 1) & 0x55555555); |
| 710 | // x = (x & 0x33333333) + ((x >> 2) & 0x33333333); |
| 711 | // x = (x + (x >> 4)) & 0x0F0F0F0F; |
| 712 | // x = x + (x >> 8); |
| 713 | // x = x + (x >> 16); |
| 714 | // return x & 0x0000003F; |
| 715 | // } |
| 716 | |
| 717 | // int popcnt(unsigned x) { |
| 718 | // x = x - ((x >> 1) & 0x55555555); |
| 719 | // x = x - 3*((x >> 2) & 0x33333333); |
| 720 | // x = (x + (x >> 4)) & 0x0F0F0F0F; |
| 721 | // x = x + (x >> 8); |
| 722 | // x = x + (x >> 16); |
| 723 | // return x & 0x0000003F; |
| 724 | // } |
| 725 | static bool tryToRecognizePopCount2n3(Instruction &I) { |
| 726 | if (I.getOpcode() != Instruction::And) |
| 727 | return false; |
| 728 | |
| 729 | Type *Ty = I.getType(); |
| 730 | if (!Ty->isIntOrIntVectorTy()) |
| 731 | return false; |
| 732 | |
| 733 | unsigned Len = Ty->getScalarSizeInBits(); |
| 734 | Value *Add1; |
| 735 | if (Len == 8) { |
| 736 | // Special case for Len == 8, we only need to match the And at the end of |
| 737 | // matchPopCountBytes. |
| 738 | Add1 = &I; |
| 739 | } else { |
| 740 | const APInt *MaskRes; |
| 741 | if (!match(V: &I, P: m_And(L: m_Value(V&: Add1), R: m_APInt(Res&: MaskRes)))) |
| 742 | return false; |
| 743 | |
| 744 | // Since `(trunc (and x, C))` might be canonicalized into `(and (trunc x), |
| 745 | // C)` we might loose the opportunity to recognize `(trunc (popcount y))`. |
| 746 | // The following block tries to capture such truncation, update `Len`, and |
| 747 | // append the truncation at the end of the emitting popcount, if there is |
| 748 | // any. |
| 749 | Value *TruncSrc; |
| 750 | if (match(V: Add1, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: TruncSrc))))) { |
| 751 | Add1 = TruncSrc; |
| 752 | Len = Add1->getType()->getScalarSizeInBits(); |
| 753 | } |
| 754 | |
| 755 | if (Len > 64 || Len <= 8 || Len % 8 != 0) |
| 756 | return false; |
| 757 | |
| 758 | // Len should be a power of 2 for the loop to work correctly |
| 759 | if (!isPowerOf2_32(Value: Len)) |
| 760 | return false; |
| 761 | |
| 762 | // Number of bits needed to represent Len. |
| 763 | unsigned NumLenBits = Log2_32(Value: Len) + 1; |
| 764 | // The "mask" here really only needs to fulfill two conditions: |
| 765 | // (1) All ones for the lower NumLenBits-bits |
| 766 | // (2) Zeros from bit 8 and onward. |
| 767 | // Condition (1) is straightforward. The reason behind condition |
| 768 | // (2) is that we don't care any 8-bit chunks but the first one |
| 769 | // in the original divide-and-conquer algorithm. |
| 770 | if (MaskRes->countTrailingOnes() < NumLenBits || |
| 771 | MaskRes->getActiveBits() > 8) |
| 772 | return false; |
| 773 | |
| 774 | for (unsigned I = Len; I >= 16; I = I / 2) { |
| 775 | Value *Add2; |
| 776 | // Matching "x = x + (x >> I/2)" for I-bit. |
| 777 | if (!match(V: Add1, P: m_c_Add(L: m_LShr(L: m_Value(V&: Add2), R: m_SpecificInt(V: I / 2)), |
| 778 | R: m_Deferred(V: Add2)))) |
| 779 | return false; |
| 780 | Add1 = Add2; |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | Value *Root = matchPopCountBytes(V: Add1, Len, DL: I.getDataLayout()); |
| 785 | if (!Root) |
| 786 | return false; |
| 787 | |
| 788 | replaceWithPopCount(I, Root); |
| 789 | return true; |
| 790 | } |
| 791 | |
| 792 | /// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and |
| 793 | /// C2 saturate the value of the fp conversion. The transform is not reversable |
| 794 | /// as the fptosi.sat is more defined than the input - all values produce a |
| 795 | /// valid value for the fptosi.sat, where as some produce poison for original |
| 796 | /// that were out of range of the integer conversion. The reversed pattern may |
| 797 | /// use fmax and fmin instead. As we cannot directly reverse the transform, and |
| 798 | /// it is not always profitable, we make it conditional on the cost being |
| 799 | /// reported as lower by TTI. |
| 800 | static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI) { |
| 801 | // Look for min(max(fptosi, converting to fptosi_sat. |
| 802 | Value *In; |
| 803 | const APInt *MinC, *MaxC; |
| 804 | if (!match(V: &I, P: m_SMax(Op0: m_OneUse(SubPattern: m_SMin(Op0: m_OneUse(SubPattern: m_FPToSI(Op: m_Value(V&: In))), |
| 805 | Op1: m_APInt(Res&: MinC))), |
| 806 | Op1: m_APInt(Res&: MaxC))) && |
| 807 | !match(V: &I, P: m_SMin(Op0: m_OneUse(SubPattern: m_SMax(Op0: m_OneUse(SubPattern: m_FPToSI(Op: m_Value(V&: In))), |
| 808 | Op1: m_APInt(Res&: MaxC))), |
| 809 | Op1: m_APInt(Res&: MinC)))) |
| 810 | return false; |
| 811 | |
| 812 | // Check that the constants clamp a saturate. |
| 813 | if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1) |
| 814 | return false; |
| 815 | |
| 816 | Type *IntTy = I.getType(); |
| 817 | Type *FpTy = In->getType(); |
| 818 | Type *SatTy = |
| 819 | IntegerType::get(C&: IntTy->getContext(), NumBits: (*MinC + 1).exactLogBase2() + 1); |
| 820 | if (auto *VecTy = dyn_cast<VectorType>(Val: IntTy)) |
| 821 | SatTy = VectorType::get(ElementType: SatTy, EC: VecTy->getElementCount()); |
| 822 | |
| 823 | // Get the cost of the intrinsic, and check that against the cost of |
| 824 | // fptosi+smin+smax |
| 825 | InstructionCost SatCost = TTI.getIntrinsicInstrCost( |
| 826 | ICA: IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}), |
| 827 | CostKind: TTI::TCK_RecipThroughput); |
| 828 | SatCost += TTI.getCastInstrCost(Opcode: Instruction::SExt, Dst: IntTy, Src: SatTy, |
| 829 | CCH: TTI::CastContextHint::None, |
| 830 | CostKind: TTI::TCK_RecipThroughput); |
| 831 | |
| 832 | InstructionCost MinMaxCost = TTI.getCastInstrCost( |
| 833 | Opcode: Instruction::FPToSI, Dst: IntTy, Src: FpTy, CCH: TTI::CastContextHint::None, |
| 834 | CostKind: TTI::TCK_RecipThroughput); |
| 835 | MinMaxCost += TTI.getIntrinsicInstrCost( |
| 836 | ICA: IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}), |
| 837 | CostKind: TTI::TCK_RecipThroughput); |
| 838 | MinMaxCost += TTI.getIntrinsicInstrCost( |
| 839 | ICA: IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}), |
| 840 | CostKind: TTI::TCK_RecipThroughput); |
| 841 | |
| 842 | if (SatCost >= MinMaxCost) |
| 843 | return false; |
| 844 | |
| 845 | IRBuilder<> Builder(&I); |
| 846 | Value *Sat = |
| 847 | Builder.CreateIntrinsic(ID: Intrinsic::fptosi_sat, OverloadTypes: {SatTy, FpTy}, Args: In); |
| 848 | I.replaceAllUsesWith(V: Builder.CreateSExt(V: Sat, DestTy: IntTy)); |
| 849 | return true; |
| 850 | } |
| 851 | |
| 852 | /// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids |
| 853 | /// pessimistic codegen that has to account for setting errno and can enable |
| 854 | /// vectorization. |
| 855 | static bool foldSqrt(CallInst *Call, LibFunc Func, TargetTransformInfo &TTI, |
| 856 | TargetLibraryInfo &TLI, AssumptionCache &AC, |
| 857 | DominatorTree &DT) { |
| 858 | // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created |
| 859 | // (because NNAN or the operand arg must not be less than -0.0) and (2) we |
| 860 | // would not end up lowering to a libcall anyway (which could change the value |
| 861 | // of errno), then: |
| 862 | // (1) errno won't be set. |
| 863 | // (2) it is safe to convert this to an intrinsic call. |
| 864 | Type *Ty = Call->getType(); |
| 865 | Value *Arg = Call->getArgOperand(i: 0); |
| 866 | if (TTI.haveFastSqrt(Ty) && |
| 867 | (Call->hasNoNaNs() || |
| 868 | cannotBeOrderedLessThanZero( |
| 869 | V: Arg, SQ: SimplifyQuery(Call->getDataLayout(), &TLI, &DT, &AC, Call)))) { |
| 870 | IRBuilder<> Builder(Call); |
| 871 | Value *NewSqrt = |
| 872 | Builder.CreateIntrinsic(ID: Intrinsic::sqrt, OverloadTypes: Ty, Args: Arg, FMFSource: Call, Name: "sqrt" ); |
| 873 | Call->replaceAllUsesWith(V: NewSqrt); |
| 874 | |
| 875 | // Explicitly erase the old call because a call with side effects is not |
| 876 | // trivially dead. |
| 877 | Call->eraseFromParent(); |
| 878 | return true; |
| 879 | } |
| 880 | |
| 881 | return false; |
| 882 | } |
| 883 | |
| 884 | // Check if this array of constants represents a cttz table. |
| 885 | // Iterate over the elements from \p Table by trying to find/match all |
| 886 | // the numbers from 0 to \p InputBits that should represent cttz results. |
| 887 | static bool isCTTZTable(Constant *Table, const APInt &Mul, const APInt &Shift, |
| 888 | const APInt &AndMask, Type *AccessTy, |
| 889 | unsigned InputBits, const APInt &GEPIdxFactor, |
| 890 | const DataLayout &DL) { |
| 891 | for (unsigned Idx = 0; Idx < InputBits; Idx++) { |
| 892 | APInt Index = |
| 893 | (APInt::getOneBitSet(numBits: InputBits, BitNo: Idx) * Mul).lshr(ShiftAmt: Shift) & AndMask; |
| 894 | ConstantInt *C = dyn_cast_or_null<ConstantInt>( |
| 895 | Val: ConstantFoldLoadFromConst(C: Table, Ty: AccessTy, Offset: Index * GEPIdxFactor, DL)); |
| 896 | if (!C || C->getValue() != Idx) |
| 897 | return false; |
| 898 | } |
| 899 | |
| 900 | return true; |
| 901 | } |
| 902 | |
| 903 | // Try to recognize table-based ctz implementation. |
| 904 | // E.g., an example in C (for more cases please see the llvm/tests): |
| 905 | // int f(unsigned x) { |
| 906 | // static const char table[32] = |
| 907 | // {0, 1, 28, 2, 29, 14, 24, 3, 30, |
| 908 | // 22, 20, 15, 25, 17, 4, 8, 31, 27, |
| 909 | // 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; |
| 910 | // return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27]; |
| 911 | // } |
| 912 | // this can be lowered to `cttz` instruction. |
| 913 | // There is also a special case when the element is 0. |
| 914 | // |
| 915 | // The (x & -x) sets the lowest non-zero bit to 1. The multiply is a de-bruijn |
| 916 | // sequence that contains each pattern of bits in it. The shift extracts |
| 917 | // the top bits after the multiply, and that index into the table should |
| 918 | // represent the number of trailing zeros in the original number. |
| 919 | // |
| 920 | // Here are some examples or LLVM IR for a 64-bit target: |
| 921 | // |
| 922 | // CASE 1: |
| 923 | // %sub = sub i32 0, %x |
| 924 | // %and = and i32 %sub, %x |
| 925 | // %mul = mul i32 %and, 125613361 |
| 926 | // %shr = lshr i32 %mul, 27 |
| 927 | // %idxprom = zext i32 %shr to i64 |
| 928 | // %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0, |
| 929 | // i64 %idxprom |
| 930 | // %0 = load i8, i8* %arrayidx, align 1, !tbaa !8 |
| 931 | // |
| 932 | // CASE 2: |
| 933 | // %sub = sub i32 0, %x |
| 934 | // %and = and i32 %sub, %x |
| 935 | // %mul = mul i32 %and, 72416175 |
| 936 | // %shr = lshr i32 %mul, 26 |
| 937 | // %idxprom = zext i32 %shr to i64 |
| 938 | // %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table, |
| 939 | // i64 0, i64 %idxprom |
| 940 | // %0 = load i16, i16* %arrayidx, align 2, !tbaa !8 |
| 941 | // |
| 942 | // CASE 3: |
| 943 | // %sub = sub i32 0, %x |
| 944 | // %and = and i32 %sub, %x |
| 945 | // %mul = mul i32 %and, 81224991 |
| 946 | // %shr = lshr i32 %mul, 27 |
| 947 | // %idxprom = zext i32 %shr to i64 |
| 948 | // %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table, |
| 949 | // i64 0, i64 %idxprom |
| 950 | // %0 = load i32, i32* %arrayidx, align 4, !tbaa !8 |
| 951 | // |
| 952 | // CASE 4: |
| 953 | // %sub = sub i64 0, %x |
| 954 | // %and = and i64 %sub, %x |
| 955 | // %mul = mul i64 %and, 283881067100198605 |
| 956 | // %shr = lshr i64 %mul, 58 |
| 957 | // %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0, |
| 958 | // i64 %shr |
| 959 | // %0 = load i8, i8* %arrayidx, align 1, !tbaa !8 |
| 960 | // |
| 961 | // All these can be lowered to @llvm.cttz.i32/64 intrinsics. |
| 962 | // |
| 963 | // This shares its initial match (load from a GEP into a constant table with |
| 964 | // a single variable index) with tryToRecognizeTableBasedLog2() below; see |
| 965 | // tryToRecognizeTableBasedPatterns(). |
| 966 | static bool tryToRecognizeTableBasedCttz(LoadInst *LI, Type *AccessType, |
| 967 | GlobalVariable *GVTable, Value *GepIdx, |
| 968 | const APInt &GEPScale, |
| 969 | const DataLayout &DL) { |
| 970 | Value *X1; |
| 971 | const APInt *MulConst, *ShiftConst, *AndCst = nullptr; |
| 972 | // Check that the gep variable index is ((x & -x) * MulConst) >> ShiftConst. |
| 973 | // This might be extended to the pointer index type, and if the gep index type |
| 974 | // has been replaced with an i8 then a new And (and different ShiftConst) will |
| 975 | // be present. |
| 976 | auto MatchInner = m_LShr( |
| 977 | L: m_Mul(L: m_c_And(L: m_Neg(V: m_Value(V&: X1)), R: m_Deferred(V: X1)), R: m_APInt(Res&: MulConst)), |
| 978 | R: m_APInt(Res&: ShiftConst)); |
| 979 | if (!match(V: GepIdx, P: m_CastOrSelf(Op: MatchInner)) && |
| 980 | !match(V: GepIdx, P: m_CastOrSelf(Op: m_And(L: MatchInner, R: m_APInt(Res&: AndCst))))) |
| 981 | return false; |
| 982 | |
| 983 | unsigned InputBits = X1->getType()->getScalarSizeInBits(); |
| 984 | if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128) |
| 985 | return false; |
| 986 | |
| 987 | if (!GEPScale.isIntN(N: InputBits) || |
| 988 | !isCTTZTable(Table: GVTable->getInitializer(), Mul: *MulConst, Shift: *ShiftConst, |
| 989 | AndMask: AndCst ? *AndCst : APInt::getAllOnes(numBits: InputBits), AccessTy: AccessType, |
| 990 | InputBits, GEPIdxFactor: GEPScale.zextOrTrunc(width: InputBits), DL)) |
| 991 | return false; |
| 992 | |
| 993 | ConstantInt *ZeroTableElem = cast<ConstantInt>( |
| 994 | Val: ConstantFoldLoadFromConst(C: GVTable->getInitializer(), Ty: AccessType, DL)); |
| 995 | bool DefinedForZero = ZeroTableElem->equalsInt(V: InputBits); |
| 996 | |
| 997 | IRBuilder<> B(LI); |
| 998 | ConstantInt *BoolConst = B.getInt1(V: !DefinedForZero); |
| 999 | Type *XType = X1->getType(); |
| 1000 | auto Cttz = B.CreateIntrinsic(ID: Intrinsic::cttz, OverloadTypes: {XType}, Args: {X1, BoolConst}); |
| 1001 | Value *Res = B.CreateZExtOrTrunc(V: Cttz, DestTy: AccessType); |
| 1002 | |
| 1003 | if (!DefinedForZero) { |
| 1004 | // If the value in elem 0 isn't the same as InputBits, we still want to |
| 1005 | // produce the value from the table. Emit the select in AccessType with elem |
| 1006 | // 0 unchanged, as the table's element type may be wider than the input |
| 1007 | // type (and directly truncating ZeroTableElem into the input type could |
| 1008 | // incorrectly drop bits). |
| 1009 | auto Cmp = B.CreateICmpEQ(LHS: X1, RHS: ConstantInt::get(Ty: XType, V: 0)); |
| 1010 | Res = B.CreateSelect(C: Cmp, True: ZeroTableElem, False: Res); |
| 1011 | |
| 1012 | // The true branch of select handles the cttz(0) case, which is rare. |
| 1013 | if (Instruction *SelectI = dyn_cast<Instruction>(Val: Res)) |
| 1014 | SelectI->setMetadata( |
| 1015 | KindID: LLVMContext::MD_prof, |
| 1016 | Node: MDBuilder(SelectI->getContext()).createUnlikelyBranchWeights()); |
| 1017 | |
| 1018 | // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target |
| 1019 | // it should be handled as: `cttz(x) & (typeSize - 1)`. |
| 1020 | } |
| 1021 | |
| 1022 | LI->replaceAllUsesWith(V: Res); |
| 1023 | |
| 1024 | return true; |
| 1025 | } |
| 1026 | |
| 1027 | // Check if this array of constants represents a log2 table. |
| 1028 | // Iterate over the elements from \p Table by trying to find/match all |
| 1029 | // the numbers from 0 to \p InputBits that should represent log2 results. |
| 1030 | static bool isLog2Table(Constant *Table, const APInt &Mul, const APInt &Shift, |
| 1031 | Type *AccessTy, unsigned InputBits, |
| 1032 | const APInt &GEPIdxFactor, const DataLayout &DL) { |
| 1033 | for (unsigned Idx = 0; Idx < InputBits; Idx++) { |
| 1034 | APInt Index = (APInt::getLowBitsSet(numBits: InputBits, loBitsSet: Idx + 1) * Mul).lshr(ShiftAmt: Shift); |
| 1035 | ConstantInt *C = dyn_cast_or_null<ConstantInt>( |
| 1036 | Val: ConstantFoldLoadFromConst(C: Table, Ty: AccessTy, Offset: Index * GEPIdxFactor, DL)); |
| 1037 | if (!C || C->getValue() != Idx) |
| 1038 | return false; |
| 1039 | } |
| 1040 | |
| 1041 | // Verify that an input of zero will select table index 0. |
| 1042 | APInt ZeroIndex = Mul.lshr(ShiftAmt: Shift); |
| 1043 | if (!ZeroIndex.isZero()) |
| 1044 | return false; |
| 1045 | |
| 1046 | return true; |
| 1047 | } |
| 1048 | |
| 1049 | // Try to recognize table-based log2 implementation. |
| 1050 | // E.g., an example in C (for more cases please the llvm/tests): |
| 1051 | // int f(unsigned v) { |
| 1052 | // static const char table[32] = |
| 1053 | // {0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, |
| 1054 | // 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31}; |
| 1055 | // |
| 1056 | // v |= v >> 1; // first round down to one less than a power of 2 |
| 1057 | // v |= v >> 2; |
| 1058 | // v |= v >> 4; |
| 1059 | // v |= v >> 8; |
| 1060 | // v |= v >> 16; |
| 1061 | // |
| 1062 | // return table[(unsigned)(v * 0x07C4ACDDU) >> 27]; |
| 1063 | // } |
| 1064 | // this can be lowered to `ctlz` instruction. |
| 1065 | // There is also a special case when the element is 0. |
| 1066 | // |
| 1067 | // The >> and |= sequence sets all bits below the most significant set bit. The |
| 1068 | // multiply is a de-bruijn sequence that contains each pattern of bits in it. |
| 1069 | // The shift extracts the top bits after the multiply, and that index into the |
| 1070 | // table should represent the floor log base 2 of the original number. |
| 1071 | // |
| 1072 | // Here are some examples of LLVM IR for a 64-bit target. |
| 1073 | // |
| 1074 | // CASE 1: |
| 1075 | // %shr = lshr i32 %v, 1 |
| 1076 | // %or = or i32 %shr, %v |
| 1077 | // %shr1 = lshr i32 %or, 2 |
| 1078 | // %or2 = or i32 %shr1, %or |
| 1079 | // %shr3 = lshr i32 %or2, 4 |
| 1080 | // %or4 = or i32 %shr3, %or2 |
| 1081 | // %shr5 = lshr i32 %or4, 8 |
| 1082 | // %or6 = or i32 %shr5, %or4 |
| 1083 | // %shr7 = lshr i32 %or6, 16 |
| 1084 | // %or8 = or i32 %shr7, %or6 |
| 1085 | // %mul = mul i32 %or8, 130329821 |
| 1086 | // %shr9 = lshr i32 %mul, 27 |
| 1087 | // %idxprom = zext nneg i32 %shr9 to i64 |
| 1088 | // %arrayidx = getelementptr inbounds i8, ptr @table, i64 %idxprom |
| 1089 | // %0 = load i8, ptr %arrayidx, align 1 |
| 1090 | // |
| 1091 | // CASE 2: |
| 1092 | // %shr = lshr i64 %v, 1 |
| 1093 | // %or = or i64 %shr, %v |
| 1094 | // %shr1 = lshr i64 %or, 2 |
| 1095 | // %or2 = or i64 %shr1, %or |
| 1096 | // %shr3 = lshr i64 %or2, 4 |
| 1097 | // %or4 = or i64 %shr3, %or2 |
| 1098 | // %shr5 = lshr i64 %or4, 8 |
| 1099 | // %or6 = or i64 %shr5, %or4 |
| 1100 | // %shr7 = lshr i64 %or6, 16 |
| 1101 | // %or8 = or i64 %shr7, %or6 |
| 1102 | // %shr9 = lshr i64 %or8, 32 |
| 1103 | // %or10 = or i64 %shr9, %or8 |
| 1104 | // %mul = mul i64 %or10, 285870213051386505 |
| 1105 | // %shr11 = lshr i64 %mul, 58 |
| 1106 | // %arrayidx = getelementptr inbounds i8, ptr @table, i64 %shr11 |
| 1107 | // %0 = load i8, ptr %arrayidx, align 1 |
| 1108 | // |
| 1109 | // CASE 3: |
| 1110 | // A variant where the most-significant set bit of the OR-cascade result is |
| 1111 | // isolated via subtraction before the multiply, i.e. |
| 1112 | // table[((v - (v >> 1)) * MulConst) >> ShiftConst], analogous to how the |
| 1113 | // cttz pattern isolates the least-significant set bit via `x & -x`: |
| 1114 | // |
| 1115 | // %shr = lshr i64 %v, 1 |
| 1116 | // %or = or i64 %shr, %v |
| 1117 | // ... (rest of the OR-cascade, as above) ... |
| 1118 | // %shr11 = lshr i64 %or10, 1 |
| 1119 | // %sub = sub i64 %or10, %shr11 |
| 1120 | // %mul = mul i64 %sub, 571347909858961602 |
| 1121 | // %shr12 = lshr i64 %mul, 58 |
| 1122 | // %arrayidx = getelementptr inbounds i8, ptr @table, i64 %shr12 |
| 1123 | // %0 = load i8, ptr %arrayidx, align 1 |
| 1124 | // |
| 1125 | // All these can be lowered to @llvm.ctlz.i32/64 intrinsics and a subtract. |
| 1126 | // |
| 1127 | // This shares its initial match (load from a GEP into a constant table with |
| 1128 | // a single variable index) with tryToRecognizeTableBasedCttz() above; see |
| 1129 | // tryToRecognizeTableBasedPatterns(). |
| 1130 | static bool tryToRecognizeTableBasedLog2(LoadInst *LI, Type *AccessType, |
| 1131 | GlobalVariable *GVTable, Value *GepIdx, |
| 1132 | const APInt &GEPScale, |
| 1133 | const DataLayout &DL, |
| 1134 | TargetTransformInfo &TTI) { |
| 1135 | Value *X; |
| 1136 | const APInt *MulConst, *ShiftConst; |
| 1137 | // Check that the gep variable index is (x * MulConst) >> ShiftConst. |
| 1138 | auto MatchInner = |
| 1139 | m_LShr(L: m_Mul(L: m_Value(V&: X), R: m_APInt(Res&: MulConst)), R: m_APInt(Res&: ShiftConst)); |
| 1140 | if (!match(V: GepIdx, P: m_CastOrSelf(Op: MatchInner))) |
| 1141 | return false; |
| 1142 | |
| 1143 | // The multiplied value may instead be the OR-cascade result with its |
| 1144 | // most-significant set bit isolated first via `v - (v >> 1)`: since every |
| 1145 | // bit below the MSB of an OR-cascade result is 1, this subtraction leaves |
| 1146 | // just the MSB, mirroring how tryToRecognizeTableBasedCttz() isolates the |
| 1147 | // least-significant set bit via `x & -x`. |
| 1148 | bool IsolatedMSB = false; |
| 1149 | Value *V; |
| 1150 | if (match(V: X, P: m_Sub(L: m_Value(V), R: m_LShr(L: m_Deferred(V), R: m_SpecificInt(V: 1))))) { |
| 1151 | IsolatedMSB = true; |
| 1152 | X = V; |
| 1153 | } |
| 1154 | |
| 1155 | unsigned InputBits = X->getType()->getScalarSizeInBits(); |
| 1156 | if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128) |
| 1157 | return false; |
| 1158 | |
| 1159 | // Verify shift amount. |
| 1160 | // TODO: Allow other shift amounts when we have proper test coverage. |
| 1161 | if (*ShiftConst != InputBits - Log2_32(Value: InputBits)) |
| 1162 | return false; |
| 1163 | |
| 1164 | // Match the sequence of OR operations with right shifts by powers of 2. |
| 1165 | for (unsigned ShiftAmt = InputBits / 2; ShiftAmt != 0; ShiftAmt /= 2) { |
| 1166 | Value *Y; |
| 1167 | if (!match(V: X, P: m_c_Or(L: m_LShr(L: m_Value(V&: Y), R: m_SpecificInt(V: ShiftAmt)), |
| 1168 | R: m_Deferred(V: Y)))) |
| 1169 | return false; |
| 1170 | X = Y; |
| 1171 | } |
| 1172 | |
| 1173 | if (!GEPScale.isIntN(N: InputBits)) |
| 1174 | return false; |
| 1175 | |
| 1176 | if (IsolatedMSB) { |
| 1177 | // With the MSB isolated, the multiplicand for an input whose MSB is at bit |
| 1178 | // Idx is a single set bit rather than a run of low bits, which is exactly |
| 1179 | // what isCTTZTable() checks for (there is no additional masking here, so |
| 1180 | // pass an all-ones mask). |
| 1181 | if (!isCTTZTable(Table: GVTable->getInitializer(), Mul: *MulConst, Shift: *ShiftConst, |
| 1182 | AndMask: APInt::getAllOnes(numBits: InputBits), AccessTy: AccessType, InputBits, |
| 1183 | GEPIdxFactor: GEPScale.zextOrTrunc(width: InputBits), DL)) |
| 1184 | return false; |
| 1185 | } else { |
| 1186 | if (!isLog2Table(Table: GVTable->getInitializer(), Mul: *MulConst, Shift: *ShiftConst, |
| 1187 | AccessTy: AccessType, InputBits, GEPIdxFactor: GEPScale.zextOrTrunc(width: InputBits), |
| 1188 | DL)) |
| 1189 | return false; |
| 1190 | } |
| 1191 | |
| 1192 | ConstantInt *ZeroTableElem = cast<ConstantInt>( |
| 1193 | Val: ConstantFoldLoadFromConst(C: GVTable->getInitializer(), Ty: AccessType, DL)); |
| 1194 | |
| 1195 | // Use InputBits - 1 - ctlz(X) to compute log2(X). |
| 1196 | IRBuilder<> B(LI); |
| 1197 | ConstantInt *BoolConst = B.getTrue(); |
| 1198 | Type *XType = X->getType(); |
| 1199 | |
| 1200 | // Check the the backend has an efficient ctlz instruction. |
| 1201 | // FIXME: Teach the backend to emit the original code when ctlz isn't |
| 1202 | // supported like we do for cttz. |
| 1203 | IntrinsicCostAttributes Attrs( |
| 1204 | Intrinsic::ctlz, XType, |
| 1205 | {PoisonValue::get(T: XType), /*is_zero_poison=*/BoolConst}); |
| 1206 | InstructionCost Cost = |
| 1207 | TTI.getIntrinsicInstrCost(ICA: Attrs, CostKind: TargetTransformInfo::TCK_SizeAndLatency); |
| 1208 | if (Cost > TargetTransformInfo::TCC_Basic) |
| 1209 | return false; |
| 1210 | |
| 1211 | Constant *InputBitsM1 = ConstantInt::get(Ty: XType, V: InputBits - 1); |
| 1212 | |
| 1213 | Value *Result; |
| 1214 | if (ZeroTableElem->getZExtValue() == InputBits - 1) { |
| 1215 | Value *Ctlz = |
| 1216 | B.CreateIntrinsic(ID: Intrinsic::ctlz, OverloadTypes: {XType}, Args: {X, B.getFalse()}); |
| 1217 | Result = B.CreateAnd(LHS: B.CreateNot(V: Ctlz), RHS: InputBitsM1); |
| 1218 | } else { |
| 1219 | Value *Ctlz = B.CreateIntrinsic(ID: Intrinsic::ctlz, OverloadTypes: {XType}, Args: {X, BoolConst}); |
| 1220 | Value *Sub = B.CreateSub(LHS: InputBitsM1, RHS: Ctlz); |
| 1221 | |
| 1222 | // The table won't produce a sensible result for 0. |
| 1223 | Value *Cmp = B.CreateICmpEQ(LHS: X, RHS: ConstantInt::get(Ty: XType, V: 0)); |
| 1224 | Value *Select = |
| 1225 | B.CreateSelect(C: Cmp, True: B.CreateZExt(V: ZeroTableElem, DestTy: XType), False: Sub); |
| 1226 | |
| 1227 | // The true branch of select handles the log2(0) case, which is rare. |
| 1228 | if (Instruction *SelectI = dyn_cast<Instruction>(Val: Select)) |
| 1229 | SelectI->setMetadata( |
| 1230 | KindID: LLVMContext::MD_prof, |
| 1231 | Node: MDBuilder(SelectI->getContext()).createUnlikelyBranchWeights()); |
| 1232 | |
| 1233 | Result = Select; |
| 1234 | } |
| 1235 | |
| 1236 | Value *ZExtOrTrunc = B.CreateZExtOrTrunc(V: Result, DestTy: AccessType); |
| 1237 | |
| 1238 | LI->replaceAllUsesWith(V: ZExtOrTrunc); |
| 1239 | |
| 1240 | return true; |
| 1241 | } |
| 1242 | |
| 1243 | // Recognize a load from a "low bits mask" table, tbl[j] == (1 << j) - 1: |
| 1244 | // |
| 1245 | // static const uintN_t tbl[K] = { 0, 1, 3, 7, ... }; |
| 1246 | // ... x & tbl[i] ... |
| 1247 | // |
| 1248 | // The loaded value equals the arithmetic mask (1 << i) - 1, so replace the load |
| 1249 | // with that expression and drop the table. On X86+BMI2 a surrounding `and` then |
| 1250 | // selects to a single `bzhi`; on other targets it is a shift and a decrement. |
| 1251 | // |
| 1252 | // Shares the load/GEP/offset match with the cttz and log2 recognizers above; |
| 1253 | // see tryToRecognizeTableBasedPatterns(). |
| 1254 | static bool tryToRecognizeTableBasedLowBitsMask(LoadInst *LI, Type *AccessType, |
| 1255 | GlobalVariable *GVTable, |
| 1256 | Value *GepIdx, |
| 1257 | const APInt &GEPScale, |
| 1258 | const DataLayout &DL) { |
| 1259 | // The value must be exactly the table element; refuse volatile/atomic loads. |
| 1260 | if (!LI->isSimple()) |
| 1261 | return false; |
| 1262 | |
| 1263 | // The table must be [K x AccessType] of integers; a narrower load would read |
| 1264 | // only part of an element. |
| 1265 | auto *ArrTy = dyn_cast<ArrayType>(Val: GVTable->getValueType()); |
| 1266 | if (!ArrTy || ArrTy->getElementType() != AccessType || |
| 1267 | !AccessType->isIntegerTy()) |
| 1268 | return false; |
| 1269 | |
| 1270 | unsigned EltBits = AccessType->getIntegerBitWidth(); |
| 1271 | uint64_t EltBytes = DL.getTypeAllocSize(Ty: AccessType).getFixedValue(); |
| 1272 | uint64_t K = ArrTy->getNumElements(); |
| 1273 | |
| 1274 | // Only fire when the element type fits in a legal integer, so the emitted |
| 1275 | // shift is a cheap (possibly promoted) instruction rather than a runtime |
| 1276 | // libcall (e.g. __ashlti3 for i128) -- which would be worse than the load |
| 1277 | // and is unavailable in freestanding environments that do not link a |
| 1278 | // runtime library. |
| 1279 | if (!DL.fitsInLegalInteger(Width: EltBits)) |
| 1280 | return false; |
| 1281 | |
| 1282 | // The rewrite is only valid for indices inside the table. The nusw the |
| 1283 | // shared matcher requires keeps the address computation from wrapping but |
| 1284 | // does not keep it inside the object: a nusw-only GEP with i >= K is a |
| 1285 | // well-defined pointer past the table, and a load through it (into |
| 1286 | // whatever follows) is not (1 << i) - 1. With inbounds such a GEP is poison |
| 1287 | // and the load is UB, so every executed load has 0 <= i < K. |
| 1288 | auto *GEP = cast<GetElementPtrInst>(Val: LI->getPointerOperand()); |
| 1289 | if (!GEP->isInBounds()) |
| 1290 | return false; |
| 1291 | |
| 1292 | // K <= EltBits then guarantees i < EltBits, so the emitted `1 << i` never |
| 1293 | // shifts by >= bitwidth (no poison). A table with EltBits + 1 entries (whose |
| 1294 | // last element is the all-ones mask, needing a shift by EltBits) is |
| 1295 | // therefore rejected. |
| 1296 | if (K == 0 || K > EltBits) |
| 1297 | return false; |
| 1298 | |
| 1299 | // The index must step by exactly one element, so the runtime index value is |
| 1300 | // the shift amount; a different scale would load tbl[c * i]. |
| 1301 | if (GEPScale != EltBytes) |
| 1302 | return false; |
| 1303 | |
| 1304 | // Every element must be the low-bits mask for its position. |
| 1305 | for (uint64_t J = 0; J < K; ++J) { |
| 1306 | Constant *Elt = ConstantFoldLoadFromConst( |
| 1307 | C: GVTable->getInitializer(), Ty: AccessType, |
| 1308 | Offset: APInt(GEPScale.getBitWidth(), J) * GEPScale, DL); |
| 1309 | auto *CI = dyn_cast_or_null<ConstantInt>(Val: Elt); |
| 1310 | if (!CI || CI->getValue() != APInt::getLowBitsSet(numBits: EltBits, loBitsSet: J)) |
| 1311 | return false; |
| 1312 | } |
| 1313 | |
| 1314 | // Emit (1 << i) - 1 in the element type and replace the load. A later |
| 1315 | // InstCombine canonicalizes this to ~(-1 << i); X86 lowers both to bzhi. |
| 1316 | IRBuilder<> Builder(LI); |
| 1317 | Value *Idx = Builder.CreateZExtOrTrunc(V: GepIdx, DestTy: AccessType); |
| 1318 | Value *Mask = |
| 1319 | Builder.CreateSub(LHS: Builder.CreateShl(LHS: ConstantInt::get(Ty: AccessType, V: 1), RHS: Idx), |
| 1320 | RHS: ConstantInt::get(Ty: AccessType, V: 1)); |
| 1321 | LI->replaceAllUsesWith(V: Mask); |
| 1322 | ++NumTableBasedLowBitsMask; |
| 1323 | return true; |
| 1324 | } |
| 1325 | |
| 1326 | // Match a table-based cttz, log2, or low-bits-mask implementation. These |
| 1327 | // patterns share a load from a global table that we match first; then we |
| 1328 | // try the specific matches. |
| 1329 | static bool tryToRecognizeTableBasedPatterns(Instruction &I, |
| 1330 | const DataLayout &DL, |
| 1331 | TargetTransformInfo &TTI) { |
| 1332 | LoadInst *LI = dyn_cast<LoadInst>(Val: &I); |
| 1333 | if (!LI) |
| 1334 | return false; |
| 1335 | |
| 1336 | Type *AccessType = LI->getType(); |
| 1337 | if (!AccessType->isIntegerTy()) |
| 1338 | return false; |
| 1339 | |
| 1340 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: LI->getPointerOperand()); |
| 1341 | if (!GEP || !GEP->hasNoUnsignedSignedWrap()) |
| 1342 | return false; |
| 1343 | |
| 1344 | GlobalVariable *GVTable = dyn_cast<GlobalVariable>(Val: GEP->getPointerOperand()); |
| 1345 | if (!GVTable || !GVTable->isConstant() || |
| 1346 | !GVTable->hasDefinitiveInitializer()) |
| 1347 | return false; |
| 1348 | |
| 1349 | unsigned BW = DL.getIndexTypeSizeInBits(Ty: GEP->getType()); |
| 1350 | APInt ModOffset(BW, 0); |
| 1351 | SmallMapVector<Value *, APInt, 4> VarOffsets; |
| 1352 | if (!GEP->collectOffset(DL, BitWidth: BW, VariableOffsets&: VarOffsets, ConstantOffset&: ModOffset) || |
| 1353 | VarOffsets.size() != 1 || ModOffset != 0) |
| 1354 | return false; |
| 1355 | auto [GepIdx, GEPScale] = VarOffsets.front(); |
| 1356 | |
| 1357 | if (tryToRecognizeTableBasedCttz(LI, AccessType, GVTable, GepIdx, GEPScale, |
| 1358 | DL)) |
| 1359 | return true; |
| 1360 | |
| 1361 | if (tryToRecognizeTableBasedLog2(LI, AccessType, GVTable, GepIdx, GEPScale, |
| 1362 | DL, TTI)) |
| 1363 | return true; |
| 1364 | |
| 1365 | return tryToRecognizeTableBasedLowBitsMask(LI, AccessType, GVTable, GepIdx, |
| 1366 | GEPScale, DL); |
| 1367 | } |
| 1368 | |
| 1369 | /// This is used by foldLoadsRecursive() to capture a Root Load node which is |
| 1370 | /// of type or(load, load) and recursively build the wide load. Also capture the |
| 1371 | /// shift amount, zero extend type and loadSize. |
| 1372 | struct LoadOps { |
| 1373 | LoadInst *Root = nullptr; |
| 1374 | LoadInst *RootInsert = nullptr; |
| 1375 | bool FoundRoot = false; |
| 1376 | uint64_t LoadSize = 0; |
| 1377 | uint64_t Shift = 0; |
| 1378 | Type *ZextType; |
| 1379 | AAMDNodes AATags; |
| 1380 | }; |
| 1381 | |
| 1382 | // Identify and Merge consecutive loads recursively which is of the form |
| 1383 | // (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1 |
| 1384 | // (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3) |
| 1385 | static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL, |
| 1386 | AliasAnalysis &AA, bool IsRoot = false) { |
| 1387 | uint64_t ShAmt2; |
| 1388 | Value *X; |
| 1389 | Instruction *L1, *L2; |
| 1390 | |
| 1391 | // For the root instruction, allow multiple uses since the final result |
| 1392 | // may legitimately be used in multiple places. For intermediate values, |
| 1393 | // require single use to avoid creating duplicate loads. |
| 1394 | if (!IsRoot && !V->hasOneUse()) |
| 1395 | return false; |
| 1396 | |
| 1397 | if (!match(V, P: m_c_Or(L: m_Value(V&: X), |
| 1398 | R: m_OneUse(SubPattern: m_ShlOrSelf(L: m_OneUse(SubPattern: m_ZExt(Op: m_Instruction(I&: L2))), |
| 1399 | R&: ShAmt2))))) |
| 1400 | return false; |
| 1401 | |
| 1402 | if (!foldLoadsRecursive(V: X, LOps, DL, AA, /*IsRoot=*/false) && LOps.FoundRoot) |
| 1403 | // Avoid Partial chain merge. |
| 1404 | return false; |
| 1405 | |
| 1406 | // Check if the pattern has loads |
| 1407 | LoadInst *LI1 = LOps.Root; |
| 1408 | uint64_t ShAmt1 = LOps.Shift; |
| 1409 | if (LOps.FoundRoot == false && |
| 1410 | match(V: X, P: m_OneUse( |
| 1411 | SubPattern: m_ShlOrSelf(L: m_OneUse(SubPattern: m_ZExt(Op: m_Instruction(I&: L1))), R&: ShAmt1)))) { |
| 1412 | LI1 = dyn_cast<LoadInst>(Val: L1); |
| 1413 | } |
| 1414 | LoadInst *LI2 = dyn_cast<LoadInst>(Val: L2); |
| 1415 | |
| 1416 | // Check if loads are same, atomic, volatile and having same address space. |
| 1417 | if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() || |
| 1418 | LI1->getPointerAddressSpace() != LI2->getPointerAddressSpace()) |
| 1419 | return false; |
| 1420 | |
| 1421 | // Check if Loads come from same BB. |
| 1422 | if (LI1->getParent() != LI2->getParent()) |
| 1423 | return false; |
| 1424 | |
| 1425 | // Find the data layout |
| 1426 | bool IsBigEndian = DL.isBigEndian(); |
| 1427 | |
| 1428 | // Check if loads are consecutive and same size. |
| 1429 | Value *Load1Ptr = LI1->getPointerOperand(); |
| 1430 | APInt Offset1(DL.getIndexTypeSizeInBits(Ty: Load1Ptr->getType()), 0); |
| 1431 | Load1Ptr = |
| 1432 | Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset&: Offset1, |
| 1433 | /* AllowNonInbounds */ true); |
| 1434 | |
| 1435 | Value *Load2Ptr = LI2->getPointerOperand(); |
| 1436 | APInt Offset2(DL.getIndexTypeSizeInBits(Ty: Load2Ptr->getType()), 0); |
| 1437 | Load2Ptr = |
| 1438 | Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset&: Offset2, |
| 1439 | /* AllowNonInbounds */ true); |
| 1440 | |
| 1441 | // Verify if both loads have same base pointers |
| 1442 | uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits(); |
| 1443 | uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits(); |
| 1444 | if (Load1Ptr != Load2Ptr) |
| 1445 | return false; |
| 1446 | |
| 1447 | // Make sure that there are no padding bits. |
| 1448 | if (!DL.typeSizeEqualsStoreSize(Ty: LI1->getType()) || |
| 1449 | !DL.typeSizeEqualsStoreSize(Ty: LI2->getType())) |
| 1450 | return false; |
| 1451 | |
| 1452 | // Alias Analysis to check for stores b/w the loads. |
| 1453 | LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2; |
| 1454 | MemoryLocation Loc; |
| 1455 | if (!Start->comesBefore(Other: End)) { |
| 1456 | std::swap(a&: Start, b&: End); |
| 1457 | // If LOps.RootInsert comes after LI2, since we use LI2 as the new insert |
| 1458 | // point, we should make sure whether the memory region accessed by LOps |
| 1459 | // isn't modified. |
| 1460 | if (LOps.FoundRoot) |
| 1461 | Loc = MemoryLocation( |
| 1462 | LOps.Root->getPointerOperand(), |
| 1463 | LocationSize::precise(Value: DL.getTypeStoreSize( |
| 1464 | Ty: IntegerType::get(C&: LI1->getContext(), NumBits: LOps.LoadSize))), |
| 1465 | LOps.AATags); |
| 1466 | else |
| 1467 | Loc = MemoryLocation::get(LI: End); |
| 1468 | } else |
| 1469 | Loc = MemoryLocation::get(LI: End); |
| 1470 | unsigned NumScanned = 0; |
| 1471 | for (Instruction &Inst : |
| 1472 | make_range(x: Start->getIterator(), y: End->getIterator())) { |
| 1473 | if (Inst.mayWriteToMemory() && isModSet(MRI: AA.getModRefInfo(I: &Inst, OptLoc: Loc))) |
| 1474 | return false; |
| 1475 | |
| 1476 | if (++NumScanned > MaxInstrsToScan) |
| 1477 | return false; |
| 1478 | } |
| 1479 | |
| 1480 | // Make sure Load with lower Offset is at LI1 |
| 1481 | bool Reverse = false; |
| 1482 | if (Offset2.slt(RHS: Offset1)) { |
| 1483 | std::swap(a&: LI1, b&: LI2); |
| 1484 | std::swap(a&: ShAmt1, b&: ShAmt2); |
| 1485 | std::swap(a&: Offset1, b&: Offset2); |
| 1486 | std::swap(a&: Load1Ptr, b&: Load2Ptr); |
| 1487 | std::swap(a&: LoadSize1, b&: LoadSize2); |
| 1488 | Reverse = true; |
| 1489 | } |
| 1490 | |
| 1491 | // Big endian swap the shifts |
| 1492 | if (IsBigEndian) |
| 1493 | std::swap(a&: ShAmt1, b&: ShAmt2); |
| 1494 | |
| 1495 | // First load is always LI1. This is where we put the new load. |
| 1496 | // Use the merged load size available from LI1 for forward loads. |
| 1497 | if (LOps.FoundRoot) { |
| 1498 | if (!Reverse) |
| 1499 | LoadSize1 = LOps.LoadSize; |
| 1500 | else |
| 1501 | LoadSize2 = LOps.LoadSize; |
| 1502 | } |
| 1503 | |
| 1504 | // Verify if shift amount and load index aligns and verifies that loads |
| 1505 | // are consecutive. |
| 1506 | uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1; |
| 1507 | uint64_t PrevSize = |
| 1508 | DL.getTypeStoreSize(Ty: IntegerType::get(C&: LI1->getContext(), NumBits: LoadSize1)); |
| 1509 | if ((ShAmt2 - ShAmt1) != ShiftDiff || (Offset2 - Offset1) != PrevSize) |
| 1510 | return false; |
| 1511 | |
| 1512 | // Reject if the combined size of the loads exceeds the target type size. |
| 1513 | // This avoids attempting to emit an invalid ZExt (from wider to narrower |
| 1514 | // type) when out-of-bounds shifts lead to matching too many loads. |
| 1515 | if (LoadSize1 + LoadSize2 > X->getType()->getScalarSizeInBits()) |
| 1516 | return false; |
| 1517 | |
| 1518 | // Update LOps |
| 1519 | AAMDNodes AATags1 = LOps.AATags; |
| 1520 | AAMDNodes AATags2 = LI2->getAAMetadata(); |
| 1521 | if (LOps.FoundRoot == false) { |
| 1522 | LOps.FoundRoot = true; |
| 1523 | AATags1 = LI1->getAAMetadata(); |
| 1524 | } |
| 1525 | LOps.LoadSize = LoadSize1 + LoadSize2; |
| 1526 | LOps.RootInsert = Start; |
| 1527 | |
| 1528 | // Concatenate the AATags of the Merged Loads. |
| 1529 | LOps.AATags = AATags1.concat(Other: AATags2); |
| 1530 | |
| 1531 | LOps.Root = LI1; |
| 1532 | LOps.Shift = ShAmt1; |
| 1533 | LOps.ZextType = X->getType(); |
| 1534 | return true; |
| 1535 | } |
| 1536 | |
| 1537 | // For a given BB instruction, evaluate all loads in the chain that form a |
| 1538 | // pattern which suggests that the loads can be combined. The one and only use |
| 1539 | // of the loads is to form a wider load. |
| 1540 | static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL, |
| 1541 | TargetTransformInfo &TTI, AliasAnalysis &AA, |
| 1542 | const DominatorTree &DT) { |
| 1543 | // Only consider load chains of scalar values. |
| 1544 | if (isa<VectorType>(Val: I.getType())) |
| 1545 | return false; |
| 1546 | |
| 1547 | LoadOps LOps; |
| 1548 | if (!foldLoadsRecursive(V: &I, LOps, DL, AA, /*IsRoot=*/true) || !LOps.FoundRoot) |
| 1549 | return false; |
| 1550 | |
| 1551 | IRBuilder<> Builder(&I); |
| 1552 | LoadInst *NewLoad = nullptr, *LI1 = LOps.Root; |
| 1553 | |
| 1554 | // Allow a power of 2 number of bytes that fit in a legal integer type. |
| 1555 | bool Allowed = LOps.LoadSize >= 16 && isPowerOf2_64(Value: LOps.LoadSize) && |
| 1556 | DL.fitsInLegalInteger(Width: LOps.LoadSize); |
| 1557 | if (!Allowed) |
| 1558 | return false; |
| 1559 | |
| 1560 | unsigned AS = LI1->getPointerAddressSpace(); |
| 1561 | unsigned Fast = 0; |
| 1562 | Allowed = TTI.allowsMisalignedMemoryAccesses(Context&: I.getContext(), BitWidth: LOps.LoadSize, |
| 1563 | AddressSpace: AS, Alignment: LI1->getAlign(), Fast: &Fast); |
| 1564 | if (!Allowed || !Fast) |
| 1565 | return false; |
| 1566 | |
| 1567 | // Get the Index and Ptr for the new GEP. |
| 1568 | Value *Load1Ptr = LI1->getPointerOperand(); |
| 1569 | Builder.SetInsertPoint(LOps.RootInsert); |
| 1570 | if (!DT.dominates(Def: Load1Ptr, User: LOps.RootInsert)) { |
| 1571 | APInt Offset1(DL.getIndexTypeSizeInBits(Ty: Load1Ptr->getType()), 0); |
| 1572 | Load1Ptr = Load1Ptr->stripAndAccumulateConstantOffsets( |
| 1573 | DL, Offset&: Offset1, /* AllowNonInbounds */ true); |
| 1574 | Load1Ptr = Builder.CreatePtrAdd(Ptr: Load1Ptr, Offset: Builder.getInt(AI: Offset1)); |
| 1575 | } |
| 1576 | // Generate wider load. |
| 1577 | IntegerType *WiderType = IntegerType::get(C&: I.getContext(), NumBits: LOps.LoadSize); |
| 1578 | NewLoad = Builder.CreateAlignedLoad(Ty: WiderType, Ptr: Load1Ptr, Align: LI1->getAlign(), |
| 1579 | isVolatile: LI1->isVolatile(), Name: "" ); |
| 1580 | NewLoad->takeName(V: LI1); |
| 1581 | // Set the New Load AATags Metadata. |
| 1582 | if (LOps.AATags) |
| 1583 | NewLoad->setAAMetadata(LOps.AATags); |
| 1584 | |
| 1585 | Value *NewOp = NewLoad; |
| 1586 | // Zero extend if needed. |
| 1587 | NewOp = Builder.CreateZExt(V: NewOp, DestTy: LOps.ZextType); |
| 1588 | |
| 1589 | // Check if shift needed. We need to shift with the amount of load1 |
| 1590 | // shift if not zero. |
| 1591 | if (LOps.Shift) |
| 1592 | NewOp = Builder.CreateShl(LHS: NewOp, RHS: LOps.Shift); |
| 1593 | I.replaceAllUsesWith(V: NewOp); |
| 1594 | |
| 1595 | return true; |
| 1596 | } |
| 1597 | |
| 1598 | /// ValWidth bits starting at ValOffset of Val stored at PtrBase+PtrOffset. |
| 1599 | struct PartStore { |
| 1600 | Value *PtrBase; |
| 1601 | APInt PtrOffset; |
| 1602 | Value *Val; |
| 1603 | uint64_t ValOffset; |
| 1604 | uint64_t ValWidth; |
| 1605 | StoreInst *Store; |
| 1606 | |
| 1607 | bool isCompatibleWith(const PartStore &Other) const { |
| 1608 | // Offset stripping looks through addrspacecasts, so an equal PtrBase does |
| 1609 | // not imply an equal address space, and thus not an equal PtrOffset width. |
| 1610 | return PtrBase == Other.PtrBase && Val == Other.Val && |
| 1611 | Store->getPointerAddressSpace() == |
| 1612 | Other.Store->getPointerAddressSpace(); |
| 1613 | } |
| 1614 | |
| 1615 | bool operator<(const PartStore &Other) const { |
| 1616 | return PtrOffset.slt(RHS: Other.PtrOffset); |
| 1617 | } |
| 1618 | }; |
| 1619 | |
| 1620 | static std::optional<PartStore> matchPartStore(Instruction &I, |
| 1621 | const DataLayout &DL) { |
| 1622 | auto *Store = dyn_cast<StoreInst>(Val: &I); |
| 1623 | if (!Store || !Store->isSimple()) |
| 1624 | return std::nullopt; |
| 1625 | |
| 1626 | Value *StoredVal = Store->getValueOperand(); |
| 1627 | Type *StoredTy = StoredVal->getType(); |
| 1628 | if (!StoredTy->isIntegerTy() || !DL.typeSizeEqualsStoreSize(Ty: StoredTy)) |
| 1629 | return std::nullopt; |
| 1630 | |
| 1631 | uint64_t ValWidth = StoredTy->getPrimitiveSizeInBits(); |
| 1632 | uint64_t ValOffset; |
| 1633 | Value *Val; |
| 1634 | if (!match(V: StoredVal, P: m_Trunc(Op: m_LShrOrSelf(L: m_Value(V&: Val), R&: ValOffset)))) |
| 1635 | return std::nullopt; |
| 1636 | |
| 1637 | Value *Ptr = Store->getPointerOperand(); |
| 1638 | APInt PtrOffset(DL.getIndexTypeSizeInBits(Ty: Ptr->getType()), 0); |
| 1639 | Value *PtrBase = Ptr->stripAndAccumulateConstantOffsets( |
| 1640 | DL, Offset&: PtrOffset, /*AllowNonInbounds=*/true); |
| 1641 | return {{.PtrBase: PtrBase, .PtrOffset: PtrOffset, .Val: Val, .ValOffset: ValOffset, .ValWidth: ValWidth, .Store: Store}}; |
| 1642 | } |
| 1643 | |
| 1644 | static bool mergeConsecutivePartStores(ArrayRef<PartStore> Parts, |
| 1645 | unsigned Width, const DataLayout &DL, |
| 1646 | TargetTransformInfo &TTI) { |
| 1647 | if (Parts.size() < 2) |
| 1648 | return false; |
| 1649 | |
| 1650 | // Check whether combining the stores is profitable. |
| 1651 | // FIXME: We could generate smaller stores if we can't produce a large one. |
| 1652 | const PartStore &First = Parts.front(); |
| 1653 | LLVMContext &Ctx = First.Store->getContext(); |
| 1654 | unsigned Fast = 0; |
| 1655 | bool Allowed = |
| 1656 | Width >= 16 && isPowerOf2_64(Value: Width) && DL.fitsInLegalInteger(Width); |
| 1657 | if (!Allowed || |
| 1658 | !TTI.allowsMisalignedMemoryAccesses(Context&: Ctx, BitWidth: Width, |
| 1659 | AddressSpace: First.Store->getPointerAddressSpace(), |
| 1660 | Alignment: First.Store->getAlign(), Fast: &Fast) || |
| 1661 | !Fast) |
| 1662 | return false; |
| 1663 | |
| 1664 | // Generate the combined store. |
| 1665 | IRBuilder<> Builder(First.Store); |
| 1666 | Type *NewTy = Type::getIntNTy(C&: Ctx, N: Width); |
| 1667 | Value *Val = First.Val; |
| 1668 | if (First.ValOffset != 0) |
| 1669 | Val = Builder.CreateLShr(LHS: Val, RHS: First.ValOffset); |
| 1670 | Val = Builder.CreateZExtOrTrunc(V: Val, DestTy: NewTy); |
| 1671 | StoreInst *Store = Builder.CreateAlignedStore( |
| 1672 | Val, Ptr: First.Store->getPointerOperand(), Align: First.Store->getAlign()); |
| 1673 | |
| 1674 | // Merge various metadata onto the new store. |
| 1675 | AAMDNodes AATags = First.Store->getAAMetadata(); |
| 1676 | SmallVector<Instruction *> Stores = {First.Store}; |
| 1677 | Stores.reserve(N: Parts.size()); |
| 1678 | SmallVector<DebugLoc> DbgLocs = {First.Store->getDebugLoc()}; |
| 1679 | DbgLocs.reserve(N: Parts.size()); |
| 1680 | for (const PartStore &Part : drop_begin(RangeOrContainer&: Parts)) { |
| 1681 | AATags = AATags.concat(Other: Part.Store->getAAMetadata()); |
| 1682 | Stores.push_back(Elt: Part.Store); |
| 1683 | DbgLocs.push_back(Elt: Part.Store->getDebugLoc()); |
| 1684 | } |
| 1685 | Store->setAAMetadata(AATags); |
| 1686 | Store->mergeDIAssignID(SourceInstructions: Stores); |
| 1687 | Store->setDebugLoc(DebugLoc::getMergedLocations(Locs: DbgLocs)); |
| 1688 | |
| 1689 | // Remove the old stores. |
| 1690 | for (const PartStore &Part : Parts) |
| 1691 | Part.Store->eraseFromParent(); |
| 1692 | |
| 1693 | return true; |
| 1694 | } |
| 1695 | |
| 1696 | static bool mergePartStores(SmallVectorImpl<PartStore> &Parts, |
| 1697 | const DataLayout &DL, TargetTransformInfo &TTI) { |
| 1698 | if (Parts.size() < 2) |
| 1699 | return false; |
| 1700 | |
| 1701 | // We now have multiple parts of the same value stored to the same pointer. |
| 1702 | // Sort the parts by pointer offset, and make sure they are consistent with |
| 1703 | // the value offsets. Also check that the value is fully covered without |
| 1704 | // overlaps. |
| 1705 | bool Changed = false; |
| 1706 | llvm::sort(C&: Parts); |
| 1707 | int64_t LastEndOffsetFromFirst = 0; |
| 1708 | const PartStore *First = &Parts[0]; |
| 1709 | for (const PartStore &Part : Parts) { |
| 1710 | APInt PtrOffsetFromFirst = Part.PtrOffset - First->PtrOffset; |
| 1711 | int64_t ValOffsetFromFirst = Part.ValOffset - First->ValOffset; |
| 1712 | if (PtrOffsetFromFirst * 8 != ValOffsetFromFirst || |
| 1713 | LastEndOffsetFromFirst != ValOffsetFromFirst) { |
| 1714 | Changed |= mergeConsecutivePartStores(Parts: ArrayRef(First, &Part), |
| 1715 | Width: LastEndOffsetFromFirst, DL, TTI); |
| 1716 | First = &Part; |
| 1717 | LastEndOffsetFromFirst = Part.ValWidth; |
| 1718 | continue; |
| 1719 | } |
| 1720 | |
| 1721 | LastEndOffsetFromFirst = ValOffsetFromFirst + Part.ValWidth; |
| 1722 | } |
| 1723 | |
| 1724 | Changed |= mergeConsecutivePartStores(Parts: ArrayRef(First, Parts.end()), |
| 1725 | Width: LastEndOffsetFromFirst, DL, TTI); |
| 1726 | return Changed; |
| 1727 | } |
| 1728 | |
| 1729 | static bool foldConsecutiveStores(BasicBlock &BB, const DataLayout &DL, |
| 1730 | TargetTransformInfo &TTI, AliasAnalysis &AA) { |
| 1731 | // FIXME: Add big endian support. |
| 1732 | if (DL.isBigEndian()) |
| 1733 | return false; |
| 1734 | |
| 1735 | BatchAAResults BatchAA(AA); |
| 1736 | SmallVector<PartStore, 8> Parts; |
| 1737 | bool MadeChange = false; |
| 1738 | for (Instruction &I : make_early_inc_range(Range&: BB)) { |
| 1739 | if (std::optional<PartStore> Part = matchPartStore(I, DL)) { |
| 1740 | if (Parts.empty() || Part->isCompatibleWith(Other: Parts[0])) { |
| 1741 | Parts.push_back(Elt: std::move(*Part)); |
| 1742 | continue; |
| 1743 | } |
| 1744 | |
| 1745 | MadeChange |= mergePartStores(Parts, DL, TTI); |
| 1746 | Parts.clear(); |
| 1747 | Parts.push_back(Elt: std::move(*Part)); |
| 1748 | continue; |
| 1749 | } |
| 1750 | |
| 1751 | if (Parts.empty()) |
| 1752 | continue; |
| 1753 | |
| 1754 | if (I.mayThrow() || |
| 1755 | (I.mayReadOrWriteMemory() && |
| 1756 | isModOrRefSet(MRI: BatchAA.getModRefInfo( |
| 1757 | I: &I, OptLoc: MemoryLocation::getBeforeOrAfter(Ptr: Parts[0].PtrBase))))) { |
| 1758 | MadeChange |= mergePartStores(Parts, DL, TTI); |
| 1759 | Parts.clear(); |
| 1760 | continue; |
| 1761 | } |
| 1762 | } |
| 1763 | |
| 1764 | MadeChange |= mergePartStores(Parts, DL, TTI); |
| 1765 | return MadeChange; |
| 1766 | } |
| 1767 | |
| 1768 | /// Combine away instructions providing they are still equivalent when compared |
| 1769 | /// against 0. i.e do they have any bits set. |
| 1770 | static Value *optimizeShiftInOrChain(Value *V, IRBuilder<> &Builder) { |
| 1771 | auto *I = dyn_cast<Instruction>(Val: V); |
| 1772 | if (!I || I->getOpcode() != Instruction::Or || !I->hasOneUse()) |
| 1773 | return nullptr; |
| 1774 | |
| 1775 | Value *A; |
| 1776 | |
| 1777 | // Look deeper into the chain of or's, combining away shl (so long as they are |
| 1778 | // nuw or nsw). |
| 1779 | Value *Op0 = I->getOperand(i: 0); |
| 1780 | if (match(V: Op0, P: m_CombineOr(Ps: m_NSWShl(L: m_Value(V&: A), R: m_Value()), |
| 1781 | Ps: m_NUWShl(L: m_Value(V&: A), R: m_Value())))) |
| 1782 | Op0 = A; |
| 1783 | else if (auto *NOp = optimizeShiftInOrChain(V: Op0, Builder)) |
| 1784 | Op0 = NOp; |
| 1785 | |
| 1786 | Value *Op1 = I->getOperand(i: 1); |
| 1787 | if (match(V: Op1, P: m_CombineOr(Ps: m_NSWShl(L: m_Value(V&: A), R: m_Value()), |
| 1788 | Ps: m_NUWShl(L: m_Value(V&: A), R: m_Value())))) |
| 1789 | Op1 = A; |
| 1790 | else if (auto *NOp = optimizeShiftInOrChain(V: Op1, Builder)) |
| 1791 | Op1 = NOp; |
| 1792 | |
| 1793 | if (Op0 != I->getOperand(i: 0) || Op1 != I->getOperand(i: 1)) |
| 1794 | return Builder.CreateOr(LHS: Op0, RHS: Op1); |
| 1795 | return nullptr; |
| 1796 | } |
| 1797 | |
| 1798 | static bool foldICmpOrChain(Instruction &I, const DataLayout &DL, |
| 1799 | TargetTransformInfo &TTI, AliasAnalysis &AA, |
| 1800 | const DominatorTree &DT) { |
| 1801 | CmpPredicate Pred; |
| 1802 | Value *Op0; |
| 1803 | if (!match(V: &I, P: m_ICmp(Pred, L: m_Value(V&: Op0), R: m_Zero())) || |
| 1804 | !ICmpInst::isEquality(P: Pred)) |
| 1805 | return false; |
| 1806 | |
| 1807 | // If the chain or or's matches a load, combine to that before attempting to |
| 1808 | // remove shifts. |
| 1809 | if (auto OpI = dyn_cast<Instruction>(Val: Op0)) |
| 1810 | if (OpI->getOpcode() == Instruction::Or) |
| 1811 | if (foldConsecutiveLoads(I&: *OpI, DL, TTI, AA, DT)) |
| 1812 | return true; |
| 1813 | |
| 1814 | IRBuilder<> Builder(&I); |
| 1815 | // icmp eq/ne or(shl(a), b), 0 -> icmp eq/ne or(a, b), 0 |
| 1816 | if (auto *Res = optimizeShiftInOrChain(V: Op0, Builder)) { |
| 1817 | I.replaceAllUsesWith(V: Builder.CreateICmp(P: Pred, LHS: Res, RHS: I.getOperand(i: 1))); |
| 1818 | return true; |
| 1819 | } |
| 1820 | |
| 1821 | return false; |
| 1822 | } |
| 1823 | |
| 1824 | // Calculate GEP Stride and accumulated const ModOffset. Return Stride and |
| 1825 | // ModOffset |
| 1826 | static std::pair<APInt, APInt> |
| 1827 | getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL) { |
| 1828 | unsigned BW = DL.getIndexTypeSizeInBits(Ty: PtrOp->getType()); |
| 1829 | std::optional<APInt> Stride; |
| 1830 | APInt ModOffset(BW, 0); |
| 1831 | // Return a minimum gep stride, greatest common divisor of consective gep |
| 1832 | // index scales(c.f. Bézout's identity). |
| 1833 | while (auto *GEP = dyn_cast<GEPOperator>(Val: PtrOp)) { |
| 1834 | SmallMapVector<Value *, APInt, 4> VarOffsets; |
| 1835 | if (!GEP->collectOffset(DL, BitWidth: BW, VariableOffsets&: VarOffsets, ConstantOffset&: ModOffset)) |
| 1836 | break; |
| 1837 | |
| 1838 | for (auto [V, Scale] : VarOffsets) { |
| 1839 | // Only keep a power of two factor for non-inbounds |
| 1840 | if (!GEP->hasNoUnsignedSignedWrap()) |
| 1841 | Scale = APInt::getOneBitSet(numBits: Scale.getBitWidth(), BitNo: Scale.countr_zero()); |
| 1842 | |
| 1843 | if (!Stride) |
| 1844 | Stride = Scale; |
| 1845 | else |
| 1846 | Stride = APIntOps::GreatestCommonDivisor(A: *Stride, B: Scale); |
| 1847 | } |
| 1848 | |
| 1849 | PtrOp = GEP->getPointerOperand(); |
| 1850 | } |
| 1851 | |
| 1852 | // Check whether pointer arrives back at Global Variable via at least one GEP. |
| 1853 | // Even if it doesn't, we can check by alignment. |
| 1854 | if (!isa<GlobalVariable>(Val: PtrOp) || !Stride) |
| 1855 | return {APInt(BW, 1), APInt(BW, 0)}; |
| 1856 | |
| 1857 | // In consideration of signed GEP indices, non-negligible offset become |
| 1858 | // remainder of division by minimum GEP stride. |
| 1859 | ModOffset = ModOffset.srem(RHS: *Stride); |
| 1860 | if (ModOffset.isNegative()) |
| 1861 | ModOffset += *Stride; |
| 1862 | |
| 1863 | return {*Stride, ModOffset}; |
| 1864 | } |
| 1865 | |
| 1866 | /// If C is a constant patterned array and all valid loaded results for given |
| 1867 | /// alignment are same to a constant, return that constant. |
| 1868 | static bool foldPatternedLoads(Instruction &I, const DataLayout &DL) { |
| 1869 | auto *LI = dyn_cast<LoadInst>(Val: &I); |
| 1870 | if (!LI || LI->isVolatile()) |
| 1871 | return false; |
| 1872 | |
| 1873 | // We can only fold the load if it is from a constant global with definitive |
| 1874 | // initializer. Skip expensive logic if this is not the case. |
| 1875 | auto *PtrOp = LI->getPointerOperand(); |
| 1876 | auto *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: PtrOp)); |
| 1877 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) |
| 1878 | return false; |
| 1879 | |
| 1880 | // Bail for large initializers in excess of 4K to avoid too many scans. |
| 1881 | Constant *C = GV->getInitializer(); |
| 1882 | uint64_t GVSize = DL.getTypeAllocSize(Ty: C->getType()); |
| 1883 | if (!GVSize || 4096 < GVSize) |
| 1884 | return false; |
| 1885 | |
| 1886 | Type *LoadTy = LI->getType(); |
| 1887 | unsigned BW = DL.getIndexTypeSizeInBits(Ty: PtrOp->getType()); |
| 1888 | auto [Stride, ConstOffset] = getStrideAndModOffsetOfGEP(PtrOp, DL); |
| 1889 | |
| 1890 | // Any possible offset could be multiple of GEP stride. And any valid |
| 1891 | // offset is multiple of load alignment, so checking only multiples of bigger |
| 1892 | // one is sufficient to say results' equality. |
| 1893 | if (auto LA = LI->getAlign(); |
| 1894 | LA <= GV->getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) { |
| 1895 | ConstOffset = APInt(BW, 0); |
| 1896 | Stride = APInt(BW, LA.value()); |
| 1897 | } |
| 1898 | |
| 1899 | Constant *Ca = ConstantFoldLoadFromConst(C, Ty: LoadTy, Offset: ConstOffset, DL); |
| 1900 | if (!Ca) |
| 1901 | return false; |
| 1902 | |
| 1903 | unsigned E = GVSize - DL.getTypeStoreSize(Ty: LoadTy); |
| 1904 | for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride) |
| 1905 | if (Ca != ConstantFoldLoadFromConst(C, Ty: LoadTy, Offset: ConstOffset, DL)) |
| 1906 | return false; |
| 1907 | |
| 1908 | I.replaceAllUsesWith(V: Ca); |
| 1909 | |
| 1910 | return true; |
| 1911 | } |
| 1912 | |
| 1913 | namespace { |
| 1914 | class StrNCmpInliner { |
| 1915 | public: |
| 1916 | StrNCmpInliner(CallInst *CI, LibFunc Func, DomTreeUpdater *DTU, |
| 1917 | const DataLayout &DL) |
| 1918 | : CI(CI), Func(Func), DTU(DTU), DL(DL) {} |
| 1919 | |
| 1920 | bool optimizeStrNCmp(); |
| 1921 | |
| 1922 | private: |
| 1923 | void inlineCompare(Value *LHS, StringRef RHS, uint64_t N, bool Swapped); |
| 1924 | |
| 1925 | CallInst *CI; |
| 1926 | LibFunc Func; |
| 1927 | DomTreeUpdater *DTU; |
| 1928 | const DataLayout &DL; |
| 1929 | }; |
| 1930 | |
| 1931 | } // namespace |
| 1932 | |
| 1933 | /// First we normalize calls to strncmp/strcmp to the form of |
| 1934 | /// compare(s1, s2, N), which means comparing first N bytes of s1 and s2 |
| 1935 | /// (without considering '\0'). |
| 1936 | /// |
| 1937 | /// Examples: |
| 1938 | /// |
| 1939 | /// \code |
| 1940 | /// strncmp(s, "a", 3) -> compare(s, "a", 2) |
| 1941 | /// strncmp(s, "abc", 3) -> compare(s, "abc", 3) |
| 1942 | /// strncmp(s, "a\0b", 3) -> compare(s, "a\0b", 2) |
| 1943 | /// strcmp(s, "a") -> compare(s, "a", 2) |
| 1944 | /// |
| 1945 | /// char s2[] = {'a'} |
| 1946 | /// strncmp(s, s2, 3) -> compare(s, s2, 3) |
| 1947 | /// |
| 1948 | /// char s2[] = {'a', 'b', 'c', 'd'} |
| 1949 | /// strncmp(s, s2, 3) -> compare(s, s2, 3) |
| 1950 | /// \endcode |
| 1951 | /// |
| 1952 | /// We only handle cases where N and exactly one of s1 and s2 are constant. |
| 1953 | /// Cases that s1 and s2 are both constant are already handled by the |
| 1954 | /// instcombine pass. |
| 1955 | /// |
| 1956 | /// We do not handle cases where N > StrNCmpInlineThreshold. |
| 1957 | /// |
| 1958 | /// We also do not handles cases where N < 2, which are already |
| 1959 | /// handled by the instcombine pass. |
| 1960 | /// |
| 1961 | bool StrNCmpInliner::optimizeStrNCmp() { |
| 1962 | if (StrNCmpInlineThreshold < 2) |
| 1963 | return false; |
| 1964 | |
| 1965 | if (!isOnlyUsedInZeroComparison(CtxI: CI)) |
| 1966 | return false; |
| 1967 | |
| 1968 | Value *Str1P = CI->getArgOperand(i: 0); |
| 1969 | Value *Str2P = CI->getArgOperand(i: 1); |
| 1970 | // Should be handled elsewhere. |
| 1971 | if (Str1P == Str2P) |
| 1972 | return false; |
| 1973 | |
| 1974 | StringRef Str1, Str2; |
| 1975 | bool HasStr1 = getConstantStringInfo(V: Str1P, Str&: Str1, /*TrimAtNul=*/false); |
| 1976 | bool HasStr2 = getConstantStringInfo(V: Str2P, Str&: Str2, /*TrimAtNul=*/false); |
| 1977 | if (HasStr1 == HasStr2) |
| 1978 | return false; |
| 1979 | |
| 1980 | // Note that '\0' and characters after it are not trimmed. |
| 1981 | StringRef Str = HasStr1 ? Str1 : Str2; |
| 1982 | Value *StrP = HasStr1 ? Str2P : Str1P; |
| 1983 | |
| 1984 | size_t Idx = Str.find(C: '\0'); |
| 1985 | uint64_t N = Idx == StringRef::npos ? UINT64_MAX : Idx + 1; |
| 1986 | if (Func == LibFunc_strncmp) { |
| 1987 | if (auto *ConstInt = dyn_cast<ConstantInt>(Val: CI->getArgOperand(i: 2))) |
| 1988 | N = std::min(a: N, b: ConstInt->getZExtValue()); |
| 1989 | else |
| 1990 | return false; |
| 1991 | } |
| 1992 | // Now N means how many bytes we need to compare at most. |
| 1993 | if (N > Str.size() || N < 2 || N > StrNCmpInlineThreshold) |
| 1994 | return false; |
| 1995 | |
| 1996 | // Cases where StrP has two or more dereferenceable bytes might be better |
| 1997 | // optimized elsewhere. |
| 1998 | bool CanBeNull = false; |
| 1999 | if (StrP->getPointerDereferenceableBytes(DL, CanBeNull, |
| 2000 | /*CanBeFreed=*/nullptr) > 1) |
| 2001 | return false; |
| 2002 | inlineCompare(LHS: StrP, RHS: Str, N, Swapped: HasStr1); |
| 2003 | return true; |
| 2004 | } |
| 2005 | |
| 2006 | /// Convert |
| 2007 | /// |
| 2008 | /// \code |
| 2009 | /// ret = compare(s1, s2, N) |
| 2010 | /// \endcode |
| 2011 | /// |
| 2012 | /// into |
| 2013 | /// |
| 2014 | /// \code |
| 2015 | /// ret = (int)s1[0] - (int)s2[0] |
| 2016 | /// if (ret != 0) |
| 2017 | /// goto NE |
| 2018 | /// ... |
| 2019 | /// ret = (int)s1[N-2] - (int)s2[N-2] |
| 2020 | /// if (ret != 0) |
| 2021 | /// goto NE |
| 2022 | /// ret = (int)s1[N-1] - (int)s2[N-1] |
| 2023 | /// NE: |
| 2024 | /// \endcode |
| 2025 | /// |
| 2026 | /// CFG before and after the transformation: |
| 2027 | /// |
| 2028 | /// (before) |
| 2029 | /// BBCI |
| 2030 | /// |
| 2031 | /// (after) |
| 2032 | /// BBCI -> BBSubs[0] (sub,icmp) --NE-> BBNE -> BBTail |
| 2033 | /// | ^ |
| 2034 | /// E | |
| 2035 | /// | | |
| 2036 | /// BBSubs[1] (sub,icmp) --NE-----+ |
| 2037 | /// ... | |
| 2038 | /// BBSubs[N-1] (sub) ---------+ |
| 2039 | /// |
| 2040 | void StrNCmpInliner::inlineCompare(Value *LHS, StringRef RHS, uint64_t N, |
| 2041 | bool Swapped) { |
| 2042 | auto &Ctx = CI->getContext(); |
| 2043 | IRBuilder<> B(*CI->getModule()); |
| 2044 | // We want these instructions to be recognized as inlined instructions for the |
| 2045 | // compare call, but we don't have a source location for the definition of |
| 2046 | // that function, since we're generating that code now. Because the generated |
| 2047 | // code is a viable point for a memory access error, we make the pragmatic |
| 2048 | // choice here to directly use CI's location so that we have useful |
| 2049 | // attribution for the generated code. |
| 2050 | B.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 2051 | |
| 2052 | BasicBlock *BBCI = CI->getParent(); |
| 2053 | BasicBlock *BBTail = |
| 2054 | SplitBlock(Old: BBCI, SplitPt: CI, DTU, LI: nullptr, MSSAU: nullptr, BBName: BBCI->getName() + ".tail" ); |
| 2055 | |
| 2056 | SmallVector<BasicBlock *> BBSubs; |
| 2057 | for (uint64_t I = 0; I < N; ++I) |
| 2058 | BBSubs.push_back( |
| 2059 | Elt: BasicBlock::Create(Context&: Ctx, Name: "sub_" + Twine(I), Parent: BBCI->getParent(), InsertBefore: BBTail)); |
| 2060 | BasicBlock *BBNE = BasicBlock::Create(Context&: Ctx, Name: "ne" , Parent: BBCI->getParent(), InsertBefore: BBTail); |
| 2061 | |
| 2062 | cast<UncondBrInst>(Val: BBCI->getTerminator())->setSuccessor(BBSubs[0]); |
| 2063 | |
| 2064 | B.SetInsertPoint(BBNE); |
| 2065 | PHINode *Phi = B.CreatePHI(Ty: CI->getType(), NumReservedValues: N); |
| 2066 | B.CreateBr(Dest: BBTail); |
| 2067 | |
| 2068 | Value *Base = LHS; |
| 2069 | for (uint64_t i = 0; i < N; ++i) { |
| 2070 | B.SetInsertPoint(BBSubs[i]); |
| 2071 | Value *VL = |
| 2072 | B.CreateZExt(V: B.CreateLoad(Ty: B.getInt8Ty(), |
| 2073 | Ptr: B.CreateInBoundsPtrAdd(Ptr: Base, Offset: B.getInt64(C: i))), |
| 2074 | DestTy: CI->getType()); |
| 2075 | Value *VR = |
| 2076 | ConstantInt::get(Ty: CI->getType(), V: static_cast<unsigned char>(RHS[i])); |
| 2077 | Value *Sub = Swapped ? B.CreateSub(LHS: VR, RHS: VL) : B.CreateSub(LHS: VL, RHS: VR); |
| 2078 | if (i < N - 1) { |
| 2079 | CondBrInst *CondBrInst = B.CreateCondBr( |
| 2080 | Cond: B.CreateICmpNE(LHS: Sub, RHS: ConstantInt::get(Ty: CI->getType(), V: 0)), True: BBNE, |
| 2081 | False: BBSubs[i + 1]); |
| 2082 | |
| 2083 | Function *F = CI->getFunction(); |
| 2084 | assert(F && "Instruction does not belong to a function!" ); |
| 2085 | std::optional<uint64_t> EC = F->getEntryCount(); |
| 2086 | if (EC && *EC > 0) |
| 2087 | setExplicitlyUnknownBranchWeights(I&: *CondBrInst, DEBUG_TYPE); |
| 2088 | } else { |
| 2089 | B.CreateBr(Dest: BBNE); |
| 2090 | } |
| 2091 | |
| 2092 | Phi->addIncoming(V: Sub, BB: BBSubs[i]); |
| 2093 | } |
| 2094 | |
| 2095 | CI->replaceAllUsesWith(V: Phi); |
| 2096 | CI->eraseFromParent(); |
| 2097 | |
| 2098 | if (DTU) { |
| 2099 | SmallVector<DominatorTree::UpdateType, 8> Updates; |
| 2100 | Updates.push_back(Elt: {DominatorTree::Insert, BBCI, BBSubs[0]}); |
| 2101 | for (uint64_t i = 0; i < N; ++i) { |
| 2102 | if (i < N - 1) |
| 2103 | Updates.push_back(Elt: {DominatorTree::Insert, BBSubs[i], BBSubs[i + 1]}); |
| 2104 | Updates.push_back(Elt: {DominatorTree::Insert, BBSubs[i], BBNE}); |
| 2105 | } |
| 2106 | Updates.push_back(Elt: {DominatorTree::Insert, BBNE, BBTail}); |
| 2107 | Updates.push_back(Elt: {DominatorTree::Delete, BBCI, BBTail}); |
| 2108 | DTU->applyUpdates(Updates); |
| 2109 | } |
| 2110 | } |
| 2111 | |
| 2112 | /// Convert memchr with a small constant string into a switch |
| 2113 | static bool foldMemChr(CallInst *Call, DomTreeUpdater *DTU, |
| 2114 | const DataLayout &DL) { |
| 2115 | if (isa<Constant>(Val: Call->getArgOperand(i: 1))) |
| 2116 | return false; |
| 2117 | |
| 2118 | StringRef Str; |
| 2119 | Value *Base = Call->getArgOperand(i: 0); |
| 2120 | if (!getConstantStringInfo(V: Base, Str, /*TrimAtNul=*/false)) |
| 2121 | return false; |
| 2122 | |
| 2123 | uint64_t N = Str.size(); |
| 2124 | if (auto *ConstInt = dyn_cast<ConstantInt>(Val: Call->getArgOperand(i: 2))) { |
| 2125 | uint64_t Val = ConstInt->getZExtValue(); |
| 2126 | // Ignore the case that n is larger than the size of string. |
| 2127 | if (Val > N) |
| 2128 | return false; |
| 2129 | N = Val; |
| 2130 | } else |
| 2131 | return false; |
| 2132 | |
| 2133 | if (N > MemChrInlineThreshold) |
| 2134 | return false; |
| 2135 | |
| 2136 | BasicBlock *BB = Call->getParent(); |
| 2137 | BasicBlock *BBNext = SplitBlock(Old: BB, SplitPt: Call, DTU); |
| 2138 | IRBuilder<> IRB(BB); |
| 2139 | IRB.SetCurrentDebugLocation(Call->getDebugLoc()); |
| 2140 | IntegerType *ByteTy = IRB.getInt8Ty(); |
| 2141 | BB->getTerminator()->eraseFromParent(); |
| 2142 | SwitchInst *SI = IRB.CreateSwitch( |
| 2143 | V: IRB.CreateTrunc(V: Call->getArgOperand(i: 1), DestTy: ByteTy), Dest: BBNext, NumCases: N); |
| 2144 | // We can't know the precise weights here, as they would depend on the value |
| 2145 | // distribution of Call->getArgOperand(1). So we just mark it as "unknown". |
| 2146 | setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE); |
| 2147 | Type *IndexTy = DL.getIndexType(PtrTy: Call->getType()); |
| 2148 | SmallVector<DominatorTree::UpdateType, 8> Updates; |
| 2149 | |
| 2150 | BasicBlock *BBSuccess = BasicBlock::Create( |
| 2151 | Context&: Call->getContext(), Name: "memchr.success" , Parent: BB->getParent(), InsertBefore: BBNext); |
| 2152 | IRB.SetInsertPoint(BBSuccess); |
| 2153 | PHINode *IndexPHI = IRB.CreatePHI(Ty: IndexTy, NumReservedValues: N, Name: "memchr.idx" ); |
| 2154 | Value *FirstOccursLocation = IRB.CreateInBoundsPtrAdd(Ptr: Base, Offset: IndexPHI); |
| 2155 | IRB.CreateBr(Dest: BBNext); |
| 2156 | if (DTU) |
| 2157 | Updates.push_back(Elt: {DominatorTree::Insert, BBSuccess, BBNext}); |
| 2158 | |
| 2159 | SmallPtrSet<ConstantInt *, 4> Cases; |
| 2160 | for (uint64_t I = 0; I < N; ++I) { |
| 2161 | ConstantInt *CaseVal = |
| 2162 | ConstantInt::get(Ty: ByteTy, V: static_cast<unsigned char>(Str[I])); |
| 2163 | if (!Cases.insert(Ptr: CaseVal).second) |
| 2164 | continue; |
| 2165 | |
| 2166 | BasicBlock *BBCase = BasicBlock::Create(Context&: Call->getContext(), Name: "memchr.case" , |
| 2167 | Parent: BB->getParent(), InsertBefore: BBSuccess); |
| 2168 | SI->addCase(OnVal: CaseVal, Dest: BBCase); |
| 2169 | IRB.SetInsertPoint(BBCase); |
| 2170 | IndexPHI->addIncoming(V: ConstantInt::get(Ty: IndexTy, V: I), BB: BBCase); |
| 2171 | IRB.CreateBr(Dest: BBSuccess); |
| 2172 | if (DTU) { |
| 2173 | Updates.push_back(Elt: {DominatorTree::Insert, BB, BBCase}); |
| 2174 | Updates.push_back(Elt: {DominatorTree::Insert, BBCase, BBSuccess}); |
| 2175 | } |
| 2176 | } |
| 2177 | |
| 2178 | PHINode *PHI = |
| 2179 | PHINode::Create(Ty: Call->getType(), NumReservedValues: 2, NameStr: Call->getName(), InsertBefore: BBNext->begin()); |
| 2180 | PHI->addIncoming(V: Constant::getNullValue(Ty: Call->getType()), BB); |
| 2181 | PHI->addIncoming(V: FirstOccursLocation, BB: BBSuccess); |
| 2182 | |
| 2183 | Call->replaceAllUsesWith(V: PHI); |
| 2184 | Call->eraseFromParent(); |
| 2185 | |
| 2186 | if (DTU) |
| 2187 | DTU->applyUpdates(Updates); |
| 2188 | |
| 2189 | return true; |
| 2190 | } |
| 2191 | |
| 2192 | static bool foldLibCalls(Instruction &I, TargetTransformInfo &TTI, |
| 2193 | TargetLibraryInfo &TLI, AssumptionCache &AC, |
| 2194 | DominatorTree &DT, const DataLayout &DL, |
| 2195 | bool &MadeCFGChange) { |
| 2196 | |
| 2197 | auto *CI = dyn_cast<CallInst>(Val: &I); |
| 2198 | if (!CI || CI->isNoBuiltin()) |
| 2199 | return false; |
| 2200 | |
| 2201 | Function *CalledFunc = CI->getCalledFunction(); |
| 2202 | if (!CalledFunc) |
| 2203 | return false; |
| 2204 | |
| 2205 | LibFunc LF = TLI.getLibFunc(FDecl: *CalledFunc); |
| 2206 | if (!isLibFuncEmittable(M: CI->getModule(), TLI: &TLI, TheLibFunc: LF)) |
| 2207 | return false; |
| 2208 | |
| 2209 | DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy); |
| 2210 | |
| 2211 | switch (LF) { |
| 2212 | case LibFunc_sqrt: |
| 2213 | case LibFunc_sqrtf: |
| 2214 | case LibFunc_sqrtl: |
| 2215 | return foldSqrt(Call: CI, Func: LF, TTI, TLI, AC, DT); |
| 2216 | case LibFunc_strcmp: |
| 2217 | case LibFunc_strncmp: |
| 2218 | if (StrNCmpInliner(CI, LF, &DTU, DL).optimizeStrNCmp()) { |
| 2219 | MadeCFGChange = true; |
| 2220 | return true; |
| 2221 | } |
| 2222 | break; |
| 2223 | case LibFunc_memchr: |
| 2224 | if (foldMemChr(Call: CI, DTU: &DTU, DL)) { |
| 2225 | MadeCFGChange = true; |
| 2226 | return true; |
| 2227 | } |
| 2228 | break; |
| 2229 | default:; |
| 2230 | } |
| 2231 | return false; |
| 2232 | } |
| 2233 | |
| 2234 | /// Match high part of long multiplication. |
| 2235 | /// |
| 2236 | /// Considering a multiply made up of high and low parts, we can split the |
| 2237 | /// multiply into: |
| 2238 | /// x * y == (xh*T + xl) * (yh*T + yl) |
| 2239 | /// where xh == x>>32 and xl == x & 0xffffffff. T = 2^32. |
| 2240 | /// This expands to |
| 2241 | /// xh*yh*T*T + xh*yl*T + xl*yh*T + xl*yl |
| 2242 | /// which can be drawn as |
| 2243 | /// [ xh*yh ] |
| 2244 | /// [ xh*yl ] |
| 2245 | /// [ xl*yh ] |
| 2246 | /// [ xl*yl ] |
| 2247 | /// We are looking for the "high" half, which is xh*yh + xh*yl>>32 + xl*yh>>32 + |
| 2248 | /// some carrys. The carry makes this difficult and there are multiple ways of |
| 2249 | /// representing it. The ones we attempt to support here are: |
| 2250 | /// Carry: xh*yh + carry + lowsum |
| 2251 | /// carry = lowsum < xh*yl ? 0x1000000 : 0 |
| 2252 | /// lowsum = xh*yl + xl*yh + (xl*yl>>32) |
| 2253 | /// Ladder: xh*yh + c2>>32 + c3>>32 |
| 2254 | /// c2 = xh*yl + (xl*yl>>32); c3 = c2&0xffffffff + xl*yh |
| 2255 | /// or c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32); c3 = xl*yh |
| 2256 | /// Carry4: xh*yh + carry + crosssum>>32 + (xl*yl + crosssum&0xffffffff) >> 32 |
| 2257 | /// crosssum = xh*yl + xl*yh |
| 2258 | /// carry = crosssum < xh*yl ? 0x1000000 : 0 |
| 2259 | /// Ladder4: xh*yh + (xl*yh)>>32 + (xh*yl)>>32 + low>>32; |
| 2260 | /// low = (xl*yl)>>32 + (xl*yh)&0xffffffff + (xh*yl)&0xffffffff |
| 2261 | /// |
| 2262 | /// They all start by matching xh*yh + 2 or 3 other operands. The bottom of the |
| 2263 | /// tree is xh*yh, xh*yl, xl*yh and xl*yl. |
| 2264 | static bool foldMulHigh(Instruction &I) { |
| 2265 | Type *Ty = I.getType(); |
| 2266 | if (!Ty->isIntOrIntVectorTy()) |
| 2267 | return false; |
| 2268 | |
| 2269 | unsigned BitWidth = Ty->getScalarSizeInBits(); |
| 2270 | APInt LowMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth / 2); |
| 2271 | if (BitWidth % 2 != 0) |
| 2272 | return false; |
| 2273 | |
| 2274 | auto CreateMulHigh = [&](Value *X, Value *Y) { |
| 2275 | IRBuilder<> Builder(&I); |
| 2276 | Type *NTy = Ty->getWithNewBitWidth(NewBitWidth: BitWidth * 2); |
| 2277 | Value *XExt = Builder.CreateZExt(V: X, DestTy: NTy); |
| 2278 | Value *YExt = Builder.CreateZExt(V: Y, DestTy: NTy); |
| 2279 | Value *Mul = Builder.CreateMul(LHS: XExt, RHS: YExt, Name: "" , /*HasNUW=*/true); |
| 2280 | Value *High = Builder.CreateLShr(LHS: Mul, RHS: BitWidth); |
| 2281 | Value *Res = Builder.CreateTrunc(V: High, DestTy: Ty, Name: "" , /*HasNUW=*/IsNUW: true); |
| 2282 | Res->takeName(V: &I); |
| 2283 | I.replaceAllUsesWith(V: Res); |
| 2284 | LLVM_DEBUG(dbgs() << "Created long multiply from parts of " << *X << " and " |
| 2285 | << *Y << "\n" ); |
| 2286 | return true; |
| 2287 | }; |
| 2288 | |
| 2289 | // Common check routines for X_lo*Y_lo and X_hi*Y_lo |
| 2290 | auto CheckLoLo = [&](Value *XlYl, Value *X, Value *Y) { |
| 2291 | return match(V: XlYl, P: m_c_Mul(L: m_And(L: m_Specific(V: X), R: m_SpecificInt(V: LowMask)), |
| 2292 | R: m_And(L: m_Specific(V: Y), R: m_SpecificInt(V: LowMask)))); |
| 2293 | }; |
| 2294 | auto CheckHiLo = [&](Value *XhYl, Value *X, Value *Y) { |
| 2295 | return match(V: XhYl, |
| 2296 | P: m_c_Mul(L: m_LShr(L: m_Specific(V: X), R: m_SpecificInt(V: BitWidth / 2)), |
| 2297 | R: m_And(L: m_Specific(V: Y), R: m_SpecificInt(V: LowMask)))); |
| 2298 | }; |
| 2299 | |
| 2300 | auto FoldMulHighCarry = [&](Value *X, Value *Y, Instruction *Carry, |
| 2301 | Instruction *B) { |
| 2302 | // Looking for LowSum >> 32 and carry (select) |
| 2303 | if (Carry->getOpcode() != Instruction::Select) |
| 2304 | std::swap(a&: Carry, b&: B); |
| 2305 | |
| 2306 | // Carry = LowSum < XhYl ? 0x100000000 : 0 |
| 2307 | Value *LowSum, *XhYl; |
| 2308 | if (!match(V: Carry, |
| 2309 | P: m_OneUse(SubPattern: m_Select( |
| 2310 | C: m_OneUse(SubPattern: m_SpecificICmp(MatchPred: ICmpInst::ICMP_ULT, L: m_Value(V&: LowSum), |
| 2311 | R: m_Value(V&: XhYl))), |
| 2312 | L: m_SpecificInt(V: APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth / 2)), |
| 2313 | R: m_Zero())))) |
| 2314 | return false; |
| 2315 | |
| 2316 | // XhYl can be Xh*Yl or Xl*Yh |
| 2317 | if (!CheckHiLo(XhYl, X, Y)) { |
| 2318 | if (CheckHiLo(XhYl, Y, X)) |
| 2319 | std::swap(a&: X, b&: Y); |
| 2320 | else |
| 2321 | return false; |
| 2322 | } |
| 2323 | if (XhYl->hasNUsesOrMore(N: 3)) |
| 2324 | return false; |
| 2325 | |
| 2326 | // B = LowSum >> 32 |
| 2327 | if (!match(V: B, P: m_OneUse(SubPattern: m_LShr(L: m_Specific(V: LowSum), |
| 2328 | R: m_SpecificInt(V: BitWidth / 2)))) || |
| 2329 | LowSum->hasNUsesOrMore(N: 3)) |
| 2330 | return false; |
| 2331 | |
| 2332 | // LowSum = XhYl + XlYh + XlYl>>32 |
| 2333 | Value *XlYh, *XlYl; |
| 2334 | auto XlYlHi = m_LShr(L: m_Value(V&: XlYl), R: m_SpecificInt(V: BitWidth / 2)); |
| 2335 | if (!match(V: LowSum, |
| 2336 | P: m_c_Add(L: m_Specific(V: XhYl), |
| 2337 | R: m_OneUse(SubPattern: m_c_Add(L: m_OneUse(SubPattern: m_Value(V&: XlYh)), R: XlYlHi)))) && |
| 2338 | !match(V: LowSum, P: m_c_Add(L: m_OneUse(SubPattern: m_Value(V&: XlYh)), |
| 2339 | R: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: XhYl), R: XlYlHi)))) && |
| 2340 | !match(V: LowSum, |
| 2341 | P: m_c_Add(L: XlYlHi, R: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: XhYl), |
| 2342 | R: m_OneUse(SubPattern: m_Value(V&: XlYh))))))) |
| 2343 | return false; |
| 2344 | |
| 2345 | // Check XlYl and XlYh |
| 2346 | if (!CheckLoLo(XlYl, X, Y)) |
| 2347 | return false; |
| 2348 | if (!CheckHiLo(XlYh, Y, X)) |
| 2349 | return false; |
| 2350 | |
| 2351 | return CreateMulHigh(X, Y); |
| 2352 | }; |
| 2353 | |
| 2354 | auto FoldMulHighLadder = [&](Value *X, Value *Y, Instruction *A, |
| 2355 | Instruction *B) { |
| 2356 | // xh*yh + c2>>32 + c3>>32 |
| 2357 | // c2 = xh*yl + (xl*yl>>32); c3 = c2&0xffffffff + xl*yh |
| 2358 | // or c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32); c3 = xh*yl |
| 2359 | Value *XlYh, *XhYl, *XlYl, *C2, *C3; |
| 2360 | // Strip off the two expected shifts. |
| 2361 | if (!match(V: A, P: m_LShr(L: m_Value(V&: C2), R: m_SpecificInt(V: BitWidth / 2))) || |
| 2362 | !match(V: B, P: m_LShr(L: m_Value(V&: C3), R: m_SpecificInt(V: BitWidth / 2)))) |
| 2363 | return false; |
| 2364 | |
| 2365 | if (match(V: C3, P: m_c_Add(L: m_Add(L: m_Value(), R: m_Value()), R: m_Value()))) |
| 2366 | std::swap(a&: C2, b&: C3); |
| 2367 | // Try to match c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32) |
| 2368 | if (match(V: C2, |
| 2369 | P: m_c_Add(L: m_c_Add(L: m_And(L: m_Specific(V: C3), R: m_SpecificInt(V: LowMask)), |
| 2370 | R: m_Value(V&: XlYh)), |
| 2371 | R: m_LShr(L: m_Value(V&: XlYl), R: m_SpecificInt(V: BitWidth / 2)))) || |
| 2372 | match(V: C2, P: m_c_Add(L: m_c_Add(L: m_And(L: m_Specific(V: C3), R: m_SpecificInt(V: LowMask)), |
| 2373 | R: m_LShr(L: m_Value(V&: XlYl), |
| 2374 | R: m_SpecificInt(V: BitWidth / 2))), |
| 2375 | R: m_Value(V&: XlYh))) || |
| 2376 | match(V: C2, P: m_c_Add(L: m_c_Add(L: m_LShr(L: m_Value(V&: XlYl), |
| 2377 | R: m_SpecificInt(V: BitWidth / 2)), |
| 2378 | R: m_Value(V&: XlYh)), |
| 2379 | R: m_And(L: m_Specific(V: C3), R: m_SpecificInt(V: LowMask))))) { |
| 2380 | XhYl = C3; |
| 2381 | } else { |
| 2382 | // Match c3 = c2&0xffffffff + xl*yh |
| 2383 | if (!match(V: C3, P: m_c_Add(L: m_And(L: m_Specific(V: C2), R: m_SpecificInt(V: LowMask)), |
| 2384 | R: m_Value(V&: XlYh)))) |
| 2385 | std::swap(a&: C2, b&: C3); |
| 2386 | if (!match(V: C3, P: m_c_Add(L: m_OneUse( |
| 2387 | SubPattern: m_And(L: m_Specific(V: C2), R: m_SpecificInt(V: LowMask))), |
| 2388 | R: m_Value(V&: XlYh))) || |
| 2389 | !C3->hasOneUse() || C2->hasNUsesOrMore(N: 3)) |
| 2390 | return false; |
| 2391 | |
| 2392 | // Match c2 = xh*yl + (xl*yl >> 32) |
| 2393 | if (!match(V: C2, P: m_c_Add(L: m_LShr(L: m_Value(V&: XlYl), R: m_SpecificInt(V: BitWidth / 2)), |
| 2394 | R: m_Value(V&: XhYl)))) |
| 2395 | return false; |
| 2396 | } |
| 2397 | |
| 2398 | // Match XhYl and XlYh - they can appear either way around. |
| 2399 | if (!CheckHiLo(XlYh, Y, X)) |
| 2400 | std::swap(a&: XlYh, b&: XhYl); |
| 2401 | if (!CheckHiLo(XlYh, Y, X)) |
| 2402 | return false; |
| 2403 | if (!CheckHiLo(XhYl, X, Y)) |
| 2404 | return false; |
| 2405 | if (!CheckLoLo(XlYl, X, Y)) |
| 2406 | return false; |
| 2407 | |
| 2408 | return CreateMulHigh(X, Y); |
| 2409 | }; |
| 2410 | |
| 2411 | auto FoldMulHighLadder4 = [&](Value *X, Value *Y, Instruction *A, |
| 2412 | Instruction *B, Instruction *C) { |
| 2413 | /// Ladder4: xh*yh + (xl*yh)>>32 + (xh+yl)>>32 + low>>32; |
| 2414 | /// low = (xl*yl)>>32 + (xl*yh)&0xffffffff + (xh*yl)&0xffffffff |
| 2415 | |
| 2416 | // Find A = Low >> 32 and B/C = XhYl>>32, XlYh>>32. |
| 2417 | auto ShiftAdd = |
| 2418 | m_LShr(L: m_Add(L: m_Value(), R: m_Value()), R: m_SpecificInt(V: BitWidth / 2)); |
| 2419 | if (!match(V: A, P: ShiftAdd)) |
| 2420 | std::swap(a&: A, b&: B); |
| 2421 | if (!match(V: A, P: ShiftAdd)) |
| 2422 | std::swap(a&: A, b&: C); |
| 2423 | Value *Low; |
| 2424 | if (!match(V: A, P: m_LShr(L: m_OneUse(SubPattern: m_Value(V&: Low)), R: m_SpecificInt(V: BitWidth / 2)))) |
| 2425 | return false; |
| 2426 | |
| 2427 | // Match B == XhYl>>32 and C == XlYh>>32 |
| 2428 | Value *XhYl, *XlYh; |
| 2429 | if (!match(V: B, P: m_LShr(L: m_Value(V&: XhYl), R: m_SpecificInt(V: BitWidth / 2))) || |
| 2430 | !match(V: C, P: m_LShr(L: m_Value(V&: XlYh), R: m_SpecificInt(V: BitWidth / 2)))) |
| 2431 | return false; |
| 2432 | if (!CheckHiLo(XhYl, X, Y)) |
| 2433 | std::swap(a&: XhYl, b&: XlYh); |
| 2434 | if (!CheckHiLo(XhYl, X, Y) || XhYl->hasNUsesOrMore(N: 3)) |
| 2435 | return false; |
| 2436 | if (!CheckHiLo(XlYh, Y, X) || XlYh->hasNUsesOrMore(N: 3)) |
| 2437 | return false; |
| 2438 | |
| 2439 | // Match Low as XlYl>>32 + XhYl&0xffffffff + XlYh&0xffffffff |
| 2440 | Value *XlYl; |
| 2441 | if (!match( |
| 2442 | V: Low, |
| 2443 | P: m_c_Add( |
| 2444 | L: m_OneUse(SubPattern: m_c_Add( |
| 2445 | L: m_OneUse(SubPattern: m_And(L: m_Specific(V: XhYl), R: m_SpecificInt(V: LowMask))), |
| 2446 | R: m_OneUse(SubPattern: m_And(L: m_Specific(V: XlYh), R: m_SpecificInt(V: LowMask))))), |
| 2447 | R: m_OneUse( |
| 2448 | SubPattern: m_LShr(L: m_Value(V&: XlYl), R: m_SpecificInt(V: BitWidth / 2))))) && |
| 2449 | !match( |
| 2450 | V: Low, |
| 2451 | P: m_c_Add( |
| 2452 | L: m_OneUse(SubPattern: m_c_Add( |
| 2453 | L: m_OneUse(SubPattern: m_And(L: m_Specific(V: XhYl), R: m_SpecificInt(V: LowMask))), |
| 2454 | R: m_OneUse( |
| 2455 | SubPattern: m_LShr(L: m_Value(V&: XlYl), R: m_SpecificInt(V: BitWidth / 2))))), |
| 2456 | R: m_OneUse(SubPattern: m_And(L: m_Specific(V: XlYh), R: m_SpecificInt(V: LowMask))))) && |
| 2457 | !match( |
| 2458 | V: Low, |
| 2459 | P: m_c_Add( |
| 2460 | L: m_OneUse(SubPattern: m_c_Add( |
| 2461 | L: m_OneUse(SubPattern: m_And(L: m_Specific(V: XlYh), R: m_SpecificInt(V: LowMask))), |
| 2462 | R: m_OneUse( |
| 2463 | SubPattern: m_LShr(L: m_Value(V&: XlYl), R: m_SpecificInt(V: BitWidth / 2))))), |
| 2464 | R: m_OneUse(SubPattern: m_And(L: m_Specific(V: XhYl), R: m_SpecificInt(V: LowMask)))))) |
| 2465 | return false; |
| 2466 | if (!CheckLoLo(XlYl, X, Y)) |
| 2467 | return false; |
| 2468 | |
| 2469 | return CreateMulHigh(X, Y); |
| 2470 | }; |
| 2471 | |
| 2472 | auto FoldMulHighCarry4 = [&](Value *X, Value *Y, Instruction *Carry, |
| 2473 | Instruction *B, Instruction *C) { |
| 2474 | // xh*yh + carry + crosssum>>32 + (xl*yl + crosssum&0xffffffff) >> 32 |
| 2475 | // crosssum = xh*yl+xl*yh |
| 2476 | // carry = crosssum < xh*yl ? 0x1000000 : 0 |
| 2477 | if (Carry->getOpcode() != Instruction::Select) |
| 2478 | std::swap(a&: Carry, b&: B); |
| 2479 | if (Carry->getOpcode() != Instruction::Select) |
| 2480 | std::swap(a&: Carry, b&: C); |
| 2481 | |
| 2482 | // Carry = CrossSum < XhYl ? 0x100000000 : 0 |
| 2483 | Value *CrossSum, *XhYl; |
| 2484 | if (!match(V: Carry, |
| 2485 | P: m_OneUse(SubPattern: m_Select( |
| 2486 | C: m_OneUse(SubPattern: m_SpecificICmp(MatchPred: ICmpInst::ICMP_ULT, |
| 2487 | L: m_Value(V&: CrossSum), R: m_Value(V&: XhYl))), |
| 2488 | L: m_SpecificInt(V: APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth / 2)), |
| 2489 | R: m_Zero())))) |
| 2490 | return false; |
| 2491 | |
| 2492 | if (!match(V: B, P: m_LShr(L: m_Specific(V: CrossSum), R: m_SpecificInt(V: BitWidth / 2)))) |
| 2493 | std::swap(a&: B, b&: C); |
| 2494 | if (!match(V: B, P: m_LShr(L: m_Specific(V: CrossSum), R: m_SpecificInt(V: BitWidth / 2)))) |
| 2495 | return false; |
| 2496 | |
| 2497 | Value *XlYl, *LowAccum; |
| 2498 | if (!match(V: C, P: m_LShr(L: m_Value(V&: LowAccum), R: m_SpecificInt(V: BitWidth / 2))) || |
| 2499 | !match(V: LowAccum, P: m_c_Add(L: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: XlYl), |
| 2500 | R: m_SpecificInt(V: BitWidth / 2))), |
| 2501 | R: m_OneUse(SubPattern: m_And(L: m_Specific(V: CrossSum), |
| 2502 | R: m_SpecificInt(V: LowMask))))) || |
| 2503 | LowAccum->hasNUsesOrMore(N: 3)) |
| 2504 | return false; |
| 2505 | if (!CheckLoLo(XlYl, X, Y)) |
| 2506 | return false; |
| 2507 | |
| 2508 | if (!CheckHiLo(XhYl, X, Y)) |
| 2509 | std::swap(a&: X, b&: Y); |
| 2510 | if (!CheckHiLo(XhYl, X, Y)) |
| 2511 | return false; |
| 2512 | Value *XlYh; |
| 2513 | if (!match(V: CrossSum, P: m_c_Add(L: m_Specific(V: XhYl), R: m_OneUse(SubPattern: m_Value(V&: XlYh)))) || |
| 2514 | !CheckHiLo(XlYh, Y, X) || CrossSum->hasNUsesOrMore(N: 4) || |
| 2515 | XhYl->hasNUsesOrMore(N: 3)) |
| 2516 | return false; |
| 2517 | |
| 2518 | return CreateMulHigh(X, Y); |
| 2519 | }; |
| 2520 | |
| 2521 | // X and Y are the two inputs, A, B and C are other parts of the pattern |
| 2522 | // (crosssum>>32, carry, etc). |
| 2523 | Value *X, *Y; |
| 2524 | Instruction *A, *B, *C; |
| 2525 | auto HiHi = m_OneUse(SubPattern: m_Mul(L: m_LShr(L: m_Value(V&: X), R: m_SpecificInt(V: BitWidth / 2)), |
| 2526 | R: m_LShr(L: m_Value(V&: Y), R: m_SpecificInt(V: BitWidth / 2)))); |
| 2527 | if ((match(V: &I, P: m_c_Add(L: HiHi, R: m_OneUse(SubPattern: m_Add(L: m_Instruction(I&: A), |
| 2528 | R: m_Instruction(I&: B))))) || |
| 2529 | match(V: &I, P: m_c_Add(L: m_Instruction(I&: A), |
| 2530 | R: m_OneUse(SubPattern: m_c_Add(L: HiHi, R: m_Instruction(I&: B)))))) && |
| 2531 | A->hasOneUse() && B->hasOneUse()) |
| 2532 | if (FoldMulHighCarry(X, Y, A, B) || FoldMulHighLadder(X, Y, A, B)) |
| 2533 | return true; |
| 2534 | |
| 2535 | if ((match(V: &I, P: m_c_Add(L: HiHi, R: m_OneUse(SubPattern: m_c_Add( |
| 2536 | L: m_Instruction(I&: A), |
| 2537 | R: m_OneUse(SubPattern: m_Add(L: m_Instruction(I&: B), |
| 2538 | R: m_Instruction(I&: C))))))) || |
| 2539 | match(V: &I, P: m_c_Add(L: m_Instruction(I&: A), |
| 2540 | R: m_OneUse(SubPattern: m_c_Add( |
| 2541 | L: HiHi, R: m_OneUse(SubPattern: m_Add(L: m_Instruction(I&: B), |
| 2542 | R: m_Instruction(I&: C))))))) || |
| 2543 | match(V: &I, P: m_c_Add(L: m_Instruction(I&: A), |
| 2544 | R: m_OneUse(SubPattern: m_c_Add( |
| 2545 | L: m_Instruction(I&: B), |
| 2546 | R: m_OneUse(SubPattern: m_c_Add(L: HiHi, R: m_Instruction(I&: C))))))) || |
| 2547 | match(V: &I, |
| 2548 | P: m_c_Add(L: m_OneUse(SubPattern: m_c_Add(L: HiHi, R: m_Instruction(I&: A))), |
| 2549 | R: m_OneUse(SubPattern: m_Add(L: m_Instruction(I&: B), R: m_Instruction(I&: C)))))) && |
| 2550 | A->hasOneUse() && B->hasOneUse() && C->hasOneUse()) |
| 2551 | return FoldMulHighCarry4(X, Y, A, B, C) || |
| 2552 | FoldMulHighLadder4(X, Y, A, B, C); |
| 2553 | |
| 2554 | return false; |
| 2555 | } |
| 2556 | |
| 2557 | /// Guard a memset whose nonconstant length is known to be in [0, 1]. |
| 2558 | /// Inserts a conditional branch around the memset and specialises the |
| 2559 | /// executed path to a one-byte store. |
| 2560 | static bool foldMemSetZeroOrOneLength(Instruction &I, const DataLayout &DL, |
| 2561 | TargetLibraryInfo &TLI, |
| 2562 | AssumptionCache &AC, DominatorTree &DT, |
| 2563 | bool &MadeCFGChange) { |
| 2564 | auto *MI = dyn_cast<MemSetInst>(Val: &I); |
| 2565 | if (!MI || isa<ConstantInt>(Val: MI->getLength())) |
| 2566 | return false; |
| 2567 | |
| 2568 | SimplifyQuery SQ(DL, &TLI, &DT, &AC, MI); |
| 2569 | KnownBits KnownLen = computeKnownBits(V: MI->getLength(), Q: SQ); |
| 2570 | if (!KnownLen.getMaxValue().isOne()) |
| 2571 | return false; |
| 2572 | |
| 2573 | uint64_t TotalCount; |
| 2574 | SmallVector<InstrProfValueData> MemsetVPMetadata = getValueProfDataFromInst( |
| 2575 | Inst: I, ValueKind: InstrProfValueKind::IPVK_MemOPSize, MaxNumValueData: 2, TotalC&: TotalCount); |
| 2576 | std::optional<uint64_t> ZeroCount = std::nullopt; |
| 2577 | std::optional<uint64_t> OneCount = std::nullopt; |
| 2578 | for (const auto [MemOpSize, SizeFrequency] : MemsetVPMetadata) { |
| 2579 | if (MemOpSize == 0) |
| 2580 | ZeroCount = SizeFrequency; |
| 2581 | else if (MemOpSize == 1) |
| 2582 | OneCount = SizeFrequency; |
| 2583 | } |
| 2584 | // If we only have one value in the profile, we assume that the other is zero. |
| 2585 | if (MemsetVPMetadata.size() == 1) { |
| 2586 | if (ZeroCount.has_value()) |
| 2587 | OneCount = 0; |
| 2588 | else if (OneCount.has_value()) |
| 2589 | ZeroCount = 0; |
| 2590 | } |
| 2591 | |
| 2592 | BasicBlock *HeadBlock = MI->getIterator()->getParent(); |
| 2593 | DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); |
| 2594 | IRBuilder<> B(MI); |
| 2595 | Value *IsNonZero = B.CreateIsNotNull(Arg: MI->getLength(), Name: "memset.notzero" ); |
| 2596 | Instruction *ThenTerm = SplitBlockAndInsertIfThen( |
| 2597 | Cond: IsNonZero, SplitBefore: MI->getIterator(), /*Unreachable=*/false, |
| 2598 | /*BranchWeights=*/nullptr, DTU: &DTU); |
| 2599 | |
| 2600 | Instruction &IsNonZeroBranch = *HeadBlock->getTerminator(); |
| 2601 | if (!ProfcheckDisableMetadataFixes && OneCount.has_value() && |
| 2602 | ZeroCount.has_value() && (*OneCount + *ZeroCount > 0)) |
| 2603 | setFittedBranchWeights(I&: IsNonZeroBranch, Weights: {*OneCount, *ZeroCount}, IsExpected: false); |
| 2604 | else |
| 2605 | setExplicitlyUnknownBranchWeightsIfProfiled(I&: IsNonZeroBranch, DEBUG_TYPE); |
| 2606 | |
| 2607 | IRBuilder<> StoreBuilder(ThenTerm); |
| 2608 | StoreInst *Store = StoreBuilder.CreateAlignedStore( |
| 2609 | Val: MI->getValue(), Ptr: MI->getDest(), Align: MI->getDestAlign(), isVolatile: MI->isVolatile()); |
| 2610 | Store->copyMetadata(SrcInst: *MI, WL: LLVMContext::MD_DIAssignID); |
| 2611 | MI->eraseFromParent(); |
| 2612 | ++NumMemSetsGuarded; |
| 2613 | MadeCFGChange = true; |
| 2614 | return true; |
| 2615 | } |
| 2616 | |
| 2617 | /// This is the entry point for folds that could be implemented in regular |
| 2618 | /// InstCombine, but they are separated because they are not expected to |
| 2619 | /// occur frequently and/or have more than a constant-length pattern match. |
| 2620 | static bool foldUnusualPatterns(Function &F, DominatorTree &DT, |
| 2621 | TargetTransformInfo &TTI, |
| 2622 | TargetLibraryInfo &TLI, AliasAnalysis &AA, |
| 2623 | AssumptionCache &AC, bool &MadeCFGChange) { |
| 2624 | bool MadeChange = false; |
| 2625 | for (BasicBlock &BB : F) { |
| 2626 | // Ignore unreachable basic blocks. |
| 2627 | if (!DT.isReachableFromEntry(A: &BB)) |
| 2628 | continue; |
| 2629 | |
| 2630 | const DataLayout &DL = F.getDataLayout(); |
| 2631 | |
| 2632 | // Walk the block backwards for efficiency. We're matching a chain of |
| 2633 | // use->defs, so we're more likely to succeed by starting from the bottom. |
| 2634 | // Also, we want to avoid matching partial patterns. |
| 2635 | // TODO: It would be more efficient if we removed dead instructions |
| 2636 | // iteratively in this loop rather than waiting until the end. |
| 2637 | for (Instruction &I : make_early_inc_range(Range: llvm::reverse(C&: BB))) { |
| 2638 | MadeChange |= foldAnyOrAllBitsSet(I); |
| 2639 | MadeChange |= foldGuardedFunnelShift(I, DT); |
| 2640 | MadeChange |= foldSelectSplitCTLZCTTZ(I); |
| 2641 | MadeChange |= tryToRecognizePopCount(I); |
| 2642 | MadeChange |= tryToRecognizePopCount1(I); |
| 2643 | MadeChange |= tryToRecognizePopCount2n3(I); |
| 2644 | MadeChange |= tryToFPToSat(I, TTI); |
| 2645 | MadeChange |= tryToRecognizeTableBasedPatterns(I, DL, TTI); |
| 2646 | MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA, DT); |
| 2647 | MadeChange |= foldPatternedLoads(I, DL); |
| 2648 | MadeChange |= foldICmpOrChain(I, DL, TTI, AA, DT); |
| 2649 | MadeChange |= foldMulHigh(I); |
| 2650 | // These folds can erase the instruction `I`, so they need to be called |
| 2651 | // at the end of this sequence. |
| 2652 | if (foldLibCalls(I, TTI, TLI, AC, DT, DL, MadeCFGChange)) { |
| 2653 | MadeChange = true; |
| 2654 | continue; |
| 2655 | } |
| 2656 | if (foldMemSetZeroOrOneLength(I, DL, TLI, AC, DT, MadeCFGChange)) |
| 2657 | MadeChange = true; |
| 2658 | } |
| 2659 | |
| 2660 | // Do this separately to avoid redundantly scanning stores multiple times. |
| 2661 | MadeChange |= foldConsecutiveStores(BB, DL, TTI, AA); |
| 2662 | } |
| 2663 | |
| 2664 | // We're done with transforms, so remove dead instructions. |
| 2665 | if (MadeChange) |
| 2666 | for (BasicBlock &BB : F) |
| 2667 | SimplifyInstructionsInBlock(BB: &BB); |
| 2668 | |
| 2669 | return MadeChange; |
| 2670 | } |
| 2671 | |
| 2672 | /// This is the entry point for all transforms. Pass manager differences are |
| 2673 | /// handled in the callers of this function. |
| 2674 | static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI, |
| 2675 | TargetLibraryInfo &TLI, DominatorTree &DT, |
| 2676 | AliasAnalysis &AA, bool &MadeCFGChange) { |
| 2677 | bool MadeChange = false; |
| 2678 | const DataLayout &DL = F.getDataLayout(); |
| 2679 | TruncInstCombine TIC(AC, TLI, DL, DT); |
| 2680 | MadeChange |= TIC.run(F); |
| 2681 | MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA, AC, MadeCFGChange); |
| 2682 | return MadeChange; |
| 2683 | } |
| 2684 | |
| 2685 | PreservedAnalyses AggressiveInstCombinePass::run(Function &F, |
| 2686 | FunctionAnalysisManager &AM) { |
| 2687 | auto &AC = AM.getResult<AssumptionAnalysis>(IR&: F); |
| 2688 | auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F); |
| 2689 | auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F); |
| 2690 | auto &TTI = AM.getResult<TargetIRAnalysis>(IR&: F); |
| 2691 | auto &AA = AM.getResult<AAManager>(IR&: F); |
| 2692 | bool MadeCFGChange = false; |
| 2693 | if (!runImpl(F, AC, TTI, TLI, DT, AA, MadeCFGChange)) { |
| 2694 | // No changes, all analyses are preserved. |
| 2695 | return PreservedAnalyses::all(); |
| 2696 | } |
| 2697 | // Mark all the analyses that instcombine updates as preserved. |
| 2698 | PreservedAnalyses PA; |
| 2699 | if (MadeCFGChange) |
| 2700 | PA.preserve<DominatorTreeAnalysis>(); |
| 2701 | else |
| 2702 | PA.preserveSet<CFGAnalyses>(); |
| 2703 | return PA; |
| 2704 | } |
| 2705 | |