X86PartialReduction.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. //===-- X86PartialReduction.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 pass looks for add instructions used by a horizontal reduction to see
  10. // if we might be able to use pmaddwd or psadbw. Some cases of this require
  11. // cross basic block knowledge and can't be done in SelectionDAG.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "X86.h"
  15. #include "X86TargetMachine.h"
  16. #include "llvm/Analysis/ValueTracking.h"
  17. #include "llvm/CodeGen/TargetPassConfig.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/IntrinsicsX86.h"
  22. #include "llvm/IR/Operator.h"
  23. #include "llvm/Pass.h"
  24. #include "llvm/Support/KnownBits.h"
  25. using namespace llvm;
  26. #define DEBUG_TYPE "x86-partial-reduction"
  27. namespace {
  28. class X86PartialReduction : public FunctionPass {
  29. const DataLayout *DL;
  30. const X86Subtarget *ST;
  31. public:
  32. static char ID; // Pass identification, replacement for typeid.
  33. X86PartialReduction() : FunctionPass(ID) { }
  34. bool runOnFunction(Function &Fn) override;
  35. void getAnalysisUsage(AnalysisUsage &AU) const override {
  36. AU.setPreservesCFG();
  37. }
  38. StringRef getPassName() const override {
  39. return "X86 Partial Reduction";
  40. }
  41. private:
  42. bool tryMAddReplacement(Instruction *Op, bool ReduceInOneBB);
  43. bool trySADReplacement(Instruction *Op);
  44. };
  45. }
  46. FunctionPass *llvm::createX86PartialReductionPass() {
  47. return new X86PartialReduction();
  48. }
  49. char X86PartialReduction::ID = 0;
  50. INITIALIZE_PASS(X86PartialReduction, DEBUG_TYPE,
  51. "X86 Partial Reduction", false, false)
  52. // This function should be aligned with detectExtMul() in X86ISelLowering.cpp.
  53. static bool matchVPDPBUSDPattern(const X86Subtarget *ST, BinaryOperator *Mul,
  54. const DataLayout *DL) {
  55. if (!ST->hasVNNI() && !ST->hasAVXVNNI())
  56. return false;
  57. Value *LHS = Mul->getOperand(0);
  58. Value *RHS = Mul->getOperand(1);
  59. if (isa<SExtInst>(LHS))
  60. std::swap(LHS, RHS);
  61. auto IsFreeTruncation = [&](Value *Op) {
  62. if (auto *Cast = dyn_cast<CastInst>(Op)) {
  63. if (Cast->getParent() == Mul->getParent() &&
  64. (Cast->getOpcode() == Instruction::SExt ||
  65. Cast->getOpcode() == Instruction::ZExt) &&
  66. Cast->getOperand(0)->getType()->getScalarSizeInBits() <= 8)
  67. return true;
  68. }
  69. return isa<Constant>(Op);
  70. };
  71. // (dpbusd (zext a), (sext, b)). Since the first operand should be unsigned
  72. // value, we need to check LHS is zero extended value. RHS should be signed
  73. // value, so we just check the signed bits.
  74. if ((IsFreeTruncation(LHS) &&
  75. computeKnownBits(LHS, *DL).countMaxActiveBits() <= 8) &&
  76. (IsFreeTruncation(RHS) && ComputeMaxSignificantBits(RHS, *DL) <= 8))
  77. return true;
  78. return false;
  79. }
  80. bool X86PartialReduction::tryMAddReplacement(Instruction *Op,
  81. bool ReduceInOneBB) {
  82. if (!ST->hasSSE2())
  83. return false;
  84. // Need at least 8 elements.
  85. if (cast<FixedVectorType>(Op->getType())->getNumElements() < 8)
  86. return false;
  87. // Element type should be i32.
  88. if (!cast<VectorType>(Op->getType())->getElementType()->isIntegerTy(32))
  89. return false;
  90. auto *Mul = dyn_cast<BinaryOperator>(Op);
  91. if (!Mul || Mul->getOpcode() != Instruction::Mul)
  92. return false;
  93. Value *LHS = Mul->getOperand(0);
  94. Value *RHS = Mul->getOperand(1);
  95. // If the target support VNNI, leave it to ISel to combine reduce operation
  96. // to VNNI instruction.
  97. // TODO: we can support transforming reduce to VNNI intrinsic for across block
  98. // in this pass.
  99. if (ReduceInOneBB && matchVPDPBUSDPattern(ST, Mul, DL))
  100. return false;
  101. // LHS and RHS should be only used once or if they are the same then only
  102. // used twice. Only check this when SSE4.1 is enabled and we have zext/sext
  103. // instructions, otherwise we use punpck to emulate zero extend in stages. The
  104. // trunc/ we need to do likely won't introduce new instructions in that case.
  105. if (ST->hasSSE41()) {
  106. if (LHS == RHS) {
  107. if (!isa<Constant>(LHS) && !LHS->hasNUses(2))
  108. return false;
  109. } else {
  110. if (!isa<Constant>(LHS) && !LHS->hasOneUse())
  111. return false;
  112. if (!isa<Constant>(RHS) && !RHS->hasOneUse())
  113. return false;
  114. }
  115. }
  116. auto CanShrinkOp = [&](Value *Op) {
  117. auto IsFreeTruncation = [&](Value *Op) {
  118. if (auto *Cast = dyn_cast<CastInst>(Op)) {
  119. if (Cast->getParent() == Mul->getParent() &&
  120. (Cast->getOpcode() == Instruction::SExt ||
  121. Cast->getOpcode() == Instruction::ZExt) &&
  122. Cast->getOperand(0)->getType()->getScalarSizeInBits() <= 16)
  123. return true;
  124. }
  125. return isa<Constant>(Op);
  126. };
  127. // If the operation can be freely truncated and has enough sign bits we
  128. // can shrink.
  129. if (IsFreeTruncation(Op) &&
  130. ComputeNumSignBits(Op, *DL, 0, nullptr, Mul) > 16)
  131. return true;
  132. // SelectionDAG has limited support for truncating through an add or sub if
  133. // the inputs are freely truncatable.
  134. if (auto *BO = dyn_cast<BinaryOperator>(Op)) {
  135. if (BO->getParent() == Mul->getParent() &&
  136. IsFreeTruncation(BO->getOperand(0)) &&
  137. IsFreeTruncation(BO->getOperand(1)) &&
  138. ComputeNumSignBits(Op, *DL, 0, nullptr, Mul) > 16)
  139. return true;
  140. }
  141. return false;
  142. };
  143. // Both Ops need to be shrinkable.
  144. if (!CanShrinkOp(LHS) && !CanShrinkOp(RHS))
  145. return false;
  146. IRBuilder<> Builder(Mul);
  147. auto *MulTy = cast<FixedVectorType>(Op->getType());
  148. unsigned NumElts = MulTy->getNumElements();
  149. // Extract even elements and odd elements and add them together. This will
  150. // be pattern matched by SelectionDAG to pmaddwd. This instruction will be
  151. // half the original width.
  152. SmallVector<int, 16> EvenMask(NumElts / 2);
  153. SmallVector<int, 16> OddMask(NumElts / 2);
  154. for (int i = 0, e = NumElts / 2; i != e; ++i) {
  155. EvenMask[i] = i * 2;
  156. OddMask[i] = i * 2 + 1;
  157. }
  158. // Creating a new mul so the replaceAllUsesWith below doesn't replace the
  159. // uses in the shuffles we're creating.
  160. Value *NewMul = Builder.CreateMul(Mul->getOperand(0), Mul->getOperand(1));
  161. Value *EvenElts = Builder.CreateShuffleVector(NewMul, NewMul, EvenMask);
  162. Value *OddElts = Builder.CreateShuffleVector(NewMul, NewMul, OddMask);
  163. Value *MAdd = Builder.CreateAdd(EvenElts, OddElts);
  164. // Concatenate zeroes to extend back to the original type.
  165. SmallVector<int, 32> ConcatMask(NumElts);
  166. std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
  167. Value *Zero = Constant::getNullValue(MAdd->getType());
  168. Value *Concat = Builder.CreateShuffleVector(MAdd, Zero, ConcatMask);
  169. Mul->replaceAllUsesWith(Concat);
  170. Mul->eraseFromParent();
  171. return true;
  172. }
  173. bool X86PartialReduction::trySADReplacement(Instruction *Op) {
  174. if (!ST->hasSSE2())
  175. return false;
  176. // TODO: There's nothing special about i32, any integer type above i16 should
  177. // work just as well.
  178. if (!cast<VectorType>(Op->getType())->getElementType()->isIntegerTy(32))
  179. return false;
  180. // Operand should be a select.
  181. auto *SI = dyn_cast<SelectInst>(Op);
  182. if (!SI)
  183. return false;
  184. // Select needs to implement absolute value.
  185. Value *LHS, *RHS;
  186. auto SPR = matchSelectPattern(SI, LHS, RHS);
  187. if (SPR.Flavor != SPF_ABS)
  188. return false;
  189. // Need a subtract of two values.
  190. auto *Sub = dyn_cast<BinaryOperator>(LHS);
  191. if (!Sub || Sub->getOpcode() != Instruction::Sub)
  192. return false;
  193. // Look for zero extend from i8.
  194. auto getZeroExtendedVal = [](Value *Op) -> Value * {
  195. if (auto *ZExt = dyn_cast<ZExtInst>(Op))
  196. if (cast<VectorType>(ZExt->getOperand(0)->getType())
  197. ->getElementType()
  198. ->isIntegerTy(8))
  199. return ZExt->getOperand(0);
  200. return nullptr;
  201. };
  202. // Both operands of the subtract should be extends from vXi8.
  203. Value *Op0 = getZeroExtendedVal(Sub->getOperand(0));
  204. Value *Op1 = getZeroExtendedVal(Sub->getOperand(1));
  205. if (!Op0 || !Op1)
  206. return false;
  207. IRBuilder<> Builder(SI);
  208. auto *OpTy = cast<FixedVectorType>(Op->getType());
  209. unsigned NumElts = OpTy->getNumElements();
  210. unsigned IntrinsicNumElts;
  211. Intrinsic::ID IID;
  212. if (ST->hasBWI() && NumElts >= 64) {
  213. IID = Intrinsic::x86_avx512_psad_bw_512;
  214. IntrinsicNumElts = 64;
  215. } else if (ST->hasAVX2() && NumElts >= 32) {
  216. IID = Intrinsic::x86_avx2_psad_bw;
  217. IntrinsicNumElts = 32;
  218. } else {
  219. IID = Intrinsic::x86_sse2_psad_bw;
  220. IntrinsicNumElts = 16;
  221. }
  222. Function *PSADBWFn = Intrinsic::getDeclaration(SI->getModule(), IID);
  223. if (NumElts < 16) {
  224. // Pad input with zeroes.
  225. SmallVector<int, 32> ConcatMask(16);
  226. for (unsigned i = 0; i != NumElts; ++i)
  227. ConcatMask[i] = i;
  228. for (unsigned i = NumElts; i != 16; ++i)
  229. ConcatMask[i] = (i % NumElts) + NumElts;
  230. Value *Zero = Constant::getNullValue(Op0->getType());
  231. Op0 = Builder.CreateShuffleVector(Op0, Zero, ConcatMask);
  232. Op1 = Builder.CreateShuffleVector(Op1, Zero, ConcatMask);
  233. NumElts = 16;
  234. }
  235. // Intrinsics produce vXi64 and need to be casted to vXi32.
  236. auto *I32Ty =
  237. FixedVectorType::get(Builder.getInt32Ty(), IntrinsicNumElts / 4);
  238. assert(NumElts % IntrinsicNumElts == 0 && "Unexpected number of elements!");
  239. unsigned NumSplits = NumElts / IntrinsicNumElts;
  240. // First collect the pieces we need.
  241. SmallVector<Value *, 4> Ops(NumSplits);
  242. for (unsigned i = 0; i != NumSplits; ++i) {
  243. SmallVector<int, 64> ExtractMask(IntrinsicNumElts);
  244. std::iota(ExtractMask.begin(), ExtractMask.end(), i * IntrinsicNumElts);
  245. Value *ExtractOp0 = Builder.CreateShuffleVector(Op0, Op0, ExtractMask);
  246. Value *ExtractOp1 = Builder.CreateShuffleVector(Op1, Op0, ExtractMask);
  247. Ops[i] = Builder.CreateCall(PSADBWFn, {ExtractOp0, ExtractOp1});
  248. Ops[i] = Builder.CreateBitCast(Ops[i], I32Ty);
  249. }
  250. assert(isPowerOf2_32(NumSplits) && "Expected power of 2 splits");
  251. unsigned Stages = Log2_32(NumSplits);
  252. for (unsigned s = Stages; s > 0; --s) {
  253. unsigned NumConcatElts =
  254. cast<FixedVectorType>(Ops[0]->getType())->getNumElements() * 2;
  255. for (unsigned i = 0; i != 1U << (s - 1); ++i) {
  256. SmallVector<int, 64> ConcatMask(NumConcatElts);
  257. std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
  258. Ops[i] = Builder.CreateShuffleVector(Ops[i*2], Ops[i*2+1], ConcatMask);
  259. }
  260. }
  261. // At this point the final value should be in Ops[0]. Now we need to adjust
  262. // it to the final original type.
  263. NumElts = cast<FixedVectorType>(OpTy)->getNumElements();
  264. if (NumElts == 2) {
  265. // Extract down to 2 elements.
  266. Ops[0] = Builder.CreateShuffleVector(Ops[0], Ops[0], ArrayRef<int>{0, 1});
  267. } else if (NumElts >= 8) {
  268. SmallVector<int, 32> ConcatMask(NumElts);
  269. unsigned SubElts =
  270. cast<FixedVectorType>(Ops[0]->getType())->getNumElements();
  271. for (unsigned i = 0; i != SubElts; ++i)
  272. ConcatMask[i] = i;
  273. for (unsigned i = SubElts; i != NumElts; ++i)
  274. ConcatMask[i] = (i % SubElts) + SubElts;
  275. Value *Zero = Constant::getNullValue(Ops[0]->getType());
  276. Ops[0] = Builder.CreateShuffleVector(Ops[0], Zero, ConcatMask);
  277. }
  278. SI->replaceAllUsesWith(Ops[0]);
  279. SI->eraseFromParent();
  280. return true;
  281. }
  282. // Walk backwards from the ExtractElementInst and determine if it is the end of
  283. // a horizontal reduction. Return the input to the reduction if we find one.
  284. static Value *matchAddReduction(const ExtractElementInst &EE,
  285. bool &ReduceInOneBB) {
  286. ReduceInOneBB = true;
  287. // Make sure we're extracting index 0.
  288. auto *Index = dyn_cast<ConstantInt>(EE.getIndexOperand());
  289. if (!Index || !Index->isNullValue())
  290. return nullptr;
  291. const auto *BO = dyn_cast<BinaryOperator>(EE.getVectorOperand());
  292. if (!BO || BO->getOpcode() != Instruction::Add || !BO->hasOneUse())
  293. return nullptr;
  294. if (EE.getParent() != BO->getParent())
  295. ReduceInOneBB = false;
  296. unsigned NumElems = cast<FixedVectorType>(BO->getType())->getNumElements();
  297. // Ensure the reduction size is a power of 2.
  298. if (!isPowerOf2_32(NumElems))
  299. return nullptr;
  300. const Value *Op = BO;
  301. unsigned Stages = Log2_32(NumElems);
  302. for (unsigned i = 0; i != Stages; ++i) {
  303. const auto *BO = dyn_cast<BinaryOperator>(Op);
  304. if (!BO || BO->getOpcode() != Instruction::Add)
  305. return nullptr;
  306. if (EE.getParent() != BO->getParent())
  307. ReduceInOneBB = false;
  308. // If this isn't the first add, then it should only have 2 users, the
  309. // shuffle and another add which we checked in the previous iteration.
  310. if (i != 0 && !BO->hasNUses(2))
  311. return nullptr;
  312. Value *LHS = BO->getOperand(0);
  313. Value *RHS = BO->getOperand(1);
  314. auto *Shuffle = dyn_cast<ShuffleVectorInst>(LHS);
  315. if (Shuffle) {
  316. Op = RHS;
  317. } else {
  318. Shuffle = dyn_cast<ShuffleVectorInst>(RHS);
  319. Op = LHS;
  320. }
  321. // The first operand of the shuffle should be the same as the other operand
  322. // of the bin op.
  323. if (!Shuffle || Shuffle->getOperand(0) != Op)
  324. return nullptr;
  325. // Verify the shuffle has the expected (at this stage of the pyramid) mask.
  326. unsigned MaskEnd = 1 << i;
  327. for (unsigned Index = 0; Index < MaskEnd; ++Index)
  328. if (Shuffle->getMaskValue(Index) != (int)(MaskEnd + Index))
  329. return nullptr;
  330. }
  331. return const_cast<Value *>(Op);
  332. }
  333. // See if this BO is reachable from this Phi by walking forward through single
  334. // use BinaryOperators with the same opcode. If we get back then we know we've
  335. // found a loop and it is safe to step through this Add to find more leaves.
  336. static bool isReachableFromPHI(PHINode *Phi, BinaryOperator *BO) {
  337. // The PHI itself should only have one use.
  338. if (!Phi->hasOneUse())
  339. return false;
  340. Instruction *U = cast<Instruction>(*Phi->user_begin());
  341. if (U == BO)
  342. return true;
  343. while (U->hasOneUse() && U->getOpcode() == BO->getOpcode())
  344. U = cast<Instruction>(*U->user_begin());
  345. return U == BO;
  346. }
  347. // Collect all the leaves of the tree of adds that feeds into the horizontal
  348. // reduction. Root is the Value that is used by the horizontal reduction.
  349. // We look through single use phis, single use adds, or adds that are used by
  350. // a phi that forms a loop with the add.
  351. static void collectLeaves(Value *Root, SmallVectorImpl<Instruction *> &Leaves) {
  352. SmallPtrSet<Value *, 8> Visited;
  353. SmallVector<Value *, 8> Worklist;
  354. Worklist.push_back(Root);
  355. while (!Worklist.empty()) {
  356. Value *V = Worklist.pop_back_val();
  357. if (!Visited.insert(V).second)
  358. continue;
  359. if (auto *PN = dyn_cast<PHINode>(V)) {
  360. // PHI node should have single use unless it is the root node, then it
  361. // has 2 uses.
  362. if (!PN->hasNUses(PN == Root ? 2 : 1))
  363. break;
  364. // Push incoming values to the worklist.
  365. append_range(Worklist, PN->incoming_values());
  366. continue;
  367. }
  368. if (auto *BO = dyn_cast<BinaryOperator>(V)) {
  369. if (BO->getOpcode() == Instruction::Add) {
  370. // Simple case. Single use, just push its operands to the worklist.
  371. if (BO->hasNUses(BO == Root ? 2 : 1)) {
  372. append_range(Worklist, BO->operands());
  373. continue;
  374. }
  375. // If there is additional use, make sure it is an unvisited phi that
  376. // gets us back to this node.
  377. if (BO->hasNUses(BO == Root ? 3 : 2)) {
  378. PHINode *PN = nullptr;
  379. for (auto *U : Root->users())
  380. if (auto *P = dyn_cast<PHINode>(U))
  381. if (!Visited.count(P))
  382. PN = P;
  383. // If we didn't find a 2-input PHI then this isn't a case we can
  384. // handle.
  385. if (!PN || PN->getNumIncomingValues() != 2)
  386. continue;
  387. // Walk forward from this phi to see if it reaches back to this add.
  388. if (!isReachableFromPHI(PN, BO))
  389. continue;
  390. // The phi forms a loop with this Add, push its operands.
  391. append_range(Worklist, BO->operands());
  392. }
  393. }
  394. }
  395. // Not an add or phi, make it a leaf.
  396. if (auto *I = dyn_cast<Instruction>(V)) {
  397. if (!V->hasNUses(I == Root ? 2 : 1))
  398. continue;
  399. // Add this as a leaf.
  400. Leaves.push_back(I);
  401. }
  402. }
  403. }
  404. bool X86PartialReduction::runOnFunction(Function &F) {
  405. if (skipFunction(F))
  406. return false;
  407. auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
  408. if (!TPC)
  409. return false;
  410. auto &TM = TPC->getTM<X86TargetMachine>();
  411. ST = TM.getSubtargetImpl(F);
  412. DL = &F.getParent()->getDataLayout();
  413. bool MadeChange = false;
  414. for (auto &BB : F) {
  415. for (auto &I : BB) {
  416. auto *EE = dyn_cast<ExtractElementInst>(&I);
  417. if (!EE)
  418. continue;
  419. bool ReduceInOneBB;
  420. // First find a reduction tree.
  421. // FIXME: Do we need to handle other opcodes than Add?
  422. Value *Root = matchAddReduction(*EE, ReduceInOneBB);
  423. if (!Root)
  424. continue;
  425. SmallVector<Instruction *, 8> Leaves;
  426. collectLeaves(Root, Leaves);
  427. for (Instruction *I : Leaves) {
  428. if (tryMAddReplacement(I, ReduceInOneBB)) {
  429. MadeChange = true;
  430. continue;
  431. }
  432. // Don't do SAD matching on the root node. SelectionDAG already
  433. // has support for that and currently generates better code.
  434. if (I != Root && trySADReplacement(I))
  435. MadeChange = true;
  436. }
  437. }
  438. }
  439. return MadeChange;
  440. }