VPlanSLP.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. //===- VPlanSLP.cpp - SLP Analysis based on VPlan -------------------------===//
  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. /// This file implements SLP analysis based on VPlan. The analysis is based on
  9. /// the ideas described in
  10. ///
  11. /// Look-ahead SLP: auto-vectorization in the presence of commutative
  12. /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
  13. /// Luís F. W. Góes
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #include "VPlan.h"
  17. #include "llvm/ADT/DepthFirstIterator.h"
  18. #include "llvm/ADT/PostOrderIterator.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/Analysis/LoopInfo.h"
  22. #include "llvm/Analysis/VectorUtils.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/CFG.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/InstrTypes.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/Type.h"
  30. #include "llvm/IR/Value.h"
  31. #include "llvm/Support/Casting.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/GraphWriter.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  37. #include <cassert>
  38. #include <iterator>
  39. #include <string>
  40. #include <vector>
  41. using namespace llvm;
  42. #define DEBUG_TYPE "vplan-slp"
  43. // Number of levels to look ahead when re-ordering multi node operands.
  44. static unsigned LookaheadMaxDepth = 5;
  45. VPInstruction *VPlanSlp::markFailed() {
  46. // FIXME: Currently this is used to signal we hit instructions we cannot
  47. // trivially SLP'ize.
  48. CompletelySLP = false;
  49. return nullptr;
  50. }
  51. void VPlanSlp::addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New) {
  52. if (all_of(Operands, [](VPValue *V) {
  53. return cast<VPInstruction>(V)->getUnderlyingInstr();
  54. })) {
  55. unsigned BundleSize = 0;
  56. for (VPValue *V : Operands) {
  57. Type *T = cast<VPInstruction>(V)->getUnderlyingInstr()->getType();
  58. assert(!T->isVectorTy() && "Only scalar types supported for now");
  59. BundleSize += T->getScalarSizeInBits();
  60. }
  61. WidestBundleBits = std::max(WidestBundleBits, BundleSize);
  62. }
  63. auto Res = BundleToCombined.try_emplace(to_vector<4>(Operands), New);
  64. assert(Res.second &&
  65. "Already created a combined instruction for the operand bundle");
  66. (void)Res;
  67. }
  68. bool VPlanSlp::areVectorizable(ArrayRef<VPValue *> Operands) const {
  69. // Currently we only support VPInstructions.
  70. if (!all_of(Operands, [](VPValue *Op) {
  71. return Op && isa<VPInstruction>(Op) &&
  72. cast<VPInstruction>(Op)->getUnderlyingInstr();
  73. })) {
  74. LLVM_DEBUG(dbgs() << "VPSLP: not all operands are VPInstructions\n");
  75. return false;
  76. }
  77. // Check if opcodes and type width agree for all instructions in the bundle.
  78. // FIXME: Differing widths/opcodes can be handled by inserting additional
  79. // instructions.
  80. // FIXME: Deal with non-primitive types.
  81. const Instruction *OriginalInstr =
  82. cast<VPInstruction>(Operands[0])->getUnderlyingInstr();
  83. unsigned Opcode = OriginalInstr->getOpcode();
  84. unsigned Width = OriginalInstr->getType()->getPrimitiveSizeInBits();
  85. if (!all_of(Operands, [Opcode, Width](VPValue *Op) {
  86. const Instruction *I = cast<VPInstruction>(Op)->getUnderlyingInstr();
  87. return I->getOpcode() == Opcode &&
  88. I->getType()->getPrimitiveSizeInBits() == Width;
  89. })) {
  90. LLVM_DEBUG(dbgs() << "VPSLP: Opcodes do not agree \n");
  91. return false;
  92. }
  93. // For now, all operands must be defined in the same BB.
  94. if (any_of(Operands, [this](VPValue *Op) {
  95. return cast<VPInstruction>(Op)->getParent() != &this->BB;
  96. })) {
  97. LLVM_DEBUG(dbgs() << "VPSLP: operands in different BBs\n");
  98. return false;
  99. }
  100. if (any_of(Operands,
  101. [](VPValue *Op) { return Op->hasMoreThanOneUniqueUser(); })) {
  102. LLVM_DEBUG(dbgs() << "VPSLP: Some operands have multiple users.\n");
  103. return false;
  104. }
  105. // For loads, check that there are no instructions writing to memory in
  106. // between them.
  107. // TODO: we only have to forbid instructions writing to memory that could
  108. // interfere with any of the loads in the bundle
  109. if (Opcode == Instruction::Load) {
  110. unsigned LoadsSeen = 0;
  111. VPBasicBlock *Parent = cast<VPInstruction>(Operands[0])->getParent();
  112. for (auto &I : *Parent) {
  113. auto *VPI = cast<VPInstruction>(&I);
  114. if (VPI->getOpcode() == Instruction::Load &&
  115. llvm::is_contained(Operands, VPI))
  116. LoadsSeen++;
  117. if (LoadsSeen == Operands.size())
  118. break;
  119. if (LoadsSeen > 0 && VPI->mayWriteToMemory()) {
  120. LLVM_DEBUG(
  121. dbgs() << "VPSLP: instruction modifying memory between loads\n");
  122. return false;
  123. }
  124. }
  125. if (!all_of(Operands, [](VPValue *Op) {
  126. return cast<LoadInst>(cast<VPInstruction>(Op)->getUnderlyingInstr())
  127. ->isSimple();
  128. })) {
  129. LLVM_DEBUG(dbgs() << "VPSLP: only simple loads are supported.\n");
  130. return false;
  131. }
  132. }
  133. if (Opcode == Instruction::Store)
  134. if (!all_of(Operands, [](VPValue *Op) {
  135. return cast<StoreInst>(cast<VPInstruction>(Op)->getUnderlyingInstr())
  136. ->isSimple();
  137. })) {
  138. LLVM_DEBUG(dbgs() << "VPSLP: only simple stores are supported.\n");
  139. return false;
  140. }
  141. return true;
  142. }
  143. static SmallVector<VPValue *, 4> getOperands(ArrayRef<VPValue *> Values,
  144. unsigned OperandIndex) {
  145. SmallVector<VPValue *, 4> Operands;
  146. for (VPValue *V : Values) {
  147. // Currently we only support VPInstructions.
  148. auto *U = cast<VPInstruction>(V);
  149. Operands.push_back(U->getOperand(OperandIndex));
  150. }
  151. return Operands;
  152. }
  153. static bool areCommutative(ArrayRef<VPValue *> Values) {
  154. return Instruction::isCommutative(
  155. cast<VPInstruction>(Values[0])->getOpcode());
  156. }
  157. static SmallVector<SmallVector<VPValue *, 4>, 4>
  158. getOperands(ArrayRef<VPValue *> Values) {
  159. SmallVector<SmallVector<VPValue *, 4>, 4> Result;
  160. auto *VPI = cast<VPInstruction>(Values[0]);
  161. switch (VPI->getOpcode()) {
  162. case Instruction::Load:
  163. llvm_unreachable("Loads terminate a tree, no need to get operands");
  164. case Instruction::Store:
  165. Result.push_back(getOperands(Values, 0));
  166. break;
  167. default:
  168. for (unsigned I = 0, NumOps = VPI->getNumOperands(); I < NumOps; ++I)
  169. Result.push_back(getOperands(Values, I));
  170. break;
  171. }
  172. return Result;
  173. }
  174. /// Returns the opcode of Values or ~0 if they do not all agree.
  175. static Optional<unsigned> getOpcode(ArrayRef<VPValue *> Values) {
  176. unsigned Opcode = cast<VPInstruction>(Values[0])->getOpcode();
  177. if (any_of(Values, [Opcode](VPValue *V) {
  178. return cast<VPInstruction>(V)->getOpcode() != Opcode;
  179. }))
  180. return None;
  181. return {Opcode};
  182. }
  183. /// Returns true if A and B access sequential memory if they are loads or
  184. /// stores or if they have identical opcodes otherwise.
  185. static bool areConsecutiveOrMatch(VPInstruction *A, VPInstruction *B,
  186. VPInterleavedAccessInfo &IAI) {
  187. if (A->getOpcode() != B->getOpcode())
  188. return false;
  189. if (A->getOpcode() != Instruction::Load &&
  190. A->getOpcode() != Instruction::Store)
  191. return true;
  192. auto *GA = IAI.getInterleaveGroup(A);
  193. auto *GB = IAI.getInterleaveGroup(B);
  194. return GA && GB && GA == GB && GA->getIndex(A) + 1 == GB->getIndex(B);
  195. }
  196. /// Implements getLAScore from Listing 7 in the paper.
  197. /// Traverses and compares operands of V1 and V2 to MaxLevel.
  198. static unsigned getLAScore(VPValue *V1, VPValue *V2, unsigned MaxLevel,
  199. VPInterleavedAccessInfo &IAI) {
  200. auto *I1 = dyn_cast<VPInstruction>(V1);
  201. auto *I2 = dyn_cast<VPInstruction>(V2);
  202. // Currently we only support VPInstructions.
  203. if (!I1 || !I2)
  204. return 0;
  205. if (MaxLevel == 0)
  206. return (unsigned)areConsecutiveOrMatch(I1, I2, IAI);
  207. unsigned Score = 0;
  208. for (unsigned I = 0, EV1 = I1->getNumOperands(); I < EV1; ++I)
  209. for (unsigned J = 0, EV2 = I2->getNumOperands(); J < EV2; ++J)
  210. Score +=
  211. getLAScore(I1->getOperand(I), I2->getOperand(J), MaxLevel - 1, IAI);
  212. return Score;
  213. }
  214. std::pair<VPlanSlp::OpMode, VPValue *>
  215. VPlanSlp::getBest(OpMode Mode, VPValue *Last,
  216. SmallPtrSetImpl<VPValue *> &Candidates,
  217. VPInterleavedAccessInfo &IAI) {
  218. assert((Mode == OpMode::Load || Mode == OpMode::Opcode) &&
  219. "Currently we only handle load and commutative opcodes");
  220. LLVM_DEBUG(dbgs() << " getBest\n");
  221. SmallVector<VPValue *, 4> BestCandidates;
  222. LLVM_DEBUG(dbgs() << " Candidates for "
  223. << *cast<VPInstruction>(Last)->getUnderlyingInstr() << " ");
  224. for (auto *Candidate : Candidates) {
  225. auto *LastI = cast<VPInstruction>(Last);
  226. auto *CandidateI = cast<VPInstruction>(Candidate);
  227. if (areConsecutiveOrMatch(LastI, CandidateI, IAI)) {
  228. LLVM_DEBUG(dbgs() << *cast<VPInstruction>(Candidate)->getUnderlyingInstr()
  229. << " ");
  230. BestCandidates.push_back(Candidate);
  231. }
  232. }
  233. LLVM_DEBUG(dbgs() << "\n");
  234. if (BestCandidates.empty())
  235. return {OpMode::Failed, nullptr};
  236. if (BestCandidates.size() == 1)
  237. return {Mode, BestCandidates[0]};
  238. VPValue *Best = nullptr;
  239. unsigned BestScore = 0;
  240. for (unsigned Depth = 1; Depth < LookaheadMaxDepth; Depth++) {
  241. unsigned PrevScore = ~0u;
  242. bool AllSame = true;
  243. // FIXME: Avoid visiting the same operands multiple times.
  244. for (auto *Candidate : BestCandidates) {
  245. unsigned Score = getLAScore(Last, Candidate, Depth, IAI);
  246. if (PrevScore == ~0u)
  247. PrevScore = Score;
  248. if (PrevScore != Score)
  249. AllSame = false;
  250. PrevScore = Score;
  251. if (Score > BestScore) {
  252. BestScore = Score;
  253. Best = Candidate;
  254. }
  255. }
  256. if (!AllSame)
  257. break;
  258. }
  259. LLVM_DEBUG(dbgs() << "Found best "
  260. << *cast<VPInstruction>(Best)->getUnderlyingInstr()
  261. << "\n");
  262. Candidates.erase(Best);
  263. return {Mode, Best};
  264. }
  265. SmallVector<VPlanSlp::MultiNodeOpTy, 4> VPlanSlp::reorderMultiNodeOps() {
  266. SmallVector<MultiNodeOpTy, 4> FinalOrder;
  267. SmallVector<OpMode, 4> Mode;
  268. FinalOrder.reserve(MultiNodeOps.size());
  269. Mode.reserve(MultiNodeOps.size());
  270. LLVM_DEBUG(dbgs() << "Reordering multinode\n");
  271. for (auto &Operands : MultiNodeOps) {
  272. FinalOrder.push_back({Operands.first, {Operands.second[0]}});
  273. if (cast<VPInstruction>(Operands.second[0])->getOpcode() ==
  274. Instruction::Load)
  275. Mode.push_back(OpMode::Load);
  276. else
  277. Mode.push_back(OpMode::Opcode);
  278. }
  279. for (unsigned Lane = 1, E = MultiNodeOps[0].second.size(); Lane < E; ++Lane) {
  280. LLVM_DEBUG(dbgs() << " Finding best value for lane " << Lane << "\n");
  281. SmallPtrSet<VPValue *, 4> Candidates;
  282. LLVM_DEBUG(dbgs() << " Candidates ");
  283. for (auto Ops : MultiNodeOps) {
  284. LLVM_DEBUG(
  285. dbgs() << *cast<VPInstruction>(Ops.second[Lane])->getUnderlyingInstr()
  286. << " ");
  287. Candidates.insert(Ops.second[Lane]);
  288. }
  289. LLVM_DEBUG(dbgs() << "\n");
  290. for (unsigned Op = 0, E = MultiNodeOps.size(); Op < E; ++Op) {
  291. LLVM_DEBUG(dbgs() << " Checking " << Op << "\n");
  292. if (Mode[Op] == OpMode::Failed)
  293. continue;
  294. VPValue *Last = FinalOrder[Op].second[Lane - 1];
  295. std::pair<OpMode, VPValue *> Res =
  296. getBest(Mode[Op], Last, Candidates, IAI);
  297. if (Res.second)
  298. FinalOrder[Op].second.push_back(Res.second);
  299. else
  300. // TODO: handle this case
  301. FinalOrder[Op].second.push_back(markFailed());
  302. }
  303. }
  304. return FinalOrder;
  305. }
  306. void VPlanSlp::dumpBundle(ArrayRef<VPValue *> Values) {
  307. dbgs() << " Ops: ";
  308. for (auto Op : Values) {
  309. if (auto *VPInstr = cast_or_null<VPInstruction>(Op))
  310. if (auto *Instr = VPInstr->getUnderlyingInstr()) {
  311. dbgs() << *Instr << " | ";
  312. continue;
  313. }
  314. dbgs() << " nullptr | ";
  315. }
  316. dbgs() << "\n";
  317. }
  318. VPInstruction *VPlanSlp::buildGraph(ArrayRef<VPValue *> Values) {
  319. assert(!Values.empty() && "Need some operands!");
  320. // If we already visited this instruction bundle, re-use the existing node
  321. auto I = BundleToCombined.find(to_vector<4>(Values));
  322. if (I != BundleToCombined.end()) {
  323. #ifndef NDEBUG
  324. // Check that the resulting graph is a tree. If we re-use a node, this means
  325. // its values have multiple users. We only allow this, if all users of each
  326. // value are the same instruction.
  327. for (auto *V : Values) {
  328. auto UI = V->user_begin();
  329. auto *FirstUser = *UI++;
  330. while (UI != V->user_end()) {
  331. assert(*UI == FirstUser && "Currently we only support SLP trees.");
  332. UI++;
  333. }
  334. }
  335. #endif
  336. return I->second;
  337. }
  338. // Dump inputs
  339. LLVM_DEBUG({
  340. dbgs() << "buildGraph: ";
  341. dumpBundle(Values);
  342. });
  343. if (!areVectorizable(Values))
  344. return markFailed();
  345. assert(getOpcode(Values) && "Opcodes for all values must match");
  346. unsigned ValuesOpcode = getOpcode(Values).getValue();
  347. SmallVector<VPValue *, 4> CombinedOperands;
  348. if (areCommutative(Values)) {
  349. bool MultiNodeRoot = !MultiNodeActive;
  350. MultiNodeActive = true;
  351. for (auto &Operands : getOperands(Values)) {
  352. LLVM_DEBUG({
  353. dbgs() << " Visiting Commutative";
  354. dumpBundle(Operands);
  355. });
  356. auto OperandsOpcode = getOpcode(Operands);
  357. if (OperandsOpcode && OperandsOpcode == getOpcode(Values)) {
  358. LLVM_DEBUG(dbgs() << " Same opcode, continue building\n");
  359. CombinedOperands.push_back(buildGraph(Operands));
  360. } else {
  361. LLVM_DEBUG(dbgs() << " Adding multinode Ops\n");
  362. // Create dummy VPInstruction, which will we replace later by the
  363. // re-ordered operand.
  364. VPInstruction *Op = new VPInstruction(0, {});
  365. CombinedOperands.push_back(Op);
  366. MultiNodeOps.emplace_back(Op, Operands);
  367. }
  368. }
  369. if (MultiNodeRoot) {
  370. LLVM_DEBUG(dbgs() << "Reorder \n");
  371. MultiNodeActive = false;
  372. auto FinalOrder = reorderMultiNodeOps();
  373. MultiNodeOps.clear();
  374. for (auto &Ops : FinalOrder) {
  375. VPInstruction *NewOp = buildGraph(Ops.second);
  376. Ops.first->replaceAllUsesWith(NewOp);
  377. for (unsigned i = 0; i < CombinedOperands.size(); i++)
  378. if (CombinedOperands[i] == Ops.first)
  379. CombinedOperands[i] = NewOp;
  380. delete Ops.first;
  381. Ops.first = NewOp;
  382. }
  383. LLVM_DEBUG(dbgs() << "Found final order\n");
  384. }
  385. } else {
  386. LLVM_DEBUG(dbgs() << " NonCommuntative\n");
  387. if (ValuesOpcode == Instruction::Load)
  388. for (VPValue *V : Values)
  389. CombinedOperands.push_back(cast<VPInstruction>(V)->getOperand(0));
  390. else
  391. for (auto &Operands : getOperands(Values))
  392. CombinedOperands.push_back(buildGraph(Operands));
  393. }
  394. unsigned Opcode;
  395. switch (ValuesOpcode) {
  396. case Instruction::Load:
  397. Opcode = VPInstruction::SLPLoad;
  398. break;
  399. case Instruction::Store:
  400. Opcode = VPInstruction::SLPStore;
  401. break;
  402. default:
  403. Opcode = ValuesOpcode;
  404. break;
  405. }
  406. if (!CompletelySLP)
  407. return markFailed();
  408. assert(CombinedOperands.size() > 0 && "Need more some operands");
  409. auto *VPI = new VPInstruction(Opcode, CombinedOperands);
  410. VPI->setUnderlyingInstr(cast<VPInstruction>(Values[0])->getUnderlyingInstr());
  411. LLVM_DEBUG(dbgs() << "Create VPInstruction " << *VPI << " "
  412. << *cast<VPInstruction>(Values[0]) << "\n");
  413. addCombined(Values, VPI);
  414. return VPI;
  415. }