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
19 #include "VPlan.h"
20 #include "VPlanDominatorTree.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/IVDescriptors.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/InstrTypes.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/ErrorHandling.h"
38 #include "llvm/Support/GenericDomTreeConstruction.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include <cassert>
43 #include <iterator>
44 #include <string>
45 #include <vector>
46
47 using namespace llvm;
48 extern cl::opt<bool> EnableVPlanNativePath;
49
50 #define DEBUG_TYPE "vplan"
51
operator <<(raw_ostream & OS,const VPValue & V)52 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
53 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
54 VPSlotTracker SlotTracker(
55 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
56 V.print(OS, SlotTracker);
57 return OS;
58 }
59
VPValue(const unsigned char SC,Value * UV,VPDef * Def)60 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
61 : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
62 if (Def)
63 Def->addDefinedValue(this);
64 }
65
~VPValue()66 VPValue::~VPValue() {
67 assert(Users.empty() && "trying to delete a VPValue with remaining users");
68 if (Def)
69 Def->removeDefinedValue(this);
70 }
71
print(raw_ostream & OS,VPSlotTracker & SlotTracker) const72 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
73 if (const VPInstruction *Instr = dyn_cast<VPInstruction>(this))
74 Instr->print(OS, SlotTracker);
75 else
76 printAsOperand(OS, SlotTracker);
77 }
78
dump() const79 void VPValue::dump() const {
80 const VPInstruction *Instr = dyn_cast<VPInstruction>(this);
81 VPSlotTracker SlotTracker(
82 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
83 print(dbgs(), SlotTracker);
84 dbgs() << "\n";
85 }
86
dump() const87 void VPRecipeBase::dump() const {
88 VPSlotTracker SlotTracker(nullptr);
89 print(dbgs(), "", SlotTracker);
90 dbgs() << "\n";
91 }
92
toVPUser()93 VPUser *VPRecipeBase::toVPUser() {
94 if (auto *U = dyn_cast<VPInstruction>(this))
95 return U;
96 if (auto *U = dyn_cast<VPWidenRecipe>(this))
97 return U;
98 if (auto *U = dyn_cast<VPWidenCallRecipe>(this))
99 return U;
100 if (auto *U = dyn_cast<VPWidenSelectRecipe>(this))
101 return U;
102 if (auto *U = dyn_cast<VPWidenGEPRecipe>(this))
103 return U;
104 if (auto *U = dyn_cast<VPBlendRecipe>(this))
105 return U;
106 if (auto *U = dyn_cast<VPInterleaveRecipe>(this))
107 return U;
108 if (auto *U = dyn_cast<VPReplicateRecipe>(this))
109 return U;
110 if (auto *U = dyn_cast<VPBranchOnMaskRecipe>(this))
111 return U;
112 if (auto *U = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
113 return U;
114 if (auto *U = dyn_cast<VPReductionRecipe>(this))
115 return U;
116 if (auto *U = dyn_cast<VPPredInstPHIRecipe>(this))
117 return U;
118 return nullptr;
119 }
120
toVPValue()121 VPValue *VPRecipeBase::toVPValue() {
122 if (auto *V = dyn_cast<VPInstruction>(this))
123 return V;
124 if (auto *V = dyn_cast<VPReductionRecipe>(this))
125 return V;
126 if (auto *V = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
127 return V;
128 if (auto *V = dyn_cast<VPWidenCallRecipe>(this))
129 return V;
130 if (auto *V = dyn_cast<VPWidenSelectRecipe>(this))
131 return V;
132 if (auto *V = dyn_cast<VPWidenGEPRecipe>(this))
133 return V;
134 if (auto *V = dyn_cast<VPWidenRecipe>(this))
135 return V;
136 if (auto *V = dyn_cast<VPReplicateRecipe>(this))
137 return V;
138 return nullptr;
139 }
140
toVPValue() const141 const VPValue *VPRecipeBase::toVPValue() const {
142 if (auto *V = dyn_cast<VPInstruction>(this))
143 return V;
144 if (auto *V = dyn_cast<VPReductionRecipe>(this))
145 return V;
146 if (auto *V = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
147 return V;
148 if (auto *V = dyn_cast<VPWidenCallRecipe>(this))
149 return V;
150 if (auto *V = dyn_cast<VPWidenSelectRecipe>(this))
151 return V;
152 if (auto *V = dyn_cast<VPWidenGEPRecipe>(this))
153 return V;
154 if (auto *V = dyn_cast<VPWidenRecipe>(this))
155 return V;
156 if (auto *V = dyn_cast<VPReplicateRecipe>(this))
157 return V;
158 return nullptr;
159 }
160
161 // Get the top-most entry block of \p Start. This is the entry block of the
162 // containing VPlan. This function is templated to support both const and non-const blocks
getPlanEntry(T * Start)163 template <typename T> static T *getPlanEntry(T *Start) {
164 T *Next = Start;
165 T *Current = Start;
166 while ((Next = Next->getParent()))
167 Current = Next;
168
169 SmallSetVector<T *, 8> WorkList;
170 WorkList.insert(Current);
171
172 for (unsigned i = 0; i < WorkList.size(); i++) {
173 T *Current = WorkList[i];
174 if (Current->getNumPredecessors() == 0)
175 return Current;
176 auto &Predecessors = Current->getPredecessors();
177 WorkList.insert(Predecessors.begin(), Predecessors.end());
178 }
179
180 llvm_unreachable("VPlan without any entry node without predecessors");
181 }
182
getPlan()183 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
184
getPlan() const185 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
186
187 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
getEntryBasicBlock() const188 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
189 const VPBlockBase *Block = this;
190 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
191 Block = Region->getEntry();
192 return cast<VPBasicBlock>(Block);
193 }
194
getEntryBasicBlock()195 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
196 VPBlockBase *Block = this;
197 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
198 Block = Region->getEntry();
199 return cast<VPBasicBlock>(Block);
200 }
201
setPlan(VPlan * ParentPlan)202 void VPBlockBase::setPlan(VPlan *ParentPlan) {
203 assert(ParentPlan->getEntry() == this &&
204 "Can only set plan on its entry block.");
205 Plan = ParentPlan;
206 }
207
208 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
getExitBasicBlock() const209 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
210 const VPBlockBase *Block = this;
211 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
212 Block = Region->getExit();
213 return cast<VPBasicBlock>(Block);
214 }
215
getExitBasicBlock()216 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
217 VPBlockBase *Block = this;
218 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
219 Block = Region->getExit();
220 return cast<VPBasicBlock>(Block);
221 }
222
getEnclosingBlockWithSuccessors()223 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
224 if (!Successors.empty() || !Parent)
225 return this;
226 assert(Parent->getExit() == this &&
227 "Block w/o successors not the exit of its parent.");
228 return Parent->getEnclosingBlockWithSuccessors();
229 }
230
getEnclosingBlockWithPredecessors()231 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
232 if (!Predecessors.empty() || !Parent)
233 return this;
234 assert(Parent->getEntry() == this &&
235 "Block w/o predecessors not the entry of its parent.");
236 return Parent->getEnclosingBlockWithPredecessors();
237 }
238
deleteCFG(VPBlockBase * Entry)239 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
240 SmallVector<VPBlockBase *, 8> Blocks;
241
242 for (VPBlockBase *Block : depth_first(Entry))
243 Blocks.push_back(Block);
244
245 for (VPBlockBase *Block : Blocks)
246 delete Block;
247 }
248
getFirstNonPhi()249 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
250 iterator It = begin();
251 while (It != end() && (isa<VPWidenPHIRecipe>(&*It) ||
252 isa<VPWidenIntOrFpInductionRecipe>(&*It) ||
253 isa<VPPredInstPHIRecipe>(&*It) ||
254 isa<VPWidenCanonicalIVRecipe>(&*It)))
255 It++;
256 return It;
257 }
258
259 BasicBlock *
createEmptyBasicBlock(VPTransformState::CFGState & CFG)260 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
261 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
262 // Pred stands for Predessor. Prev stands for Previous - last visited/created.
263 BasicBlock *PrevBB = CFG.PrevBB;
264 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
265 PrevBB->getParent(), CFG.LastBB);
266 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
267
268 // Hook up the new basic block to its predecessors.
269 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
270 VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
271 auto &PredVPSuccessors = PredVPBB->getSuccessors();
272 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
273
274 // In outer loop vectorization scenario, the predecessor BBlock may not yet
275 // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
276 // vectorization. We do not encounter this case in inner loop vectorization
277 // as we start out by building a loop skeleton with the vector loop header
278 // and latch blocks. As a result, we never enter this function for the
279 // header block in the non VPlan-native path.
280 if (!PredBB) {
281 assert(EnableVPlanNativePath &&
282 "Unexpected null predecessor in non VPlan-native path");
283 CFG.VPBBsToFix.push_back(PredVPBB);
284 continue;
285 }
286
287 assert(PredBB && "Predecessor basic-block not found building successor.");
288 auto *PredBBTerminator = PredBB->getTerminator();
289 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
290 if (isa<UnreachableInst>(PredBBTerminator)) {
291 assert(PredVPSuccessors.size() == 1 &&
292 "Predecessor ending w/o branch must have single successor.");
293 PredBBTerminator->eraseFromParent();
294 BranchInst::Create(NewBB, PredBB);
295 } else {
296 assert(PredVPSuccessors.size() == 2 &&
297 "Predecessor ending with branch must have two successors.");
298 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
299 assert(!PredBBTerminator->getSuccessor(idx) &&
300 "Trying to reset an existing successor block.");
301 PredBBTerminator->setSuccessor(idx, NewBB);
302 }
303 }
304 return NewBB;
305 }
306
execute(VPTransformState * State)307 void VPBasicBlock::execute(VPTransformState *State) {
308 bool Replica = State->Instance &&
309 !(State->Instance->Part == 0 && State->Instance->Lane == 0);
310 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
311 VPBlockBase *SingleHPred = nullptr;
312 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
313
314 // 1. Create an IR basic block, or reuse the last one if possible.
315 // The last IR basic block is reused, as an optimization, in three cases:
316 // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
317 // B. when the current VPBB has a single (hierarchical) predecessor which
318 // is PrevVPBB and the latter has a single (hierarchical) successor; and
319 // C. when the current VPBB is an entry of a region replica - where PrevVPBB
320 // is the exit of this region from a previous instance, or the predecessor
321 // of this region.
322 if (PrevVPBB && /* A */
323 !((SingleHPred = getSingleHierarchicalPredecessor()) &&
324 SingleHPred->getExitBasicBlock() == PrevVPBB &&
325 PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
326 !(Replica && getPredecessors().empty())) { /* C */
327 NewBB = createEmptyBasicBlock(State->CFG);
328 State->Builder.SetInsertPoint(NewBB);
329 // Temporarily terminate with unreachable until CFG is rewired.
330 UnreachableInst *Terminator = State->Builder.CreateUnreachable();
331 State->Builder.SetInsertPoint(Terminator);
332 // Register NewBB in its loop. In innermost loops its the same for all BB's.
333 Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
334 L->addBasicBlockToLoop(NewBB, *State->LI);
335 State->CFG.PrevBB = NewBB;
336 }
337
338 // 2. Fill the IR basic block with IR instructions.
339 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
340 << " in BB:" << NewBB->getName() << '\n');
341
342 State->CFG.VPBB2IRBB[this] = NewBB;
343 State->CFG.PrevVPBB = this;
344
345 for (VPRecipeBase &Recipe : Recipes)
346 Recipe.execute(*State);
347
348 VPValue *CBV;
349 if (EnableVPlanNativePath && (CBV = getCondBit())) {
350 Value *IRCBV = CBV->getUnderlyingValue();
351 assert(IRCBV && "Unexpected null underlying value for condition bit");
352
353 // Condition bit value in a VPBasicBlock is used as the branch selector. In
354 // the VPlan-native path case, since all branches are uniform we generate a
355 // branch instruction using the condition value from vector lane 0 and dummy
356 // successors. The successors are fixed later when the successor blocks are
357 // visited.
358 Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
359 NewCond = State->Builder.CreateExtractElement(NewCond,
360 State->Builder.getInt32(0));
361
362 // Replace the temporary unreachable terminator with the new conditional
363 // branch.
364 auto *CurrentTerminator = NewBB->getTerminator();
365 assert(isa<UnreachableInst>(CurrentTerminator) &&
366 "Expected to replace unreachable terminator with conditional "
367 "branch.");
368 auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
369 CondBr->setSuccessor(0, nullptr);
370 ReplaceInstWithInst(CurrentTerminator, CondBr);
371 }
372
373 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
374 }
375
dropAllReferences(VPValue * NewValue)376 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
377 for (VPRecipeBase &R : Recipes) {
378 if (auto *VPV = R.toVPValue())
379 VPV->replaceAllUsesWith(NewValue);
380
381 if (auto *User = R.toVPUser())
382 for (unsigned I = 0, E = User->getNumOperands(); I != E; I++)
383 User->setOperand(I, NewValue);
384 }
385 }
386
dropAllReferences(VPValue * NewValue)387 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
388 for (VPBlockBase *Block : depth_first(Entry))
389 // Drop all references in VPBasicBlocks and replace all uses with
390 // DummyValue.
391 Block->dropAllReferences(NewValue);
392 }
393
execute(VPTransformState * State)394 void VPRegionBlock::execute(VPTransformState *State) {
395 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
396
397 if (!isReplicator()) {
398 // Visit the VPBlocks connected to "this", starting from it.
399 for (VPBlockBase *Block : RPOT) {
400 if (EnableVPlanNativePath) {
401 // The inner loop vectorization path does not represent loop preheader
402 // and exit blocks as part of the VPlan. In the VPlan-native path, skip
403 // vectorizing loop preheader block. In future, we may replace this
404 // check with the check for loop preheader.
405 if (Block->getNumPredecessors() == 0)
406 continue;
407
408 // Skip vectorizing loop exit block. In future, we may replace this
409 // check with the check for loop exit.
410 if (Block->getNumSuccessors() == 0)
411 continue;
412 }
413
414 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
415 Block->execute(State);
416 }
417 return;
418 }
419
420 assert(!State->Instance && "Replicating a Region with non-null instance.");
421
422 // Enter replicating mode.
423 State->Instance = {0, 0};
424
425 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
426 State->Instance->Part = Part;
427 assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
428 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
429 ++Lane) {
430 State->Instance->Lane = Lane;
431 // Visit the VPBlocks connected to \p this, starting from it.
432 for (VPBlockBase *Block : RPOT) {
433 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
434 Block->execute(State);
435 }
436 }
437 }
438
439 // Exit replicating mode.
440 State->Instance.reset();
441 }
442
insertBefore(VPRecipeBase * InsertPos)443 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
444 assert(!Parent && "Recipe already in some VPBasicBlock");
445 assert(InsertPos->getParent() &&
446 "Insertion position not in any VPBasicBlock");
447 Parent = InsertPos->getParent();
448 Parent->getRecipeList().insert(InsertPos->getIterator(), this);
449 }
450
insertAfter(VPRecipeBase * InsertPos)451 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
452 assert(!Parent && "Recipe already in some VPBasicBlock");
453 assert(InsertPos->getParent() &&
454 "Insertion position not in any VPBasicBlock");
455 Parent = InsertPos->getParent();
456 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
457 }
458
removeFromParent()459 void VPRecipeBase::removeFromParent() {
460 assert(getParent() && "Recipe not in any VPBasicBlock");
461 getParent()->getRecipeList().remove(getIterator());
462 Parent = nullptr;
463 }
464
eraseFromParent()465 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
466 assert(getParent() && "Recipe not in any VPBasicBlock");
467 return getParent()->getRecipeList().erase(getIterator());
468 }
469
moveAfter(VPRecipeBase * InsertPos)470 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
471 removeFromParent();
472 insertAfter(InsertPos);
473 }
474
generateInstruction(VPTransformState & State,unsigned Part)475 void VPInstruction::generateInstruction(VPTransformState &State,
476 unsigned Part) {
477 IRBuilder<> &Builder = State.Builder;
478
479 if (Instruction::isBinaryOp(getOpcode())) {
480 Value *A = State.get(getOperand(0), Part);
481 Value *B = State.get(getOperand(1), Part);
482 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
483 State.set(this, V, Part);
484 return;
485 }
486
487 switch (getOpcode()) {
488 case VPInstruction::Not: {
489 Value *A = State.get(getOperand(0), Part);
490 Value *V = Builder.CreateNot(A);
491 State.set(this, V, Part);
492 break;
493 }
494 case VPInstruction::ICmpULE: {
495 Value *IV = State.get(getOperand(0), Part);
496 Value *TC = State.get(getOperand(1), Part);
497 Value *V = Builder.CreateICmpULE(IV, TC);
498 State.set(this, V, Part);
499 break;
500 }
501 case Instruction::Select: {
502 Value *Cond = State.get(getOperand(0), Part);
503 Value *Op1 = State.get(getOperand(1), Part);
504 Value *Op2 = State.get(getOperand(2), Part);
505 Value *V = Builder.CreateSelect(Cond, Op1, Op2);
506 State.set(this, V, Part);
507 break;
508 }
509 case VPInstruction::ActiveLaneMask: {
510 // Get first lane of vector induction variable.
511 Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
512 // Get the original loop tripcount.
513 Value *ScalarTC = State.TripCount;
514
515 auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
516 auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
517 Instruction *Call = Builder.CreateIntrinsic(
518 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
519 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
520 State.set(this, Call, Part);
521 break;
522 }
523 default:
524 llvm_unreachable("Unsupported opcode for instruction");
525 }
526 }
527
execute(VPTransformState & State)528 void VPInstruction::execute(VPTransformState &State) {
529 assert(!State.Instance && "VPInstruction executing an Instance");
530 for (unsigned Part = 0; Part < State.UF; ++Part)
531 generateInstruction(State, Part);
532 }
533
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const534 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
535 VPSlotTracker &SlotTracker) const {
536 O << "\"EMIT ";
537 print(O, SlotTracker);
538 }
539
print(raw_ostream & O) const540 void VPInstruction::print(raw_ostream &O) const {
541 VPSlotTracker SlotTracker(getParent()->getPlan());
542 print(O, SlotTracker);
543 }
544
print(raw_ostream & O,VPSlotTracker & SlotTracker) const545 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
546 if (hasResult()) {
547 printAsOperand(O, SlotTracker);
548 O << " = ";
549 }
550
551 switch (getOpcode()) {
552 case VPInstruction::Not:
553 O << "not";
554 break;
555 case VPInstruction::ICmpULE:
556 O << "icmp ule";
557 break;
558 case VPInstruction::SLPLoad:
559 O << "combined load";
560 break;
561 case VPInstruction::SLPStore:
562 O << "combined store";
563 break;
564 case VPInstruction::ActiveLaneMask:
565 O << "active lane mask";
566 break;
567
568 default:
569 O << Instruction::getOpcodeName(getOpcode());
570 }
571
572 for (const VPValue *Operand : operands()) {
573 O << " ";
574 Operand->printAsOperand(O, SlotTracker);
575 }
576 }
577
578 /// Generate the code inside the body of the vectorized loop. Assumes a single
579 /// LoopVectorBody basic-block was created for this. Introduce additional
580 /// basic-blocks as needed, and fill them all.
execute(VPTransformState * State)581 void VPlan::execute(VPTransformState *State) {
582 // -1. Check if the backedge taken count is needed, and if so build it.
583 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
584 Value *TC = State->TripCount;
585 IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
586 auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
587 "trip.count.minus.1");
588 auto VF = State->VF;
589 Value *VTCMO =
590 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
591 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
592 State->set(BackedgeTakenCount, VTCMO, Part);
593 }
594
595 // 0. Set the reverse mapping from VPValues to Values for code generation.
596 for (auto &Entry : Value2VPValue)
597 State->VPValue2Value[Entry.second] = Entry.first;
598
599 BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
600 BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
601 assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
602
603 // 1. Make room to generate basic-blocks inside loop body if needed.
604 BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
605 VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
606 Loop *L = State->LI->getLoopFor(VectorHeaderBB);
607 L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
608 // Remove the edge between Header and Latch to allow other connections.
609 // Temporarily terminate with unreachable until CFG is rewired.
610 // Note: this asserts the generated code's assumption that
611 // getFirstInsertionPt() can be dereferenced into an Instruction.
612 VectorHeaderBB->getTerminator()->eraseFromParent();
613 State->Builder.SetInsertPoint(VectorHeaderBB);
614 UnreachableInst *Terminator = State->Builder.CreateUnreachable();
615 State->Builder.SetInsertPoint(Terminator);
616
617 // 2. Generate code in loop body.
618 State->CFG.PrevVPBB = nullptr;
619 State->CFG.PrevBB = VectorHeaderBB;
620 State->CFG.LastBB = VectorLatchBB;
621
622 for (VPBlockBase *Block : depth_first(Entry))
623 Block->execute(State);
624
625 // Setup branch terminator successors for VPBBs in VPBBsToFix based on
626 // VPBB's successors.
627 for (auto VPBB : State->CFG.VPBBsToFix) {
628 assert(EnableVPlanNativePath &&
629 "Unexpected VPBBsToFix in non VPlan-native path");
630 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
631 assert(BB && "Unexpected null basic block for VPBB");
632
633 unsigned Idx = 0;
634 auto *BBTerminator = BB->getTerminator();
635
636 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
637 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
638 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
639 ++Idx;
640 }
641 }
642
643 // 3. Merge the temporary latch created with the last basic-block filled.
644 BasicBlock *LastBB = State->CFG.PrevBB;
645 // Connect LastBB to VectorLatchBB to facilitate their merge.
646 assert((EnableVPlanNativePath ||
647 isa<UnreachableInst>(LastBB->getTerminator())) &&
648 "Expected InnerLoop VPlan CFG to terminate with unreachable");
649 assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
650 "Expected VPlan CFG to terminate with branch in NativePath");
651 LastBB->getTerminator()->eraseFromParent();
652 BranchInst::Create(VectorLatchBB, LastBB);
653
654 // Merge LastBB with Latch.
655 bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
656 (void)Merged;
657 assert(Merged && "Could not merge last basic block with latch.");
658 VectorLatchBB = LastBB;
659
660 // We do not attempt to preserve DT for outer loop vectorization currently.
661 if (!EnableVPlanNativePath)
662 updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
663 L->getExitBlock());
664 }
665
666 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
667 LLVM_DUMP_METHOD
dump() const668 void VPlan::dump() const { dbgs() << *this << '\n'; }
669 #endif
670
updateDominatorTree(DominatorTree * DT,BasicBlock * LoopPreHeaderBB,BasicBlock * LoopLatchBB,BasicBlock * LoopExitBB)671 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
672 BasicBlock *LoopLatchBB,
673 BasicBlock *LoopExitBB) {
674 BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
675 assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
676 // The vector body may be more than a single basic-block by this point.
677 // Update the dominator tree information inside the vector body by propagating
678 // it from header to latch, expecting only triangular control-flow, if any.
679 BasicBlock *PostDomSucc = nullptr;
680 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
681 // Get the list of successors of this block.
682 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
683 assert(Succs.size() <= 2 &&
684 "Basic block in vector loop has more than 2 successors.");
685 PostDomSucc = Succs[0];
686 if (Succs.size() == 1) {
687 assert(PostDomSucc->getSinglePredecessor() &&
688 "PostDom successor has more than one predecessor.");
689 DT->addNewBlock(PostDomSucc, BB);
690 continue;
691 }
692 BasicBlock *InterimSucc = Succs[1];
693 if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
694 PostDomSucc = Succs[1];
695 InterimSucc = Succs[0];
696 }
697 assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
698 "One successor of a basic block does not lead to the other.");
699 assert(InterimSucc->getSinglePredecessor() &&
700 "Interim successor has more than one predecessor.");
701 assert(PostDomSucc->hasNPredecessors(2) &&
702 "PostDom successor has more than two predecessors.");
703 DT->addNewBlock(InterimSucc, BB);
704 DT->addNewBlock(PostDomSucc, BB);
705 }
706 // Latch block is a new dominator for the loop exit.
707 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
708 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
709 }
710
getUID(const VPBlockBase * Block)711 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
712 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
713 Twine(getOrCreateBID(Block));
714 }
715
getOrCreateName(const VPBlockBase * Block)716 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
717 const std::string &Name = Block->getName();
718 if (!Name.empty())
719 return Name;
720 return "VPB" + Twine(getOrCreateBID(Block));
721 }
722
dump()723 void VPlanPrinter::dump() {
724 Depth = 1;
725 bumpIndent(0);
726 OS << "digraph VPlan {\n";
727 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
728 if (!Plan.getName().empty())
729 OS << "\\n" << DOT::EscapeString(Plan.getName());
730 if (Plan.BackedgeTakenCount) {
731 OS << ", where:\\n";
732 Plan.BackedgeTakenCount->print(OS, SlotTracker);
733 OS << " := BackedgeTakenCount";
734 }
735 OS << "\"]\n";
736 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
737 OS << "edge [fontname=Courier, fontsize=30]\n";
738 OS << "compound=true\n";
739
740 for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
741 dumpBlock(Block);
742
743 OS << "}\n";
744 }
745
dumpBlock(const VPBlockBase * Block)746 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
747 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
748 dumpBasicBlock(BasicBlock);
749 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
750 dumpRegion(Region);
751 else
752 llvm_unreachable("Unsupported kind of VPBlock.");
753 }
754
drawEdge(const VPBlockBase * From,const VPBlockBase * To,bool Hidden,const Twine & Label)755 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
756 bool Hidden, const Twine &Label) {
757 // Due to "dot" we print an edge between two regions as an edge between the
758 // exit basic block and the entry basic of the respective regions.
759 const VPBlockBase *Tail = From->getExitBasicBlock();
760 const VPBlockBase *Head = To->getEntryBasicBlock();
761 OS << Indent << getUID(Tail) << " -> " << getUID(Head);
762 OS << " [ label=\"" << Label << '\"';
763 if (Tail != From)
764 OS << " ltail=" << getUID(From);
765 if (Head != To)
766 OS << " lhead=" << getUID(To);
767 if (Hidden)
768 OS << "; splines=none";
769 OS << "]\n";
770 }
771
dumpEdges(const VPBlockBase * Block)772 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
773 auto &Successors = Block->getSuccessors();
774 if (Successors.size() == 1)
775 drawEdge(Block, Successors.front(), false, "");
776 else if (Successors.size() == 2) {
777 drawEdge(Block, Successors.front(), false, "T");
778 drawEdge(Block, Successors.back(), false, "F");
779 } else {
780 unsigned SuccessorNumber = 0;
781 for (auto *Successor : Successors)
782 drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
783 }
784 }
785
dumpBasicBlock(const VPBasicBlock * BasicBlock)786 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
787 OS << Indent << getUID(BasicBlock) << " [label =\n";
788 bumpIndent(1);
789 OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
790 bumpIndent(1);
791
792 // Dump the block predicate.
793 const VPValue *Pred = BasicBlock->getPredicate();
794 if (Pred) {
795 OS << " +\n" << Indent << " \"BlockPredicate: ";
796 if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
797 PredI->printAsOperand(OS, SlotTracker);
798 OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
799 << ")\\l\"";
800 } else
801 Pred->printAsOperand(OS, SlotTracker);
802 }
803
804 for (const VPRecipeBase &Recipe : *BasicBlock) {
805 OS << " +\n" << Indent;
806 Recipe.print(OS, Indent, SlotTracker);
807 OS << "\\l\"";
808 }
809
810 // Dump the condition bit.
811 const VPValue *CBV = BasicBlock->getCondBit();
812 if (CBV) {
813 OS << " +\n" << Indent << " \"CondBit: ";
814 if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
815 CBI->printAsOperand(OS, SlotTracker);
816 OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
817 } else {
818 CBV->printAsOperand(OS, SlotTracker);
819 OS << "\"";
820 }
821 }
822
823 bumpIndent(-2);
824 OS << "\n" << Indent << "]\n";
825 dumpEdges(BasicBlock);
826 }
827
dumpRegion(const VPRegionBlock * Region)828 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
829 OS << Indent << "subgraph " << getUID(Region) << " {\n";
830 bumpIndent(1);
831 OS << Indent << "fontname=Courier\n"
832 << Indent << "label=\""
833 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
834 << DOT::EscapeString(Region->getName()) << "\"\n";
835 // Dump the blocks of the region.
836 assert(Region->getEntry() && "Region contains no inner blocks.");
837 for (const VPBlockBase *Block : depth_first(Region->getEntry()))
838 dumpBlock(Block);
839 bumpIndent(-1);
840 OS << Indent << "}\n";
841 dumpEdges(Region);
842 }
843
printAsIngredient(raw_ostream & O,const Value * V)844 void VPlanPrinter::printAsIngredient(raw_ostream &O, const Value *V) {
845 std::string IngredientString;
846 raw_string_ostream RSO(IngredientString);
847 if (auto *Inst = dyn_cast<Instruction>(V)) {
848 if (!Inst->getType()->isVoidTy()) {
849 Inst->printAsOperand(RSO, false);
850 RSO << " = ";
851 }
852 RSO << Inst->getOpcodeName() << " ";
853 unsigned E = Inst->getNumOperands();
854 if (E > 0) {
855 Inst->getOperand(0)->printAsOperand(RSO, false);
856 for (unsigned I = 1; I < E; ++I)
857 Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
858 }
859 } else // !Inst
860 V->printAsOperand(RSO, false);
861 RSO.flush();
862 O << DOT::EscapeString(IngredientString);
863 }
864
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const865 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
866 VPSlotTracker &SlotTracker) const {
867 O << "\"WIDEN-CALL ";
868
869 auto *CI = cast<CallInst>(getUnderlyingInstr());
870 if (CI->getType()->isVoidTy())
871 O << "void ";
872 else {
873 printAsOperand(O, SlotTracker);
874 O << " = ";
875 }
876
877 O << "call @" << CI->getCalledFunction()->getName() << "(";
878 printOperands(O, SlotTracker);
879 O << ")";
880 }
881
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const882 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
883 VPSlotTracker &SlotTracker) const {
884 O << "\"WIDEN-SELECT ";
885 printAsOperand(O, SlotTracker);
886 O << " = select ";
887 getOperand(0)->printAsOperand(O, SlotTracker);
888 O << ", ";
889 getOperand(1)->printAsOperand(O, SlotTracker);
890 O << ", ";
891 getOperand(2)->printAsOperand(O, SlotTracker);
892 O << (InvariantCond ? " (condition is loop invariant)" : "");
893 }
894
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const895 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
896 VPSlotTracker &SlotTracker) const {
897 O << "\"WIDEN ";
898 printAsOperand(O, SlotTracker);
899 O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
900 printOperands(O, SlotTracker);
901 }
902
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const903 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
904 VPSlotTracker &SlotTracker) const {
905 O << "\"WIDEN-INDUCTION";
906 if (Trunc) {
907 O << "\\l\"";
908 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\"";
909 O << " +\n" << Indent << "\" " << VPlanIngredient(Trunc);
910 } else
911 O << " " << VPlanIngredient(IV);
912 }
913
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const914 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
915 VPSlotTracker &SlotTracker) const {
916 O << "\"WIDEN-GEP ";
917 O << (IsPtrLoopInvariant ? "Inv" : "Var");
918 size_t IndicesNumber = IsIndexLoopInvariant.size();
919 for (size_t I = 0; I < IndicesNumber; ++I)
920 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
921
922 O << " ";
923 printAsOperand(O, SlotTracker);
924 O << " = getelementptr ";
925 printOperands(O, SlotTracker);
926 }
927
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const928 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
929 VPSlotTracker &SlotTracker) const {
930 O << "\"WIDEN-PHI " << VPlanIngredient(Phi);
931 }
932
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const933 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
934 VPSlotTracker &SlotTracker) const {
935 O << "\"BLEND ";
936 Phi->printAsOperand(O, false);
937 O << " =";
938 if (getNumIncomingValues() == 1) {
939 // Not a User of any mask: not really blending, this is a
940 // single-predecessor phi.
941 O << " ";
942 getIncomingValue(0)->printAsOperand(O, SlotTracker);
943 } else {
944 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
945 O << " ";
946 getIncomingValue(I)->printAsOperand(O, SlotTracker);
947 O << "/";
948 getMask(I)->printAsOperand(O, SlotTracker);
949 }
950 }
951 }
952
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const953 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
954 VPSlotTracker &SlotTracker) const {
955 O << "\"REDUCE ";
956 printAsOperand(O, SlotTracker);
957 O << " = ";
958 getChainOp()->printAsOperand(O, SlotTracker);
959 O << " + reduce." << Instruction::getOpcodeName(RdxDesc->getRecurrenceBinOp())
960 << " (";
961 getVecOp()->printAsOperand(O, SlotTracker);
962 if (getCondOp()) {
963 O << ", ";
964 getCondOp()->printAsOperand(O, SlotTracker);
965 }
966 O << ")";
967 }
968
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const969 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
970 VPSlotTracker &SlotTracker) const {
971 O << "\"" << (IsUniform ? "CLONE " : "REPLICATE ");
972
973 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
974 printAsOperand(O, SlotTracker);
975 O << " = ";
976 }
977 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
978 printOperands(O, SlotTracker);
979
980 if (AlsoPack)
981 O << " (S->V)";
982 }
983
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const984 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
985 VPSlotTracker &SlotTracker) const {
986 O << "\"PHI-PREDICATED-INSTRUCTION ";
987 printOperands(O, SlotTracker);
988 }
989
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const990 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
991 VPSlotTracker &SlotTracker) const {
992 O << "\"WIDEN ";
993
994 if (!isStore()) {
995 printAsOperand(O, SlotTracker);
996 O << " = ";
997 }
998 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
999
1000 printOperands(O, SlotTracker);
1001 }
1002
execute(VPTransformState & State)1003 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
1004 Value *CanonicalIV = State.CanonicalIV;
1005 Type *STy = CanonicalIV->getType();
1006 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
1007 ElementCount VF = State.VF;
1008 assert(!VF.isScalable() && "the code following assumes non scalables ECs");
1009 Value *VStart = VF.isScalar()
1010 ? CanonicalIV
1011 : Builder.CreateVectorSplat(VF.getKnownMinValue(),
1012 CanonicalIV, "broadcast");
1013 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
1014 SmallVector<Constant *, 8> Indices;
1015 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
1016 Indices.push_back(
1017 ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
1018 // If VF == 1, there is only one iteration in the loop above, thus the
1019 // element pushed back into Indices is ConstantInt::get(STy, Part)
1020 Constant *VStep =
1021 VF.isScalar() ? Indices.back() : ConstantVector::get(Indices);
1022 // Add the consecutive indices to the vector value.
1023 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
1024 State.set(getVPValue(), CanonicalVectorIV, Part);
1025 }
1026 }
1027
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const1028 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
1029 VPSlotTracker &SlotTracker) const {
1030 O << "\"EMIT ";
1031 getVPValue()->printAsOperand(O, SlotTracker);
1032 O << " = WIDEN-CANONICAL-INDUCTION";
1033 }
1034
1035 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1036
replaceAllUsesWith(VPValue * New)1037 void VPValue::replaceAllUsesWith(VPValue *New) {
1038 for (unsigned J = 0; J < getNumUsers();) {
1039 VPUser *User = Users[J];
1040 unsigned NumUsers = getNumUsers();
1041 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1042 if (User->getOperand(I) == this)
1043 User->setOperand(I, New);
1044 // If a user got removed after updating the current user, the next user to
1045 // update will be moved to the current position, so we only need to
1046 // increment the index if the number of users did not change.
1047 if (NumUsers == getNumUsers())
1048 J++;
1049 }
1050 }
1051
printAsOperand(raw_ostream & OS,VPSlotTracker & Tracker) const1052 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1053 if (const Value *UV = getUnderlyingValue()) {
1054 OS << "ir<";
1055 UV->printAsOperand(OS, false);
1056 OS << ">";
1057 return;
1058 }
1059
1060 unsigned Slot = Tracker.getSlot(this);
1061 if (Slot == unsigned(-1))
1062 OS << "<badref>";
1063 else
1064 OS << "vp<%" << Tracker.getSlot(this) << ">";
1065 }
1066
printOperands(raw_ostream & O,VPSlotTracker & SlotTracker) const1067 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1068 bool First = true;
1069 for (VPValue *Op : operands()) {
1070 if (!First)
1071 O << ", ";
1072 Op->printAsOperand(O, SlotTracker);
1073 First = false;
1074 }
1075 }
1076
visitRegion(VPRegionBlock * Region,Old2NewTy & Old2New,InterleavedAccessInfo & IAI)1077 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1078 Old2NewTy &Old2New,
1079 InterleavedAccessInfo &IAI) {
1080 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1081 for (VPBlockBase *Base : RPOT) {
1082 visitBlock(Base, Old2New, IAI);
1083 }
1084 }
1085
visitBlock(VPBlockBase * Block,Old2NewTy & Old2New,InterleavedAccessInfo & IAI)1086 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1087 InterleavedAccessInfo &IAI) {
1088 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1089 for (VPRecipeBase &VPI : *VPBB) {
1090 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1091 auto *VPInst = cast<VPInstruction>(&VPI);
1092 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1093 auto *IG = IAI.getInterleaveGroup(Inst);
1094 if (!IG)
1095 continue;
1096
1097 auto NewIGIter = Old2New.find(IG);
1098 if (NewIGIter == Old2New.end())
1099 Old2New[IG] = new InterleaveGroup<VPInstruction>(
1100 IG->getFactor(), IG->isReverse(), IG->getAlign());
1101
1102 if (Inst == IG->getInsertPos())
1103 Old2New[IG]->setInsertPos(VPInst);
1104
1105 InterleaveGroupMap[VPInst] = Old2New[IG];
1106 InterleaveGroupMap[VPInst]->insertMember(
1107 VPInst, IG->getIndex(Inst),
1108 Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1109 : IG->getFactor()));
1110 }
1111 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1112 visitRegion(Region, Old2New, IAI);
1113 else
1114 llvm_unreachable("Unsupported kind of VPBlock.");
1115 }
1116
VPInterleavedAccessInfo(VPlan & Plan,InterleavedAccessInfo & IAI)1117 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1118 InterleavedAccessInfo &IAI) {
1119 Old2NewTy Old2New;
1120 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1121 }
1122
assignSlot(const VPValue * V)1123 void VPSlotTracker::assignSlot(const VPValue *V) {
1124 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1125 const Value *UV = V->getUnderlyingValue();
1126 if (UV)
1127 return;
1128 const auto *VPI = dyn_cast<VPInstruction>(V);
1129 if (VPI && !VPI->hasResult())
1130 return;
1131
1132 Slots[V] = NextSlot++;
1133 }
1134
assignSlots(const VPBlockBase * VPBB)1135 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
1136 if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
1137 assignSlots(Region);
1138 else
1139 assignSlots(cast<VPBasicBlock>(VPBB));
1140 }
1141
assignSlots(const VPRegionBlock * Region)1142 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
1143 ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
1144 for (const VPBlockBase *Block : RPOT)
1145 assignSlots(Block);
1146 }
1147
assignSlots(const VPBasicBlock * VPBB)1148 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1149 for (const VPRecipeBase &Recipe : *VPBB) {
1150 if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
1151 assignSlot(VPI);
1152 else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
1153 assignSlot(VPIV->getVPValue());
1154 }
1155 }
1156
assignSlots(const VPlan & Plan)1157 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1158
1159 for (const VPValue *V : Plan.VPExternalDefs)
1160 assignSlot(V);
1161
1162 for (auto &E : Plan.Value2VPValue)
1163 if (!isa<VPInstruction>(E.second))
1164 assignSlot(E.second);
1165
1166 for (const VPValue *V : Plan.VPCBVs)
1167 assignSlot(V);
1168
1169 if (Plan.BackedgeTakenCount)
1170 assignSlot(Plan.BackedgeTakenCount);
1171
1172 ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
1173 for (const VPBlockBase *Block : RPOT)
1174 assignSlots(Block);
1175 }
1176