VPlan.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
  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. /// \file
  10. /// This is the LLVM vectorization plan. It represents a candidate for
  11. /// vectorization, allowing to plan and optimize how to vectorize a given loop
  12. /// before generating LLVM-IR.
  13. /// The vectorizer uses vectorization plans to estimate the costs of potential
  14. /// candidates and if profitable to execute the desired plan, generating vector
  15. /// LLVM-IR code.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #include "VPlan.h"
  19. #include "VPlanCFG.h"
  20. #include "VPlanDominatorTree.h"
  21. #include "llvm/ADT/DepthFirstIterator.h"
  22. #include "llvm/ADT/PostOrderIterator.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/Analysis/LoopInfo.h"
  27. #include "llvm/IR/BasicBlock.h"
  28. #include "llvm/IR/CFG.h"
  29. #include "llvm/IR/IRBuilder.h"
  30. #include "llvm/IR/Instruction.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/IR/Value.h"
  34. #include "llvm/Support/Casting.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/GenericDomTreeConstruction.h"
  38. #include "llvm/Support/GraphWriter.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  41. #include "llvm/Transforms/Utils/LoopVersioning.h"
  42. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  43. #include <cassert>
  44. #include <string>
  45. #include <vector>
  46. using namespace llvm;
  47. extern cl::opt<bool> EnableVPlanNativePath;
  48. #define DEBUG_TYPE "vplan"
  49. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  50. raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
  51. const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
  52. VPSlotTracker SlotTracker(
  53. (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
  54. V.print(OS, SlotTracker);
  55. return OS;
  56. }
  57. #endif
  58. Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
  59. const ElementCount &VF) const {
  60. switch (LaneKind) {
  61. case VPLane::Kind::ScalableLast:
  62. // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
  63. return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
  64. Builder.getInt32(VF.getKnownMinValue() - Lane));
  65. case VPLane::Kind::First:
  66. return Builder.getInt32(Lane);
  67. }
  68. llvm_unreachable("Unknown lane kind");
  69. }
  70. VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
  71. : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
  72. if (Def)
  73. Def->addDefinedValue(this);
  74. }
  75. VPValue::~VPValue() {
  76. assert(Users.empty() && "trying to delete a VPValue with remaining users");
  77. if (Def)
  78. Def->removeDefinedValue(this);
  79. }
  80. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  81. void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
  82. if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
  83. R->print(OS, "", SlotTracker);
  84. else
  85. printAsOperand(OS, SlotTracker);
  86. }
  87. void VPValue::dump() const {
  88. const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
  89. VPSlotTracker SlotTracker(
  90. (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
  91. print(dbgs(), SlotTracker);
  92. dbgs() << "\n";
  93. }
  94. void VPDef::dump() const {
  95. const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
  96. VPSlotTracker SlotTracker(
  97. (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
  98. print(dbgs(), "", SlotTracker);
  99. dbgs() << "\n";
  100. }
  101. #endif
  102. VPRecipeBase *VPValue::getDefiningRecipe() {
  103. return cast_or_null<VPRecipeBase>(Def);
  104. }
  105. const VPRecipeBase *VPValue::getDefiningRecipe() const {
  106. return cast_or_null<VPRecipeBase>(Def);
  107. }
  108. // Get the top-most entry block of \p Start. This is the entry block of the
  109. // containing VPlan. This function is templated to support both const and non-const blocks
  110. template <typename T> static T *getPlanEntry(T *Start) {
  111. T *Next = Start;
  112. T *Current = Start;
  113. while ((Next = Next->getParent()))
  114. Current = Next;
  115. SmallSetVector<T *, 8> WorkList;
  116. WorkList.insert(Current);
  117. for (unsigned i = 0; i < WorkList.size(); i++) {
  118. T *Current = WorkList[i];
  119. if (Current->getNumPredecessors() == 0)
  120. return Current;
  121. auto &Predecessors = Current->getPredecessors();
  122. WorkList.insert(Predecessors.begin(), Predecessors.end());
  123. }
  124. llvm_unreachable("VPlan without any entry node without predecessors");
  125. }
  126. VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
  127. const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
  128. /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
  129. const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
  130. const VPBlockBase *Block = this;
  131. while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
  132. Block = Region->getEntry();
  133. return cast<VPBasicBlock>(Block);
  134. }
  135. VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
  136. VPBlockBase *Block = this;
  137. while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
  138. Block = Region->getEntry();
  139. return cast<VPBasicBlock>(Block);
  140. }
  141. void VPBlockBase::setPlan(VPlan *ParentPlan) {
  142. assert(ParentPlan->getEntry() == this &&
  143. "Can only set plan on its entry block.");
  144. Plan = ParentPlan;
  145. }
  146. /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
  147. const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
  148. const VPBlockBase *Block = this;
  149. while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
  150. Block = Region->getExiting();
  151. return cast<VPBasicBlock>(Block);
  152. }
  153. VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
  154. VPBlockBase *Block = this;
  155. while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
  156. Block = Region->getExiting();
  157. return cast<VPBasicBlock>(Block);
  158. }
  159. VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
  160. if (!Successors.empty() || !Parent)
  161. return this;
  162. assert(Parent->getExiting() == this &&
  163. "Block w/o successors not the exiting block of its parent.");
  164. return Parent->getEnclosingBlockWithSuccessors();
  165. }
  166. VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
  167. if (!Predecessors.empty() || !Parent)
  168. return this;
  169. assert(Parent->getEntry() == this &&
  170. "Block w/o predecessors not the entry of its parent.");
  171. return Parent->getEnclosingBlockWithPredecessors();
  172. }
  173. void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
  174. for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry)))
  175. delete Block;
  176. }
  177. VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
  178. iterator It = begin();
  179. while (It != end() && It->isPhi())
  180. It++;
  181. return It;
  182. }
  183. Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
  184. if (!Def->hasDefiningRecipe())
  185. return Def->getLiveInIRValue();
  186. if (hasScalarValue(Def, Instance)) {
  187. return Data
  188. .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
  189. }
  190. assert(hasVectorValue(Def, Instance.Part));
  191. auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
  192. if (!VecPart->getType()->isVectorTy()) {
  193. assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
  194. return VecPart;
  195. }
  196. // TODO: Cache created scalar values.
  197. Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
  198. auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
  199. // set(Def, Extract, Instance);
  200. return Extract;
  201. }
  202. BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
  203. VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
  204. return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
  205. }
  206. void VPTransformState::addNewMetadata(Instruction *To,
  207. const Instruction *Orig) {
  208. // If the loop was versioned with memchecks, add the corresponding no-alias
  209. // metadata.
  210. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  211. LVer->annotateInstWithNoAlias(To, Orig);
  212. }
  213. void VPTransformState::addMetadata(Instruction *To, Instruction *From) {
  214. propagateMetadata(To, From);
  215. addNewMetadata(To, From);
  216. }
  217. void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) {
  218. for (Value *V : To) {
  219. if (Instruction *I = dyn_cast<Instruction>(V))
  220. addMetadata(I, From);
  221. }
  222. }
  223. void VPTransformState::setDebugLocFromInst(const Value *V) {
  224. const Instruction *Inst = dyn_cast<Instruction>(V);
  225. if (!Inst) {
  226. Builder.SetCurrentDebugLocation(DebugLoc());
  227. return;
  228. }
  229. const DILocation *DIL = Inst->getDebugLoc();
  230. // When a FSDiscriminator is enabled, we don't need to add the multiply
  231. // factors to the discriminators.
  232. if (DIL && Inst->getFunction()->shouldEmitDebugInfoForProfiling() &&
  233. !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
  234. // FIXME: For scalable vectors, assume vscale=1.
  235. auto NewDIL =
  236. DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
  237. if (NewDIL)
  238. Builder.SetCurrentDebugLocation(*NewDIL);
  239. else
  240. LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
  241. << DIL->getFilename() << " Line: " << DIL->getLine());
  242. } else
  243. Builder.SetCurrentDebugLocation(DIL);
  244. }
  245. BasicBlock *
  246. VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
  247. // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
  248. // Pred stands for Predessor. Prev stands for Previous - last visited/created.
  249. BasicBlock *PrevBB = CFG.PrevBB;
  250. BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
  251. PrevBB->getParent(), CFG.ExitBB);
  252. LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
  253. // Hook up the new basic block to its predecessors.
  254. for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
  255. VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
  256. auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
  257. BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
  258. assert(PredBB && "Predecessor basic-block not found building successor.");
  259. auto *PredBBTerminator = PredBB->getTerminator();
  260. LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
  261. auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
  262. if (isa<UnreachableInst>(PredBBTerminator)) {
  263. assert(PredVPSuccessors.size() == 1 &&
  264. "Predecessor ending w/o branch must have single successor.");
  265. DebugLoc DL = PredBBTerminator->getDebugLoc();
  266. PredBBTerminator->eraseFromParent();
  267. auto *Br = BranchInst::Create(NewBB, PredBB);
  268. Br->setDebugLoc(DL);
  269. } else if (TermBr && !TermBr->isConditional()) {
  270. TermBr->setSuccessor(0, NewBB);
  271. } else {
  272. // Set each forward successor here when it is created, excluding
  273. // backedges. A backward successor is set when the branch is created.
  274. unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
  275. assert(!TermBr->getSuccessor(idx) &&
  276. "Trying to reset an existing successor block.");
  277. TermBr->setSuccessor(idx, NewBB);
  278. }
  279. }
  280. return NewBB;
  281. }
  282. void VPBasicBlock::execute(VPTransformState *State) {
  283. bool Replica = State->Instance && !State->Instance->isFirstIteration();
  284. VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
  285. VPBlockBase *SingleHPred = nullptr;
  286. BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
  287. auto IsLoopRegion = [](VPBlockBase *BB) {
  288. auto *R = dyn_cast<VPRegionBlock>(BB);
  289. return R && !R->isReplicator();
  290. };
  291. // 1. Create an IR basic block, or reuse the last one or ExitBB if possible.
  292. if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) {
  293. // ExitBB can be re-used for the exit block of the Plan.
  294. NewBB = State->CFG.ExitBB;
  295. State->CFG.PrevBB = NewBB;
  296. // Update the branch instruction in the predecessor to branch to ExitBB.
  297. VPBlockBase *PredVPB = getSingleHierarchicalPredecessor();
  298. VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock();
  299. assert(PredVPB->getSingleSuccessor() == this &&
  300. "predecessor must have the current block as only successor");
  301. BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB];
  302. // The Exit block of a loop is always set to be successor 0 of the Exiting
  303. // block.
  304. cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB);
  305. } else if (PrevVPBB && /* A */
  306. !((SingleHPred = getSingleHierarchicalPredecessor()) &&
  307. SingleHPred->getExitingBasicBlock() == PrevVPBB &&
  308. PrevVPBB->getSingleHierarchicalSuccessor() &&
  309. (SingleHPred->getParent() == getEnclosingLoopRegion() &&
  310. !IsLoopRegion(SingleHPred))) && /* B */
  311. !(Replica && getPredecessors().empty())) { /* C */
  312. // The last IR basic block is reused, as an optimization, in three cases:
  313. // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
  314. // B. when the current VPBB has a single (hierarchical) predecessor which
  315. // is PrevVPBB and the latter has a single (hierarchical) successor which
  316. // both are in the same non-replicator region; and
  317. // C. when the current VPBB is an entry of a region replica - where PrevVPBB
  318. // is the exiting VPBB of this region from a previous instance, or the
  319. // predecessor of this region.
  320. NewBB = createEmptyBasicBlock(State->CFG);
  321. State->Builder.SetInsertPoint(NewBB);
  322. // Temporarily terminate with unreachable until CFG is rewired.
  323. UnreachableInst *Terminator = State->Builder.CreateUnreachable();
  324. // Register NewBB in its loop. In innermost loops its the same for all
  325. // BB's.
  326. if (State->CurrentVectorLoop)
  327. State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
  328. State->Builder.SetInsertPoint(Terminator);
  329. State->CFG.PrevBB = NewBB;
  330. }
  331. // 2. Fill the IR basic block with IR instructions.
  332. LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
  333. << " in BB:" << NewBB->getName() << '\n');
  334. State->CFG.VPBB2IRBB[this] = NewBB;
  335. State->CFG.PrevVPBB = this;
  336. for (VPRecipeBase &Recipe : Recipes)
  337. Recipe.execute(*State);
  338. LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
  339. }
  340. void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
  341. for (VPRecipeBase &R : Recipes) {
  342. for (auto *Def : R.definedValues())
  343. Def->replaceAllUsesWith(NewValue);
  344. for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
  345. R.setOperand(I, NewValue);
  346. }
  347. }
  348. VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
  349. assert((SplitAt == end() || SplitAt->getParent() == this) &&
  350. "can only split at a position in the same block");
  351. SmallVector<VPBlockBase *, 2> Succs(successors());
  352. // First, disconnect the current block from its successors.
  353. for (VPBlockBase *Succ : Succs)
  354. VPBlockUtils::disconnectBlocks(this, Succ);
  355. // Create new empty block after the block to split.
  356. auto *SplitBlock = new VPBasicBlock(getName() + ".split");
  357. VPBlockUtils::insertBlockAfter(SplitBlock, this);
  358. // Add successors for block to split to new block.
  359. for (VPBlockBase *Succ : Succs)
  360. VPBlockUtils::connectBlocks(SplitBlock, Succ);
  361. // Finally, move the recipes starting at SplitAt to new block.
  362. for (VPRecipeBase &ToMove :
  363. make_early_inc_range(make_range(SplitAt, this->end())))
  364. ToMove.moveBefore(*SplitBlock, SplitBlock->end());
  365. return SplitBlock;
  366. }
  367. VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
  368. VPRegionBlock *P = getParent();
  369. if (P && P->isReplicator()) {
  370. P = P->getParent();
  371. assert(!cast<VPRegionBlock>(P)->isReplicator() &&
  372. "unexpected nested replicate regions");
  373. }
  374. return P;
  375. }
  376. static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
  377. if (VPBB->empty()) {
  378. assert(
  379. VPBB->getNumSuccessors() < 2 &&
  380. "block with multiple successors doesn't have a recipe as terminator");
  381. return false;
  382. }
  383. const VPRecipeBase *R = &VPBB->back();
  384. auto *VPI = dyn_cast<VPInstruction>(R);
  385. bool IsCondBranch =
  386. isa<VPBranchOnMaskRecipe>(R) ||
  387. (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond ||
  388. VPI->getOpcode() == VPInstruction::BranchOnCount));
  389. (void)IsCondBranch;
  390. if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) {
  391. assert(IsCondBranch && "block with multiple successors not terminated by "
  392. "conditional branch recipe");
  393. return true;
  394. }
  395. assert(
  396. !IsCondBranch &&
  397. "block with 0 or 1 successors terminated by conditional branch recipe");
  398. return false;
  399. }
  400. VPRecipeBase *VPBasicBlock::getTerminator() {
  401. if (hasConditionalTerminator(this))
  402. return &back();
  403. return nullptr;
  404. }
  405. const VPRecipeBase *VPBasicBlock::getTerminator() const {
  406. if (hasConditionalTerminator(this))
  407. return &back();
  408. return nullptr;
  409. }
  410. bool VPBasicBlock::isExiting() const {
  411. return getParent()->getExitingBasicBlock() == this;
  412. }
  413. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  414. void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
  415. if (getSuccessors().empty()) {
  416. O << Indent << "No successors\n";
  417. } else {
  418. O << Indent << "Successor(s): ";
  419. ListSeparator LS;
  420. for (auto *Succ : getSuccessors())
  421. O << LS << Succ->getName();
  422. O << '\n';
  423. }
  424. }
  425. void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
  426. VPSlotTracker &SlotTracker) const {
  427. O << Indent << getName() << ":\n";
  428. auto RecipeIndent = Indent + " ";
  429. for (const VPRecipeBase &Recipe : *this) {
  430. Recipe.print(O, RecipeIndent, SlotTracker);
  431. O << '\n';
  432. }
  433. printSuccessors(O, Indent);
  434. }
  435. #endif
  436. void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
  437. for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
  438. // Drop all references in VPBasicBlocks and replace all uses with
  439. // DummyValue.
  440. Block->dropAllReferences(NewValue);
  441. }
  442. void VPRegionBlock::execute(VPTransformState *State) {
  443. ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
  444. RPOT(Entry);
  445. if (!isReplicator()) {
  446. // Create and register the new vector loop.
  447. Loop *PrevLoop = State->CurrentVectorLoop;
  448. State->CurrentVectorLoop = State->LI->AllocateLoop();
  449. BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
  450. Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
  451. // Insert the new loop into the loop nest and register the new basic blocks
  452. // before calling any utilities such as SCEV that require valid LoopInfo.
  453. if (ParentLoop)
  454. ParentLoop->addChildLoop(State->CurrentVectorLoop);
  455. else
  456. State->LI->addTopLevelLoop(State->CurrentVectorLoop);
  457. // Visit the VPBlocks connected to "this", starting from it.
  458. for (VPBlockBase *Block : RPOT) {
  459. LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
  460. Block->execute(State);
  461. }
  462. State->CurrentVectorLoop = PrevLoop;
  463. return;
  464. }
  465. assert(!State->Instance && "Replicating a Region with non-null instance.");
  466. // Enter replicating mode.
  467. State->Instance = VPIteration(0, 0);
  468. for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
  469. State->Instance->Part = Part;
  470. assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
  471. for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
  472. ++Lane) {
  473. State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
  474. // Visit the VPBlocks connected to \p this, starting from it.
  475. for (VPBlockBase *Block : RPOT) {
  476. LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
  477. Block->execute(State);
  478. }
  479. }
  480. }
  481. // Exit replicating mode.
  482. State->Instance.reset();
  483. }
  484. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  485. void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
  486. VPSlotTracker &SlotTracker) const {
  487. O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
  488. auto NewIndent = Indent + " ";
  489. for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
  490. O << '\n';
  491. BlockBase->print(O, NewIndent, SlotTracker);
  492. }
  493. O << Indent << "}\n";
  494. printSuccessors(O, Indent);
  495. }
  496. #endif
  497. VPlan::~VPlan() {
  498. clearLiveOuts();
  499. if (Entry) {
  500. VPValue DummyValue;
  501. for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
  502. Block->dropAllReferences(&DummyValue);
  503. VPBlockBase::deleteCFG(Entry);
  504. }
  505. for (VPValue *VPV : VPValuesToFree)
  506. delete VPV;
  507. if (TripCount)
  508. delete TripCount;
  509. if (BackedgeTakenCount)
  510. delete BackedgeTakenCount;
  511. for (auto &P : VPExternalDefs)
  512. delete P.second;
  513. }
  514. VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() {
  515. VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
  516. for (VPRecipeBase &R : Header->phis()) {
  517. if (isa<VPActiveLaneMaskPHIRecipe>(&R))
  518. return cast<VPActiveLaneMaskPHIRecipe>(&R);
  519. }
  520. return nullptr;
  521. }
  522. void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
  523. Value *CanonicalIVStartValue,
  524. VPTransformState &State,
  525. bool IsEpilogueVectorization) {
  526. // Check if the trip count is needed, and if so build it.
  527. if (TripCount && TripCount->getNumUsers()) {
  528. for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
  529. State.set(TripCount, TripCountV, Part);
  530. }
  531. // Check if the backedge taken count is needed, and if so build it.
  532. if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
  533. IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
  534. auto *TCMO = Builder.CreateSub(TripCountV,
  535. ConstantInt::get(TripCountV->getType(), 1),
  536. "trip.count.minus.1");
  537. auto VF = State.VF;
  538. Value *VTCMO =
  539. VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
  540. for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
  541. State.set(BackedgeTakenCount, VTCMO, Part);
  542. }
  543. for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
  544. State.set(&VectorTripCount, VectorTripCountV, Part);
  545. // When vectorizing the epilogue loop, the canonical induction start value
  546. // needs to be changed from zero to the value after the main vector loop.
  547. // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
  548. if (CanonicalIVStartValue) {
  549. VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue);
  550. auto *IV = getCanonicalIV();
  551. assert(all_of(IV->users(),
  552. [](const VPUser *U) {
  553. if (isa<VPScalarIVStepsRecipe>(U) ||
  554. isa<VPDerivedIVRecipe>(U))
  555. return true;
  556. auto *VPI = cast<VPInstruction>(U);
  557. return VPI->getOpcode() ==
  558. VPInstruction::CanonicalIVIncrement ||
  559. VPI->getOpcode() ==
  560. VPInstruction::CanonicalIVIncrementNUW;
  561. }) &&
  562. "the canonical IV should only be used by its increments or "
  563. "ScalarIVSteps when "
  564. "resetting the start value");
  565. IV->setOperand(0, VPV);
  566. }
  567. }
  568. /// Generate the code inside the preheader and body of the vectorized loop.
  569. /// Assumes a single pre-header basic-block was created for this. Introduce
  570. /// additional basic-blocks as needed, and fill them all.
  571. void VPlan::execute(VPTransformState *State) {
  572. // Set the reverse mapping from VPValues to Values for code generation.
  573. for (auto &Entry : Value2VPValue)
  574. State->VPValue2Value[Entry.second] = Entry.first;
  575. // Initialize CFG state.
  576. State->CFG.PrevVPBB = nullptr;
  577. State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
  578. BasicBlock *VectorPreHeader = State->CFG.PrevBB;
  579. State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
  580. // Generate code in the loop pre-header and body.
  581. for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
  582. Block->execute(State);
  583. VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
  584. BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
  585. // Fix the latch value of canonical, reduction and first-order recurrences
  586. // phis in the vector loop.
  587. VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
  588. for (VPRecipeBase &R : Header->phis()) {
  589. // Skip phi-like recipes that generate their backedege values themselves.
  590. if (isa<VPWidenPHIRecipe>(&R))
  591. continue;
  592. if (isa<VPWidenPointerInductionRecipe>(&R) ||
  593. isa<VPWidenIntOrFpInductionRecipe>(&R)) {
  594. PHINode *Phi = nullptr;
  595. if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
  596. Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
  597. } else {
  598. auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
  599. // TODO: Split off the case that all users of a pointer phi are scalar
  600. // from the VPWidenPointerInductionRecipe.
  601. if (WidenPhi->onlyScalarsGenerated(State->VF))
  602. continue;
  603. auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
  604. Phi = cast<PHINode>(GEP->getPointerOperand());
  605. }
  606. Phi->setIncomingBlock(1, VectorLatchBB);
  607. // Move the last step to the end of the latch block. This ensures
  608. // consistent placement of all induction updates.
  609. Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
  610. Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
  611. continue;
  612. }
  613. auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
  614. // For canonical IV, first-order recurrences and in-order reduction phis,
  615. // only a single part is generated, which provides the last part from the
  616. // previous iteration. For non-ordered reductions all UF parts are
  617. // generated.
  618. bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
  619. isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
  620. (isa<VPReductionPHIRecipe>(PhiR) &&
  621. cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
  622. unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
  623. for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
  624. Value *Phi = State->get(PhiR, Part);
  625. Value *Val = State->get(PhiR->getBackedgeValue(),
  626. SinglePartNeeded ? State->UF - 1 : Part);
  627. cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
  628. }
  629. }
  630. // We do not attempt to preserve DT for outer loop vectorization currently.
  631. if (!EnableVPlanNativePath) {
  632. BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
  633. State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
  634. updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
  635. State->CFG.ExitBB);
  636. }
  637. }
  638. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  639. LLVM_DUMP_METHOD
  640. void VPlan::print(raw_ostream &O) const {
  641. VPSlotTracker SlotTracker(this);
  642. O << "VPlan '" << getName() << "' {";
  643. if (VectorTripCount.getNumUsers() > 0) {
  644. O << "\nLive-in ";
  645. VectorTripCount.printAsOperand(O, SlotTracker);
  646. O << " = vector-trip-count\n";
  647. }
  648. if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
  649. O << "\nLive-in ";
  650. BackedgeTakenCount->printAsOperand(O, SlotTracker);
  651. O << " = backedge-taken count\n";
  652. }
  653. for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
  654. O << '\n';
  655. Block->print(O, "", SlotTracker);
  656. }
  657. if (!LiveOuts.empty())
  658. O << "\n";
  659. for (const auto &KV : LiveOuts) {
  660. O << "Live-out ";
  661. KV.second->getPhi()->printAsOperand(O);
  662. O << " = ";
  663. KV.second->getOperand(0)->printAsOperand(O, SlotTracker);
  664. O << "\n";
  665. }
  666. O << "}\n";
  667. }
  668. std::string VPlan::getName() const {
  669. std::string Out;
  670. raw_string_ostream RSO(Out);
  671. RSO << Name << " for ";
  672. if (!VFs.empty()) {
  673. RSO << "VF={" << VFs[0];
  674. for (ElementCount VF : drop_begin(VFs))
  675. RSO << "," << VF;
  676. RSO << "},";
  677. }
  678. if (UFs.empty()) {
  679. RSO << "UF>=1";
  680. } else {
  681. RSO << "UF={" << UFs[0];
  682. for (unsigned UF : drop_begin(UFs))
  683. RSO << "," << UF;
  684. RSO << "}";
  685. }
  686. return Out;
  687. }
  688. LLVM_DUMP_METHOD
  689. void VPlan::printDOT(raw_ostream &O) const {
  690. VPlanPrinter Printer(O, *this);
  691. Printer.dump();
  692. }
  693. LLVM_DUMP_METHOD
  694. void VPlan::dump() const { print(dbgs()); }
  695. #endif
  696. void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
  697. assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
  698. LiveOuts.insert({PN, new VPLiveOut(PN, V)});
  699. }
  700. void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
  701. BasicBlock *LoopLatchBB,
  702. BasicBlock *LoopExitBB) {
  703. // The vector body may be more than a single basic-block by this point.
  704. // Update the dominator tree information inside the vector body by propagating
  705. // it from header to latch, expecting only triangular control-flow, if any.
  706. BasicBlock *PostDomSucc = nullptr;
  707. for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
  708. // Get the list of successors of this block.
  709. std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
  710. assert(Succs.size() <= 2 &&
  711. "Basic block in vector loop has more than 2 successors.");
  712. PostDomSucc = Succs[0];
  713. if (Succs.size() == 1) {
  714. assert(PostDomSucc->getSinglePredecessor() &&
  715. "PostDom successor has more than one predecessor.");
  716. DT->addNewBlock(PostDomSucc, BB);
  717. continue;
  718. }
  719. BasicBlock *InterimSucc = Succs[1];
  720. if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
  721. PostDomSucc = Succs[1];
  722. InterimSucc = Succs[0];
  723. }
  724. assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
  725. "One successor of a basic block does not lead to the other.");
  726. assert(InterimSucc->getSinglePredecessor() &&
  727. "Interim successor has more than one predecessor.");
  728. assert(PostDomSucc->hasNPredecessors(2) &&
  729. "PostDom successor has more than two predecessors.");
  730. DT->addNewBlock(InterimSucc, BB);
  731. DT->addNewBlock(PostDomSucc, BB);
  732. }
  733. // Latch block is a new dominator for the loop exit.
  734. DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
  735. assert(DT->verify(DominatorTree::VerificationLevel::Fast));
  736. }
  737. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  738. Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
  739. return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
  740. Twine(getOrCreateBID(Block));
  741. }
  742. Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
  743. const std::string &Name = Block->getName();
  744. if (!Name.empty())
  745. return Name;
  746. return "VPB" + Twine(getOrCreateBID(Block));
  747. }
  748. void VPlanPrinter::dump() {
  749. Depth = 1;
  750. bumpIndent(0);
  751. OS << "digraph VPlan {\n";
  752. OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
  753. if (!Plan.getName().empty())
  754. OS << "\\n" << DOT::EscapeString(Plan.getName());
  755. if (Plan.BackedgeTakenCount) {
  756. OS << ", where:\\n";
  757. Plan.BackedgeTakenCount->print(OS, SlotTracker);
  758. OS << " := BackedgeTakenCount";
  759. }
  760. OS << "\"]\n";
  761. OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
  762. OS << "edge [fontname=Courier, fontsize=30]\n";
  763. OS << "compound=true\n";
  764. for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
  765. dumpBlock(Block);
  766. OS << "}\n";
  767. }
  768. void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
  769. if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
  770. dumpBasicBlock(BasicBlock);
  771. else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
  772. dumpRegion(Region);
  773. else
  774. llvm_unreachable("Unsupported kind of VPBlock.");
  775. }
  776. void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
  777. bool Hidden, const Twine &Label) {
  778. // Due to "dot" we print an edge between two regions as an edge between the
  779. // exiting basic block and the entry basic of the respective regions.
  780. const VPBlockBase *Tail = From->getExitingBasicBlock();
  781. const VPBlockBase *Head = To->getEntryBasicBlock();
  782. OS << Indent << getUID(Tail) << " -> " << getUID(Head);
  783. OS << " [ label=\"" << Label << '\"';
  784. if (Tail != From)
  785. OS << " ltail=" << getUID(From);
  786. if (Head != To)
  787. OS << " lhead=" << getUID(To);
  788. if (Hidden)
  789. OS << "; splines=none";
  790. OS << "]\n";
  791. }
  792. void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
  793. auto &Successors = Block->getSuccessors();
  794. if (Successors.size() == 1)
  795. drawEdge(Block, Successors.front(), false, "");
  796. else if (Successors.size() == 2) {
  797. drawEdge(Block, Successors.front(), false, "T");
  798. drawEdge(Block, Successors.back(), false, "F");
  799. } else {
  800. unsigned SuccessorNumber = 0;
  801. for (auto *Successor : Successors)
  802. drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
  803. }
  804. }
  805. void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
  806. // Implement dot-formatted dump by performing plain-text dump into the
  807. // temporary storage followed by some post-processing.
  808. OS << Indent << getUID(BasicBlock) << " [label =\n";
  809. bumpIndent(1);
  810. std::string Str;
  811. raw_string_ostream SS(Str);
  812. // Use no indentation as we need to wrap the lines into quotes ourselves.
  813. BasicBlock->print(SS, "", SlotTracker);
  814. // We need to process each line of the output separately, so split
  815. // single-string plain-text dump.
  816. SmallVector<StringRef, 0> Lines;
  817. StringRef(Str).rtrim('\n').split(Lines, "\n");
  818. auto EmitLine = [&](StringRef Line, StringRef Suffix) {
  819. OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
  820. };
  821. // Don't need the "+" after the last line.
  822. for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
  823. EmitLine(Line, " +\n");
  824. EmitLine(Lines.back(), "\n");
  825. bumpIndent(-1);
  826. OS << Indent << "]\n";
  827. dumpEdges(BasicBlock);
  828. }
  829. void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
  830. OS << Indent << "subgraph " << getUID(Region) << " {\n";
  831. bumpIndent(1);
  832. OS << Indent << "fontname=Courier\n"
  833. << Indent << "label=\""
  834. << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
  835. << DOT::EscapeString(Region->getName()) << "\"\n";
  836. // Dump the blocks of the region.
  837. assert(Region->getEntry() && "Region contains no inner blocks.");
  838. for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
  839. dumpBlock(Block);
  840. bumpIndent(-1);
  841. OS << Indent << "}\n";
  842. dumpEdges(Region);
  843. }
  844. void VPlanIngredient::print(raw_ostream &O) const {
  845. if (auto *Inst = dyn_cast<Instruction>(V)) {
  846. if (!Inst->getType()->isVoidTy()) {
  847. Inst->printAsOperand(O, false);
  848. O << " = ";
  849. }
  850. O << Inst->getOpcodeName() << " ";
  851. unsigned E = Inst->getNumOperands();
  852. if (E > 0) {
  853. Inst->getOperand(0)->printAsOperand(O, false);
  854. for (unsigned I = 1; I < E; ++I)
  855. Inst->getOperand(I)->printAsOperand(O << ", ", false);
  856. }
  857. } else // !Inst
  858. V->printAsOperand(O, false);
  859. }
  860. #endif
  861. template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
  862. void VPValue::replaceAllUsesWith(VPValue *New) {
  863. for (unsigned J = 0; J < getNumUsers();) {
  864. VPUser *User = Users[J];
  865. unsigned NumUsers = getNumUsers();
  866. for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
  867. if (User->getOperand(I) == this)
  868. User->setOperand(I, New);
  869. // If a user got removed after updating the current user, the next user to
  870. // update will be moved to the current position, so we only need to
  871. // increment the index if the number of users did not change.
  872. if (NumUsers == getNumUsers())
  873. J++;
  874. }
  875. }
  876. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  877. void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
  878. if (const Value *UV = getUnderlyingValue()) {
  879. OS << "ir<";
  880. UV->printAsOperand(OS, false);
  881. OS << ">";
  882. return;
  883. }
  884. unsigned Slot = Tracker.getSlot(this);
  885. if (Slot == unsigned(-1))
  886. OS << "<badref>";
  887. else
  888. OS << "vp<%" << Tracker.getSlot(this) << ">";
  889. }
  890. void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
  891. interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
  892. Op->printAsOperand(O, SlotTracker);
  893. });
  894. }
  895. #endif
  896. void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
  897. Old2NewTy &Old2New,
  898. InterleavedAccessInfo &IAI) {
  899. ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
  900. RPOT(Region->getEntry());
  901. for (VPBlockBase *Base : RPOT) {
  902. visitBlock(Base, Old2New, IAI);
  903. }
  904. }
  905. void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
  906. InterleavedAccessInfo &IAI) {
  907. if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
  908. for (VPRecipeBase &VPI : *VPBB) {
  909. if (isa<VPHeaderPHIRecipe>(&VPI))
  910. continue;
  911. assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
  912. auto *VPInst = cast<VPInstruction>(&VPI);
  913. auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
  914. if (!Inst)
  915. continue;
  916. auto *IG = IAI.getInterleaveGroup(Inst);
  917. if (!IG)
  918. continue;
  919. auto NewIGIter = Old2New.find(IG);
  920. if (NewIGIter == Old2New.end())
  921. Old2New[IG] = new InterleaveGroup<VPInstruction>(
  922. IG->getFactor(), IG->isReverse(), IG->getAlign());
  923. if (Inst == IG->getInsertPos())
  924. Old2New[IG]->setInsertPos(VPInst);
  925. InterleaveGroupMap[VPInst] = Old2New[IG];
  926. InterleaveGroupMap[VPInst]->insertMember(
  927. VPInst, IG->getIndex(Inst),
  928. Align(IG->isReverse() ? (-1) * int(IG->getFactor())
  929. : IG->getFactor()));
  930. }
  931. } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
  932. visitRegion(Region, Old2New, IAI);
  933. else
  934. llvm_unreachable("Unsupported kind of VPBlock.");
  935. }
  936. VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
  937. InterleavedAccessInfo &IAI) {
  938. Old2NewTy Old2New;
  939. visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
  940. }
  941. void VPSlotTracker::assignSlot(const VPValue *V) {
  942. assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
  943. Slots[V] = NextSlot++;
  944. }
  945. void VPSlotTracker::assignSlots(const VPlan &Plan) {
  946. for (const auto &P : Plan.VPExternalDefs)
  947. assignSlot(P.second);
  948. assignSlot(&Plan.VectorTripCount);
  949. if (Plan.BackedgeTakenCount)
  950. assignSlot(Plan.BackedgeTakenCount);
  951. ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
  952. RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
  953. for (const VPBasicBlock *VPBB :
  954. VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
  955. for (const VPRecipeBase &Recipe : *VPBB)
  956. for (VPValue *Def : Recipe.definedValues())
  957. assignSlot(Def);
  958. }
  959. bool vputils::onlyFirstLaneUsed(VPValue *Def) {
  960. return all_of(Def->users(),
  961. [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
  962. }
  963. VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
  964. ScalarEvolution &SE) {
  965. if (auto *E = dyn_cast<SCEVConstant>(Expr))
  966. return Plan.getOrAddExternalDef(E->getValue());
  967. if (auto *E = dyn_cast<SCEVUnknown>(Expr))
  968. return Plan.getOrAddExternalDef(E->getValue());
  969. VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
  970. VPExpandSCEVRecipe *Step = new VPExpandSCEVRecipe(Expr, SE);
  971. Preheader->appendRecipe(Step);
  972. return Step;
  973. }