AggressiveInstCombine.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
  15. #include "AggressiveInstCombineInternal.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/Analysis/AliasAnalysis.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/BasicAliasAnalysis.h"
  20. #include "llvm/Analysis/GlobalsModRef.h"
  21. #include "llvm/Analysis/TargetLibraryInfo.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/IRBuilder.h"
  28. #include "llvm/IR/PatternMatch.h"
  29. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  30. #include "llvm/Transforms/Utils/Local.h"
  31. using namespace llvm;
  32. using namespace PatternMatch;
  33. #define DEBUG_TYPE "aggressive-instcombine"
  34. STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
  35. STATISTIC(NumGuardedRotates,
  36. "Number of guarded rotates transformed into funnel shifts");
  37. STATISTIC(NumGuardedFunnelShifts,
  38. "Number of guarded funnel shifts transformed into funnel shifts");
  39. STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
  40. static cl::opt<unsigned> MaxInstrsToScan(
  41. "aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden,
  42. cl::desc("Max number of instructions to scan for aggressive instcombine."));
  43. /// Match a pattern for a bitwise funnel/rotate operation that partially guards
  44. /// against undefined behavior by branching around the funnel-shift/rotation
  45. /// when the shift amount is 0.
  46. static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT) {
  47. if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
  48. return false;
  49. // As with the one-use checks below, this is not strictly necessary, but we
  50. // are being cautious to avoid potential perf regressions on targets that
  51. // do not actually have a funnel/rotate instruction (where the funnel shift
  52. // would be expanded back into math/shift/logic ops).
  53. if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
  54. return false;
  55. // Match V to funnel shift left/right and capture the source operands and
  56. // shift amount.
  57. auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
  58. Value *&ShAmt) {
  59. Value *SubAmt;
  60. unsigned Width = V->getType()->getScalarSizeInBits();
  61. // fshl(ShVal0, ShVal1, ShAmt)
  62. // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
  63. if (match(V, m_OneUse(m_c_Or(
  64. m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
  65. m_LShr(m_Value(ShVal1),
  66. m_Sub(m_SpecificInt(Width), m_Value(SubAmt))))))) {
  67. if (ShAmt == SubAmt) // TODO: Use m_Specific
  68. return Intrinsic::fshl;
  69. }
  70. // fshr(ShVal0, ShVal1, ShAmt)
  71. // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
  72. if (match(V,
  73. m_OneUse(m_c_Or(m_Shl(m_Value(ShVal0), m_Sub(m_SpecificInt(Width),
  74. m_Value(SubAmt))),
  75. m_LShr(m_Value(ShVal1), m_Value(ShAmt)))))) {
  76. if (ShAmt == SubAmt) // TODO: Use m_Specific
  77. return Intrinsic::fshr;
  78. }
  79. return Intrinsic::not_intrinsic;
  80. };
  81. // One phi operand must be a funnel/rotate operation, and the other phi
  82. // operand must be the source value of that funnel/rotate operation:
  83. // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
  84. // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
  85. // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
  86. PHINode &Phi = cast<PHINode>(I);
  87. unsigned FunnelOp = 0, GuardOp = 1;
  88. Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
  89. Value *ShVal0, *ShVal1, *ShAmt;
  90. Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
  91. if (IID == Intrinsic::not_intrinsic ||
  92. (IID == Intrinsic::fshl && ShVal0 != P1) ||
  93. (IID == Intrinsic::fshr && ShVal1 != P1)) {
  94. IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
  95. if (IID == Intrinsic::not_intrinsic ||
  96. (IID == Intrinsic::fshl && ShVal0 != P0) ||
  97. (IID == Intrinsic::fshr && ShVal1 != P0))
  98. return false;
  99. assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
  100. "Pattern must match funnel shift left or right");
  101. std::swap(FunnelOp, GuardOp);
  102. }
  103. // The incoming block with our source operand must be the "guard" block.
  104. // That must contain a cmp+branch to avoid the funnel/rotate when the shift
  105. // amount is equal to 0. The other incoming block is the block with the
  106. // funnel/rotate.
  107. BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
  108. BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
  109. Instruction *TermI = GuardBB->getTerminator();
  110. // Ensure that the shift values dominate each block.
  111. if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
  112. return false;
  113. ICmpInst::Predicate Pred;
  114. BasicBlock *PhiBB = Phi.getParent();
  115. if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()),
  116. m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
  117. return false;
  118. if (Pred != CmpInst::ICMP_EQ)
  119. return false;
  120. IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt());
  121. if (ShVal0 == ShVal1)
  122. ++NumGuardedRotates;
  123. else
  124. ++NumGuardedFunnelShifts;
  125. // If this is not a rotate then the select was blocking poison from the
  126. // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
  127. bool IsFshl = IID == Intrinsic::fshl;
  128. if (ShVal0 != ShVal1) {
  129. if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
  130. ShVal1 = Builder.CreateFreeze(ShVal1);
  131. else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
  132. ShVal0 = Builder.CreateFreeze(ShVal0);
  133. }
  134. // We matched a variation of this IR pattern:
  135. // GuardBB:
  136. // %cmp = icmp eq i32 %ShAmt, 0
  137. // br i1 %cmp, label %PhiBB, label %FunnelBB
  138. // FunnelBB:
  139. // %sub = sub i32 32, %ShAmt
  140. // %shr = lshr i32 %ShVal1, %sub
  141. // %shl = shl i32 %ShVal0, %ShAmt
  142. // %fsh = or i32 %shr, %shl
  143. // br label %PhiBB
  144. // PhiBB:
  145. // %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
  146. // -->
  147. // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
  148. Function *F = Intrinsic::getDeclaration(Phi.getModule(), IID, Phi.getType());
  149. Phi.replaceAllUsesWith(Builder.CreateCall(F, {ShVal0, ShVal1, ShAmt}));
  150. return true;
  151. }
  152. /// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
  153. /// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
  154. /// of 'and' ops, then we also need to capture the fact that we saw an
  155. /// "and X, 1", so that's an extra return value for that case.
  156. struct MaskOps {
  157. Value *Root = nullptr;
  158. APInt Mask;
  159. bool MatchAndChain;
  160. bool FoundAnd1 = false;
  161. MaskOps(unsigned BitWidth, bool MatchAnds)
  162. : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
  163. };
  164. /// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
  165. /// chain of 'and' or 'or' instructions looking for shift ops of a common source
  166. /// value. Examples:
  167. /// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
  168. /// returns { X, 0x129 }
  169. /// and (and (X >> 1), 1), (X >> 4)
  170. /// returns { X, 0x12 }
  171. static bool matchAndOrChain(Value *V, MaskOps &MOps) {
  172. Value *Op0, *Op1;
  173. if (MOps.MatchAndChain) {
  174. // Recurse through a chain of 'and' operands. This requires an extra check
  175. // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
  176. // in the chain to know that all of the high bits are cleared.
  177. if (match(V, m_And(m_Value(Op0), m_One()))) {
  178. MOps.FoundAnd1 = true;
  179. return matchAndOrChain(Op0, MOps);
  180. }
  181. if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
  182. return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
  183. } else {
  184. // Recurse through a chain of 'or' operands.
  185. if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
  186. return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
  187. }
  188. // We need a shift-right or a bare value representing a compare of bit 0 of
  189. // the original source operand.
  190. Value *Candidate;
  191. const APInt *BitIndex = nullptr;
  192. if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
  193. Candidate = V;
  194. // Initialize result source operand.
  195. if (!MOps.Root)
  196. MOps.Root = Candidate;
  197. // The shift constant is out-of-range? This code hasn't been simplified.
  198. if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
  199. return false;
  200. // Fill in the mask bit derived from the shift constant.
  201. MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
  202. return MOps.Root == Candidate;
  203. }
  204. /// Match patterns that correspond to "any-bits-set" and "all-bits-set".
  205. /// These will include a chain of 'or' or 'and'-shifted bits from a
  206. /// common source value:
  207. /// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0
  208. /// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
  209. /// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
  210. /// that differ only with a final 'not' of the result. We expect that final
  211. /// 'not' to be folded with the compare that we create here (invert predicate).
  212. static bool foldAnyOrAllBitsSet(Instruction &I) {
  213. // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
  214. // final "and X, 1" instruction must be the final op in the sequence.
  215. bool MatchAllBitsSet;
  216. if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value())))
  217. MatchAllBitsSet = true;
  218. else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One())))
  219. MatchAllBitsSet = false;
  220. else
  221. return false;
  222. MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
  223. if (MatchAllBitsSet) {
  224. if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1)
  225. return false;
  226. } else {
  227. if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps))
  228. return false;
  229. }
  230. // The pattern was found. Create a masked compare that replaces all of the
  231. // shift and logic ops.
  232. IRBuilder<> Builder(&I);
  233. Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask);
  234. Value *And = Builder.CreateAnd(MOps.Root, Mask);
  235. Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
  236. : Builder.CreateIsNotNull(And);
  237. Value *Zext = Builder.CreateZExt(Cmp, I.getType());
  238. I.replaceAllUsesWith(Zext);
  239. ++NumAnyOrAllBitsSet;
  240. return true;
  241. }
  242. // Try to recognize below function as popcount intrinsic.
  243. // This is the "best" algorithm from
  244. // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  245. // Also used in TargetLowering::expandCTPOP().
  246. //
  247. // int popcount(unsigned int i) {
  248. // i = i - ((i >> 1) & 0x55555555);
  249. // i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
  250. // i = ((i + (i >> 4)) & 0x0F0F0F0F);
  251. // return (i * 0x01010101) >> 24;
  252. // }
  253. static bool tryToRecognizePopCount(Instruction &I) {
  254. if (I.getOpcode() != Instruction::LShr)
  255. return false;
  256. Type *Ty = I.getType();
  257. if (!Ty->isIntOrIntVectorTy())
  258. return false;
  259. unsigned Len = Ty->getScalarSizeInBits();
  260. // FIXME: fix Len == 8 and other irregular type lengths.
  261. if (!(Len <= 128 && Len > 8 && Len % 8 == 0))
  262. return false;
  263. APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
  264. APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
  265. APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
  266. APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
  267. APInt MaskShift = APInt(Len, Len - 8);
  268. Value *Op0 = I.getOperand(0);
  269. Value *Op1 = I.getOperand(1);
  270. Value *MulOp0;
  271. // Matching "(i * 0x01010101...) >> 24".
  272. if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) &&
  273. match(Op1, m_SpecificInt(MaskShift))) {
  274. Value *ShiftOp0;
  275. // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)".
  276. if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)),
  277. m_Deferred(ShiftOp0)),
  278. m_SpecificInt(Mask0F)))) {
  279. Value *AndOp0;
  280. // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)".
  281. if (match(ShiftOp0,
  282. m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)),
  283. m_And(m_LShr(m_Deferred(AndOp0), m_SpecificInt(2)),
  284. m_SpecificInt(Mask33))))) {
  285. Value *Root, *SubOp1;
  286. // Matching "i - ((i >> 1) & 0x55555555...)".
  287. if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) &&
  288. match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)),
  289. m_SpecificInt(Mask55)))) {
  290. LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
  291. IRBuilder<> Builder(&I);
  292. Function *Func = Intrinsic::getDeclaration(
  293. I.getModule(), Intrinsic::ctpop, I.getType());
  294. I.replaceAllUsesWith(Builder.CreateCall(Func, {Root}));
  295. ++NumPopCountRecognized;
  296. return true;
  297. }
  298. }
  299. }
  300. }
  301. return false;
  302. }
  303. /// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
  304. /// C2 saturate the value of the fp conversion. The transform is not reversable
  305. /// as the fptosi.sat is more defined than the input - all values produce a
  306. /// valid value for the fptosi.sat, where as some produce poison for original
  307. /// that were out of range of the integer conversion. The reversed pattern may
  308. /// use fmax and fmin instead. As we cannot directly reverse the transform, and
  309. /// it is not always profitable, we make it conditional on the cost being
  310. /// reported as lower by TTI.
  311. static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI) {
  312. // Look for min(max(fptosi, converting to fptosi_sat.
  313. Value *In;
  314. const APInt *MinC, *MaxC;
  315. if (!match(&I, m_SMax(m_OneUse(m_SMin(m_OneUse(m_FPToSI(m_Value(In))),
  316. m_APInt(MinC))),
  317. m_APInt(MaxC))) &&
  318. !match(&I, m_SMin(m_OneUse(m_SMax(m_OneUse(m_FPToSI(m_Value(In))),
  319. m_APInt(MaxC))),
  320. m_APInt(MinC))))
  321. return false;
  322. // Check that the constants clamp a saturate.
  323. if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
  324. return false;
  325. Type *IntTy = I.getType();
  326. Type *FpTy = In->getType();
  327. Type *SatTy =
  328. IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
  329. if (auto *VecTy = dyn_cast<VectorType>(IntTy))
  330. SatTy = VectorType::get(SatTy, VecTy->getElementCount());
  331. // Get the cost of the intrinsic, and check that against the cost of
  332. // fptosi+smin+smax
  333. InstructionCost SatCost = TTI.getIntrinsicInstrCost(
  334. IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
  335. TTI::TCK_RecipThroughput);
  336. SatCost += TTI.getCastInstrCost(Instruction::SExt, SatTy, IntTy,
  337. TTI::CastContextHint::None,
  338. TTI::TCK_RecipThroughput);
  339. InstructionCost MinMaxCost = TTI.getCastInstrCost(
  340. Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
  341. TTI::TCK_RecipThroughput);
  342. MinMaxCost += TTI.getIntrinsicInstrCost(
  343. IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
  344. TTI::TCK_RecipThroughput);
  345. MinMaxCost += TTI.getIntrinsicInstrCost(
  346. IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
  347. TTI::TCK_RecipThroughput);
  348. if (SatCost >= MinMaxCost)
  349. return false;
  350. IRBuilder<> Builder(&I);
  351. Function *Fn = Intrinsic::getDeclaration(I.getModule(), Intrinsic::fptosi_sat,
  352. {SatTy, FpTy});
  353. Value *Sat = Builder.CreateCall(Fn, In);
  354. I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
  355. return true;
  356. }
  357. /// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
  358. /// pessimistic codegen that has to account for setting errno and can enable
  359. /// vectorization.
  360. static bool
  361. foldSqrt(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI) {
  362. // Match a call to sqrt mathlib function.
  363. auto *Call = dyn_cast<CallInst>(&I);
  364. if (!Call)
  365. return false;
  366. Module *M = Call->getModule();
  367. LibFunc Func;
  368. if (!TLI.getLibFunc(*Call, Func) || !isLibFuncEmittable(M, &TLI, Func))
  369. return false;
  370. if (Func != LibFunc_sqrt && Func != LibFunc_sqrtf && Func != LibFunc_sqrtl)
  371. return false;
  372. // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created
  373. // (because NNAN or the operand arg must not be less than -0.0) and (2) we
  374. // would not end up lowering to a libcall anyway (which could change the value
  375. // of errno), then:
  376. // (1) errno won't be set.
  377. // (2) it is safe to convert this to an intrinsic call.
  378. Type *Ty = Call->getType();
  379. Value *Arg = Call->getArgOperand(0);
  380. if (TTI.haveFastSqrt(Ty) &&
  381. (Call->hasNoNaNs() || CannotBeOrderedLessThanZero(Arg, &TLI))) {
  382. IRBuilder<> Builder(&I);
  383. IRBuilderBase::FastMathFlagGuard Guard(Builder);
  384. Builder.setFastMathFlags(Call->getFastMathFlags());
  385. Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, Ty);
  386. Value *NewSqrt = Builder.CreateCall(Sqrt, Arg, "sqrt");
  387. I.replaceAllUsesWith(NewSqrt);
  388. // Explicitly erase the old call because a call with side effects is not
  389. // trivially dead.
  390. I.eraseFromParent();
  391. return true;
  392. }
  393. return false;
  394. }
  395. // Check if this array of constants represents a cttz table.
  396. // Iterate over the elements from \p Table by trying to find/match all
  397. // the numbers from 0 to \p InputBits that should represent cttz results.
  398. static bool isCTTZTable(const ConstantDataArray &Table, uint64_t Mul,
  399. uint64_t Shift, uint64_t InputBits) {
  400. unsigned Length = Table.getNumElements();
  401. if (Length < InputBits || Length > InputBits * 2)
  402. return false;
  403. APInt Mask = APInt::getBitsSetFrom(InputBits, Shift);
  404. unsigned Matched = 0;
  405. for (unsigned i = 0; i < Length; i++) {
  406. uint64_t Element = Table.getElementAsInteger(i);
  407. if (Element >= InputBits)
  408. continue;
  409. // Check if \p Element matches a concrete answer. It could fail for some
  410. // elements that are never accessed, so we keep iterating over each element
  411. // from the table. The number of matched elements should be equal to the
  412. // number of potential right answers which is \p InputBits actually.
  413. if ((((Mul << Element) & Mask.getZExtValue()) >> Shift) == i)
  414. Matched++;
  415. }
  416. return Matched == InputBits;
  417. }
  418. // Try to recognize table-based ctz implementation.
  419. // E.g., an example in C (for more cases please see the llvm/tests):
  420. // int f(unsigned x) {
  421. // static const char table[32] =
  422. // {0, 1, 28, 2, 29, 14, 24, 3, 30,
  423. // 22, 20, 15, 25, 17, 4, 8, 31, 27,
  424. // 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
  425. // return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27];
  426. // }
  427. // this can be lowered to `cttz` instruction.
  428. // There is also a special case when the element is 0.
  429. //
  430. // Here are some examples or LLVM IR for a 64-bit target:
  431. //
  432. // CASE 1:
  433. // %sub = sub i32 0, %x
  434. // %and = and i32 %sub, %x
  435. // %mul = mul i32 %and, 125613361
  436. // %shr = lshr i32 %mul, 27
  437. // %idxprom = zext i32 %shr to i64
  438. // %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0,
  439. // i64 %idxprom %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
  440. //
  441. // CASE 2:
  442. // %sub = sub i32 0, %x
  443. // %and = and i32 %sub, %x
  444. // %mul = mul i32 %and, 72416175
  445. // %shr = lshr i32 %mul, 26
  446. // %idxprom = zext i32 %shr to i64
  447. // %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table, i64
  448. // 0, i64 %idxprom %0 = load i16, i16* %arrayidx, align 2, !tbaa !8
  449. //
  450. // CASE 3:
  451. // %sub = sub i32 0, %x
  452. // %and = and i32 %sub, %x
  453. // %mul = mul i32 %and, 81224991
  454. // %shr = lshr i32 %mul, 27
  455. // %idxprom = zext i32 %shr to i64
  456. // %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table, i64
  457. // 0, i64 %idxprom %0 = load i32, i32* %arrayidx, align 4, !tbaa !8
  458. //
  459. // CASE 4:
  460. // %sub = sub i64 0, %x
  461. // %and = and i64 %sub, %x
  462. // %mul = mul i64 %and, 283881067100198605
  463. // %shr = lshr i64 %mul, 58
  464. // %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0, i64
  465. // %shr %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
  466. //
  467. // All this can be lowered to @llvm.cttz.i32/64 intrinsic.
  468. static bool tryToRecognizeTableBasedCttz(Instruction &I) {
  469. LoadInst *LI = dyn_cast<LoadInst>(&I);
  470. if (!LI)
  471. return false;
  472. Type *AccessType = LI->getType();
  473. if (!AccessType->isIntegerTy())
  474. return false;
  475. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
  476. if (!GEP || !GEP->isInBounds() || GEP->getNumIndices() != 2)
  477. return false;
  478. if (!GEP->getSourceElementType()->isArrayTy())
  479. return false;
  480. uint64_t ArraySize = GEP->getSourceElementType()->getArrayNumElements();
  481. if (ArraySize != 32 && ArraySize != 64)
  482. return false;
  483. GlobalVariable *GVTable = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
  484. if (!GVTable || !GVTable->hasInitializer() || !GVTable->isConstant())
  485. return false;
  486. ConstantDataArray *ConstData =
  487. dyn_cast<ConstantDataArray>(GVTable->getInitializer());
  488. if (!ConstData)
  489. return false;
  490. if (!match(GEP->idx_begin()->get(), m_ZeroInt()))
  491. return false;
  492. Value *Idx2 = std::next(GEP->idx_begin())->get();
  493. Value *X1;
  494. uint64_t MulConst, ShiftConst;
  495. // FIXME: 64-bit targets have `i64` type for the GEP index, so this match will
  496. // probably fail for other (e.g. 32-bit) targets.
  497. if (!match(Idx2, m_ZExtOrSelf(
  498. m_LShr(m_Mul(m_c_And(m_Neg(m_Value(X1)), m_Deferred(X1)),
  499. m_ConstantInt(MulConst)),
  500. m_ConstantInt(ShiftConst)))))
  501. return false;
  502. unsigned InputBits = X1->getType()->getScalarSizeInBits();
  503. if (InputBits != 32 && InputBits != 64)
  504. return false;
  505. // Shift should extract top 5..7 bits.
  506. if (InputBits - Log2_32(InputBits) != ShiftConst &&
  507. InputBits - Log2_32(InputBits) - 1 != ShiftConst)
  508. return false;
  509. if (!isCTTZTable(*ConstData, MulConst, ShiftConst, InputBits))
  510. return false;
  511. auto ZeroTableElem = ConstData->getElementAsInteger(0);
  512. bool DefinedForZero = ZeroTableElem == InputBits;
  513. IRBuilder<> B(LI);
  514. ConstantInt *BoolConst = B.getInt1(!DefinedForZero);
  515. Type *XType = X1->getType();
  516. auto Cttz = B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
  517. Value *ZExtOrTrunc = nullptr;
  518. if (DefinedForZero) {
  519. ZExtOrTrunc = B.CreateZExtOrTrunc(Cttz, AccessType);
  520. } else {
  521. // If the value in elem 0 isn't the same as InputBits, we still want to
  522. // produce the value from the table.
  523. auto Cmp = B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
  524. auto Select =
  525. B.CreateSelect(Cmp, ConstantInt::get(XType, ZeroTableElem), Cttz);
  526. // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target
  527. // it should be handled as: `cttz(x) & (typeSize - 1)`.
  528. ZExtOrTrunc = B.CreateZExtOrTrunc(Select, AccessType);
  529. }
  530. LI->replaceAllUsesWith(ZExtOrTrunc);
  531. return true;
  532. }
  533. /// This is used by foldLoadsRecursive() to capture a Root Load node which is
  534. /// of type or(load, load) and recursively build the wide load. Also capture the
  535. /// shift amount, zero extend type and loadSize.
  536. struct LoadOps {
  537. LoadInst *Root = nullptr;
  538. LoadInst *RootInsert = nullptr;
  539. bool FoundRoot = false;
  540. uint64_t LoadSize = 0;
  541. Value *Shift = nullptr;
  542. Type *ZextType;
  543. AAMDNodes AATags;
  544. };
  545. // Identify and Merge consecutive loads recursively which is of the form
  546. // (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1
  547. // (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3)
  548. static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL,
  549. AliasAnalysis &AA) {
  550. Value *ShAmt2 = nullptr;
  551. Value *X;
  552. Instruction *L1, *L2;
  553. // Go to the last node with loads.
  554. if (match(V, m_OneUse(m_c_Or(
  555. m_Value(X),
  556. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_OneUse(m_Instruction(L2)))),
  557. m_Value(ShAmt2)))))) ||
  558. match(V, m_OneUse(m_Or(m_Value(X),
  559. m_OneUse(m_ZExt(m_OneUse(m_Instruction(L2)))))))) {
  560. if (!foldLoadsRecursive(X, LOps, DL, AA) && LOps.FoundRoot)
  561. // Avoid Partial chain merge.
  562. return false;
  563. } else
  564. return false;
  565. // Check if the pattern has loads
  566. LoadInst *LI1 = LOps.Root;
  567. Value *ShAmt1 = LOps.Shift;
  568. if (LOps.FoundRoot == false &&
  569. (match(X, m_OneUse(m_ZExt(m_Instruction(L1)))) ||
  570. match(X, m_OneUse(m_Shl(m_OneUse(m_ZExt(m_OneUse(m_Instruction(L1)))),
  571. m_Value(ShAmt1)))))) {
  572. LI1 = dyn_cast<LoadInst>(L1);
  573. }
  574. LoadInst *LI2 = dyn_cast<LoadInst>(L2);
  575. // Check if loads are same, atomic, volatile and having same address space.
  576. if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() ||
  577. LI1->getPointerAddressSpace() != LI2->getPointerAddressSpace())
  578. return false;
  579. // Check if Loads come from same BB.
  580. if (LI1->getParent() != LI2->getParent())
  581. return false;
  582. // Find the data layout
  583. bool IsBigEndian = DL.isBigEndian();
  584. // Check if loads are consecutive and same size.
  585. Value *Load1Ptr = LI1->getPointerOperand();
  586. APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
  587. Load1Ptr =
  588. Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset1,
  589. /* AllowNonInbounds */ true);
  590. Value *Load2Ptr = LI2->getPointerOperand();
  591. APInt Offset2(DL.getIndexTypeSizeInBits(Load2Ptr->getType()), 0);
  592. Load2Ptr =
  593. Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset2,
  594. /* AllowNonInbounds */ true);
  595. // Verify if both loads have same base pointers and load sizes are same.
  596. uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits();
  597. uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits();
  598. if (Load1Ptr != Load2Ptr || LoadSize1 != LoadSize2)
  599. return false;
  600. // Support Loadsizes greater or equal to 8bits and only power of 2.
  601. if (LoadSize1 < 8 || !isPowerOf2_64(LoadSize1))
  602. return false;
  603. // Alias Analysis to check for stores b/w the loads.
  604. LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2;
  605. MemoryLocation Loc;
  606. if (!Start->comesBefore(End)) {
  607. std::swap(Start, End);
  608. Loc = MemoryLocation::get(End);
  609. if (LOps.FoundRoot)
  610. Loc = Loc.getWithNewSize(LOps.LoadSize);
  611. } else
  612. Loc = MemoryLocation::get(End);
  613. unsigned NumScanned = 0;
  614. for (Instruction &Inst :
  615. make_range(Start->getIterator(), End->getIterator())) {
  616. if (Inst.mayWriteToMemory() && isModSet(AA.getModRefInfo(&Inst, Loc)))
  617. return false;
  618. if (++NumScanned > MaxInstrsToScan)
  619. return false;
  620. }
  621. // Make sure Load with lower Offset is at LI1
  622. bool Reverse = false;
  623. if (Offset2.slt(Offset1)) {
  624. std::swap(LI1, LI2);
  625. std::swap(ShAmt1, ShAmt2);
  626. std::swap(Offset1, Offset2);
  627. std::swap(Load1Ptr, Load2Ptr);
  628. std::swap(LoadSize1, LoadSize2);
  629. Reverse = true;
  630. }
  631. // Big endian swap the shifts
  632. if (IsBigEndian)
  633. std::swap(ShAmt1, ShAmt2);
  634. // Find Shifts values.
  635. const APInt *Temp;
  636. uint64_t Shift1 = 0, Shift2 = 0;
  637. if (ShAmt1 && match(ShAmt1, m_APInt(Temp)))
  638. Shift1 = Temp->getZExtValue();
  639. if (ShAmt2 && match(ShAmt2, m_APInt(Temp)))
  640. Shift2 = Temp->getZExtValue();
  641. // First load is always LI1. This is where we put the new load.
  642. // Use the merged load size available from LI1 for forward loads.
  643. if (LOps.FoundRoot) {
  644. if (!Reverse)
  645. LoadSize1 = LOps.LoadSize;
  646. else
  647. LoadSize2 = LOps.LoadSize;
  648. }
  649. // Verify if shift amount and load index aligns and verifies that loads
  650. // are consecutive.
  651. uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
  652. uint64_t PrevSize =
  653. DL.getTypeStoreSize(IntegerType::get(LI1->getContext(), LoadSize1));
  654. if ((Shift2 - Shift1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
  655. return false;
  656. // Update LOps
  657. AAMDNodes AATags1 = LOps.AATags;
  658. AAMDNodes AATags2 = LI2->getAAMetadata();
  659. if (LOps.FoundRoot == false) {
  660. LOps.FoundRoot = true;
  661. AATags1 = LI1->getAAMetadata();
  662. }
  663. LOps.LoadSize = LoadSize1 + LoadSize2;
  664. LOps.RootInsert = Start;
  665. // Concatenate the AATags of the Merged Loads.
  666. LOps.AATags = AATags1.concat(AATags2);
  667. LOps.Root = LI1;
  668. LOps.Shift = ShAmt1;
  669. LOps.ZextType = X->getType();
  670. return true;
  671. }
  672. // For a given BB instruction, evaluate all loads in the chain that form a
  673. // pattern which suggests that the loads can be combined. The one and only use
  674. // of the loads is to form a wider load.
  675. static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL,
  676. TargetTransformInfo &TTI, AliasAnalysis &AA) {
  677. // Only consider load chains of scalar values.
  678. if (isa<VectorType>(I.getType()))
  679. return false;
  680. LoadOps LOps;
  681. if (!foldLoadsRecursive(&I, LOps, DL, AA) || !LOps.FoundRoot)
  682. return false;
  683. IRBuilder<> Builder(&I);
  684. LoadInst *NewLoad = nullptr, *LI1 = LOps.Root;
  685. IntegerType *WiderType = IntegerType::get(I.getContext(), LOps.LoadSize);
  686. // TTI based checks if we want to proceed with wider load
  687. bool Allowed = TTI.isTypeLegal(WiderType);
  688. if (!Allowed)
  689. return false;
  690. unsigned AS = LI1->getPointerAddressSpace();
  691. unsigned Fast = 0;
  692. Allowed = TTI.allowsMisalignedMemoryAccesses(I.getContext(), LOps.LoadSize,
  693. AS, LI1->getAlign(), &Fast);
  694. if (!Allowed || !Fast)
  695. return false;
  696. // Make sure the Load pointer of type GEP/non-GEP is above insert point
  697. Instruction *Inst = dyn_cast<Instruction>(LI1->getPointerOperand());
  698. if (Inst && Inst->getParent() == LI1->getParent() &&
  699. !Inst->comesBefore(LOps.RootInsert))
  700. Inst->moveBefore(LOps.RootInsert);
  701. // New load can be generated
  702. Value *Load1Ptr = LI1->getPointerOperand();
  703. Builder.SetInsertPoint(LOps.RootInsert);
  704. Value *NewPtr = Builder.CreateBitCast(Load1Ptr, WiderType->getPointerTo(AS));
  705. NewLoad = Builder.CreateAlignedLoad(WiderType, NewPtr, LI1->getAlign(),
  706. LI1->isVolatile(), "");
  707. NewLoad->takeName(LI1);
  708. // Set the New Load AATags Metadata.
  709. if (LOps.AATags)
  710. NewLoad->setAAMetadata(LOps.AATags);
  711. Value *NewOp = NewLoad;
  712. // Check if zero extend needed.
  713. if (LOps.ZextType)
  714. NewOp = Builder.CreateZExt(NewOp, LOps.ZextType);
  715. // Check if shift needed. We need to shift with the amount of load1
  716. // shift if not zero.
  717. if (LOps.Shift)
  718. NewOp = Builder.CreateShl(NewOp, LOps.Shift);
  719. I.replaceAllUsesWith(NewOp);
  720. return true;
  721. }
  722. /// This is the entry point for folds that could be implemented in regular
  723. /// InstCombine, but they are separated because they are not expected to
  724. /// occur frequently and/or have more than a constant-length pattern match.
  725. static bool foldUnusualPatterns(Function &F, DominatorTree &DT,
  726. TargetTransformInfo &TTI,
  727. TargetLibraryInfo &TLI, AliasAnalysis &AA) {
  728. bool MadeChange = false;
  729. for (BasicBlock &BB : F) {
  730. // Ignore unreachable basic blocks.
  731. if (!DT.isReachableFromEntry(&BB))
  732. continue;
  733. const DataLayout &DL = F.getParent()->getDataLayout();
  734. // Walk the block backwards for efficiency. We're matching a chain of
  735. // use->defs, so we're more likely to succeed by starting from the bottom.
  736. // Also, we want to avoid matching partial patterns.
  737. // TODO: It would be more efficient if we removed dead instructions
  738. // iteratively in this loop rather than waiting until the end.
  739. for (Instruction &I : make_early_inc_range(llvm::reverse(BB))) {
  740. MadeChange |= foldAnyOrAllBitsSet(I);
  741. MadeChange |= foldGuardedFunnelShift(I, DT);
  742. MadeChange |= tryToRecognizePopCount(I);
  743. MadeChange |= tryToFPToSat(I, TTI);
  744. MadeChange |= tryToRecognizeTableBasedCttz(I);
  745. MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA);
  746. // NOTE: This function introduces erasing of the instruction `I`, so it
  747. // needs to be called at the end of this sequence, otherwise we may make
  748. // bugs.
  749. MadeChange |= foldSqrt(I, TTI, TLI);
  750. }
  751. }
  752. // We're done with transforms, so remove dead instructions.
  753. if (MadeChange)
  754. for (BasicBlock &BB : F)
  755. SimplifyInstructionsInBlock(&BB);
  756. return MadeChange;
  757. }
  758. /// This is the entry point for all transforms. Pass manager differences are
  759. /// handled in the callers of this function.
  760. static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI,
  761. TargetLibraryInfo &TLI, DominatorTree &DT,
  762. AliasAnalysis &AA) {
  763. bool MadeChange = false;
  764. const DataLayout &DL = F.getParent()->getDataLayout();
  765. TruncInstCombine TIC(AC, TLI, DL, DT);
  766. MadeChange |= TIC.run(F);
  767. MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA);
  768. return MadeChange;
  769. }
  770. PreservedAnalyses AggressiveInstCombinePass::run(Function &F,
  771. FunctionAnalysisManager &AM) {
  772. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  773. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  774. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  775. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  776. auto &AA = AM.getResult<AAManager>(F);
  777. if (!runImpl(F, AC, TTI, TLI, DT, AA)) {
  778. // No changes, all analyses are preserved.
  779. return PreservedAnalyses::all();
  780. }
  781. // Mark all the analyses that instcombine updates as preserved.
  782. PreservedAnalyses PA;
  783. PA.preserveSet<CFGAnalyses>();
  784. return PA;
  785. }