blob: b15c5d0f7dad1062fbb0465cd2a6e784f31c8bdb [file] [log] [blame]
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001//===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Ayal Zaks1f58dda2017-08-27 12:55:46 +00006//
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"
Diego Caballero2a34ac82018-07-30 21:33:31 +000020#include "VPlanDominatorTree.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000021#include "llvm/ADT/DepthFirstIterator.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000022#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000025#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/IR/BasicBlock.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000027#include "llvm/IR/CFG.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000028#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Type.h"
32#include "llvm/IR/Value.h"
33#include "llvm/Support/Casting.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080034#include "llvm/Support/CommandLine.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
Diego Caballero2a34ac82018-07-30 21:33:31 +000037#include "llvm/Support/GenericDomTreeConstruction.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000038#include "llvm/Support/GraphWriter.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000039#include "llvm/Support/raw_ostream.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000041#include <cassert>
42#include <iterator>
43#include <string>
44#include <vector>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000045
46using namespace llvm;
Hideki Saitoea7f3032018-09-14 00:36:00 +000047extern cl::opt<bool> EnableVPlanNativePath;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000048
49#define DEBUG_TYPE "vplan"
50
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000051raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
52 if (const VPInstruction *Instr = dyn_cast<VPInstruction>(&V))
53 Instr->print(OS);
54 else
55 V.printAsOperand(OS);
56 return OS;
57}
58
Ayal Zaks1f58dda2017-08-27 12:55:46 +000059/// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
60const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
61 const VPBlockBase *Block = this;
62 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
63 Block = Region->getEntry();
64 return cast<VPBasicBlock>(Block);
65}
66
67VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
68 VPBlockBase *Block = this;
69 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
70 Block = Region->getEntry();
71 return cast<VPBasicBlock>(Block);
72}
73
74/// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
75const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
76 const VPBlockBase *Block = this;
77 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
78 Block = Region->getExit();
79 return cast<VPBasicBlock>(Block);
80}
81
82VPBasicBlock *VPBlockBase::getExitBasicBlock() {
83 VPBlockBase *Block = this;
84 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
85 Block = Region->getExit();
86 return cast<VPBasicBlock>(Block);
87}
88
89VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
90 if (!Successors.empty() || !Parent)
91 return this;
92 assert(Parent->getExit() == this &&
93 "Block w/o successors not the exit of its parent.");
94 return Parent->getEnclosingBlockWithSuccessors();
95}
96
97VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
98 if (!Predecessors.empty() || !Parent)
99 return this;
100 assert(Parent->getEntry() == this &&
101 "Block w/o predecessors not the entry of its parent.");
102 return Parent->getEnclosingBlockWithPredecessors();
103}
104
105void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
106 SmallVector<VPBlockBase *, 8> Blocks;
107 for (VPBlockBase *Block : depth_first(Entry))
108 Blocks.push_back(Block);
109
110 for (VPBlockBase *Block : Blocks)
111 delete Block;
112}
113
114BasicBlock *
115VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
116 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
117 // Pred stands for Predessor. Prev stands for Previous - last visited/created.
118 BasicBlock *PrevBB = CFG.PrevBB;
119 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
120 PrevBB->getParent(), CFG.LastBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000121 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000122
123 // Hook up the new basic block to its predecessors.
124 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
125 VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
126 auto &PredVPSuccessors = PredVPBB->getSuccessors();
127 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
Hideki Saitoea7f3032018-09-14 00:36:00 +0000128
129 // In outer loop vectorization scenario, the predecessor BBlock may not yet
130 // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
131 // vectorization. We do not encounter this case in inner loop vectorization
132 // as we start out by building a loop skeleton with the vector loop header
133 // and latch blocks. As a result, we never enter this function for the
134 // header block in the non VPlan-native path.
135 if (!PredBB) {
136 assert(EnableVPlanNativePath &&
137 "Unexpected null predecessor in non VPlan-native path");
138 CFG.VPBBsToFix.push_back(PredVPBB);
139 continue;
140 }
141
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000142 assert(PredBB && "Predecessor basic-block not found building successor.");
143 auto *PredBBTerminator = PredBB->getTerminator();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000144 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000145 if (isa<UnreachableInst>(PredBBTerminator)) {
146 assert(PredVPSuccessors.size() == 1 &&
147 "Predecessor ending w/o branch must have single successor.");
148 PredBBTerminator->eraseFromParent();
149 BranchInst::Create(NewBB, PredBB);
150 } else {
151 assert(PredVPSuccessors.size() == 2 &&
152 "Predecessor ending with branch must have two successors.");
153 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
154 assert(!PredBBTerminator->getSuccessor(idx) &&
155 "Trying to reset an existing successor block.");
156 PredBBTerminator->setSuccessor(idx, NewBB);
157 }
158 }
159 return NewBB;
160}
161
162void VPBasicBlock::execute(VPTransformState *State) {
163 bool Replica = State->Instance &&
164 !(State->Instance->Part == 0 && State->Instance->Lane == 0);
165 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
166 VPBlockBase *SingleHPred = nullptr;
167 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
168
169 // 1. Create an IR basic block, or reuse the last one if possible.
170 // The last IR basic block is reused, as an optimization, in three cases:
171 // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
172 // B. when the current VPBB has a single (hierarchical) predecessor which
173 // is PrevVPBB and the latter has a single (hierarchical) successor; and
174 // C. when the current VPBB is an entry of a region replica - where PrevVPBB
175 // is the exit of this region from a previous instance, or the predecessor
176 // of this region.
177 if (PrevVPBB && /* A */
178 !((SingleHPred = getSingleHierarchicalPredecessor()) &&
179 SingleHPred->getExitBasicBlock() == PrevVPBB &&
180 PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
181 !(Replica && getPredecessors().empty())) { /* C */
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000182 NewBB = createEmptyBasicBlock(State->CFG);
183 State->Builder.SetInsertPoint(NewBB);
184 // Temporarily terminate with unreachable until CFG is rewired.
185 UnreachableInst *Terminator = State->Builder.CreateUnreachable();
186 State->Builder.SetInsertPoint(Terminator);
187 // Register NewBB in its loop. In innermost loops its the same for all BB's.
188 Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
189 L->addBasicBlockToLoop(NewBB, *State->LI);
190 State->CFG.PrevBB = NewBB;
191 }
192
193 // 2. Fill the IR basic block with IR instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000194 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
195 << " in BB:" << NewBB->getName() << '\n');
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000196
197 State->CFG.VPBB2IRBB[this] = NewBB;
198 State->CFG.PrevVPBB = this;
199
200 for (VPRecipeBase &Recipe : Recipes)
201 Recipe.execute(*State);
202
Hideki Saitoea7f3032018-09-14 00:36:00 +0000203 VPValue *CBV;
204 if (EnableVPlanNativePath && (CBV = getCondBit())) {
205 Value *IRCBV = CBV->getUnderlyingValue();
206 assert(IRCBV && "Unexpected null underlying value for condition bit");
207
Hideki Saitoea7f3032018-09-14 00:36:00 +0000208 // Condition bit value in a VPBasicBlock is used as the branch selector. In
209 // the VPlan-native path case, since all branches are uniform we generate a
210 // branch instruction using the condition value from vector lane 0 and dummy
211 // successors. The successors are fixed later when the successor blocks are
212 // visited.
213 Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
214 NewCond = State->Builder.CreateExtractElement(NewCond,
215 State->Builder.getInt32(0));
216
217 // Replace the temporary unreachable terminator with the new conditional
218 // branch.
219 auto *CurrentTerminator = NewBB->getTerminator();
220 assert(isa<UnreachableInst>(CurrentTerminator) &&
221 "Expected to replace unreachable terminator with conditional "
222 "branch.");
223 auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
224 CondBr->setSuccessor(0, nullptr);
225 ReplaceInstWithInst(CurrentTerminator, CondBr);
226 }
227
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000228 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000229}
230
231void VPRegionBlock::execute(VPTransformState *State) {
232 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
233
234 if (!isReplicator()) {
235 // Visit the VPBlocks connected to "this", starting from it.
236 for (VPBlockBase *Block : RPOT) {
Hideki Saitoea7f3032018-09-14 00:36:00 +0000237 if (EnableVPlanNativePath) {
238 // The inner loop vectorization path does not represent loop preheader
239 // and exit blocks as part of the VPlan. In the VPlan-native path, skip
240 // vectorizing loop preheader block. In future, we may replace this
241 // check with the check for loop preheader.
242 if (Block->getNumPredecessors() == 0)
243 continue;
244
245 // Skip vectorizing loop exit block. In future, we may replace this
246 // check with the check for loop exit.
247 if (Block->getNumSuccessors() == 0)
248 continue;
249 }
250
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000251 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000252 Block->execute(State);
253 }
254 return;
255 }
256
257 assert(!State->Instance && "Replicating a Region with non-null instance.");
258
259 // Enter replicating mode.
260 State->Instance = {0, 0};
261
262 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
263 State->Instance->Part = Part;
264 for (unsigned Lane = 0, VF = State->VF; Lane < VF; ++Lane) {
265 State->Instance->Lane = Lane;
266 // Visit the VPBlocks connected to \p this, starting from it.
267 for (VPBlockBase *Block : RPOT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000268 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000269 Block->execute(State);
270 }
271 }
272 }
273
274 // Exit replicating mode.
275 State->Instance.reset();
276}
277
Florian Hahn7591e4e2018-06-18 11:34:17 +0000278void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
Gil Rapaport7f152542019-10-07 17:24:33 +0300279 assert(!Parent && "Recipe already in some VPBasicBlock");
280 assert(InsertPos->getParent() &&
281 "Insertion position not in any VPBasicBlock");
Florian Hahn3bcff362018-06-18 13:51:28 +0000282 Parent = InsertPos->getParent();
283 Parent->getRecipeList().insert(InsertPos->getIterator(), this);
Florian Hahn7591e4e2018-06-18 11:34:17 +0000284}
285
Gil Rapaport7f152542019-10-07 17:24:33 +0300286void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
287 assert(!Parent && "Recipe already in some VPBasicBlock");
288 assert(InsertPos->getParent() &&
289 "Insertion position not in any VPBasicBlock");
290 Parent = InsertPos->getParent();
291 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
292}
293
294void VPRecipeBase::removeFromParent() {
295 assert(getParent() && "Recipe not in any VPBasicBlock");
296 getParent()->getRecipeList().remove(getIterator());
297 Parent = nullptr;
298}
299
Florian Hahn63cbcf92018-06-18 15:18:48 +0000300iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
Gil Rapaport7f152542019-10-07 17:24:33 +0300301 assert(getParent() && "Recipe not in any VPBasicBlock");
Florian Hahn63cbcf92018-06-18 15:18:48 +0000302 return getParent()->getRecipeList().erase(getIterator());
303}
304
Florian Hahn39d4c9f2019-10-11 15:36:55 +0000305void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
Gil Rapaport7f152542019-10-07 17:24:33 +0300306 removeFromParent();
307 insertAfter(InsertPos);
Florian Hahn39d4c9f2019-10-11 15:36:55 +0000308}
309
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000310void VPInstruction::generateInstruction(VPTransformState &State,
311 unsigned Part) {
312 IRBuilder<> &Builder = State.Builder;
313
314 if (Instruction::isBinaryOp(getOpcode())) {
315 Value *A = State.get(getOperand(0), Part);
316 Value *B = State.get(getOperand(1), Part);
317 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
318 State.set(this, V, Part);
319 return;
320 }
321
322 switch (getOpcode()) {
323 case VPInstruction::Not: {
324 Value *A = State.get(getOperand(0), Part);
325 Value *V = Builder.CreateNot(A);
326 State.set(this, V, Part);
327 break;
328 }
Ayal Zaksb0b53122018-10-18 15:03:15 +0000329 case VPInstruction::ICmpULE: {
330 Value *IV = State.get(getOperand(0), Part);
331 Value *TC = State.get(getOperand(1), Part);
332 Value *V = Builder.CreateICmpULE(IV, TC);
333 State.set(this, V, Part);
334 break;
335 }
Ayal Zaksd15df0e2019-08-28 09:02:23 +0000336 case Instruction::Select: {
337 Value *Cond = State.get(getOperand(0), Part);
338 Value *Op1 = State.get(getOperand(1), Part);
339 Value *Op2 = State.get(getOperand(2), Part);
340 Value *V = Builder.CreateSelect(Cond, Op1, Op2);
341 State.set(this, V, Part);
342 break;
343 }
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000344 default:
345 llvm_unreachable("Unsupported opcode for instruction");
346 }
347}
348
349void VPInstruction::execute(VPTransformState &State) {
350 assert(!State.Instance && "VPInstruction executing an Instance");
351 for (unsigned Part = 0; Part < State.UF; ++Part)
352 generateInstruction(State, Part);
353}
354
355void VPInstruction::print(raw_ostream &O, const Twine &Indent) const {
356 O << " +\n" << Indent << "\"EMIT ";
357 print(O);
358 O << "\\l\"";
359}
360
361void VPInstruction::print(raw_ostream &O) const {
362 printAsOperand(O);
363 O << " = ";
364
365 switch (getOpcode()) {
366 case VPInstruction::Not:
367 O << "not";
368 break;
Ayal Zaksb0b53122018-10-18 15:03:15 +0000369 case VPInstruction::ICmpULE:
370 O << "icmp ule";
371 break;
Florian Hahn09e516c2018-11-14 13:11:49 +0000372 case VPInstruction::SLPLoad:
373 O << "combined load";
374 break;
375 case VPInstruction::SLPStore:
376 O << "combined store";
377 break;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000378 default:
379 O << Instruction::getOpcodeName(getOpcode());
380 }
381
382 for (const VPValue *Operand : operands()) {
383 O << " ";
384 Operand->printAsOperand(O);
385 }
386}
387
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000388/// Generate the code inside the body of the vectorized loop. Assumes a single
389/// LoopVectorBody basic-block was created for this. Introduce additional
390/// basic-blocks as needed, and fill them all.
391void VPlan::execute(VPTransformState *State) {
Ayal Zaksb0b53122018-10-18 15:03:15 +0000392 // -1. Check if the backedge taken count is needed, and if so build it.
393 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
394 Value *TC = State->TripCount;
395 IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
396 auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
397 "trip.count.minus.1");
398 Value2VPValue[TCMO] = BackedgeTakenCount;
399 }
400
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000401 // 0. Set the reverse mapping from VPValues to Values for code generation.
402 for (auto &Entry : Value2VPValue)
403 State->VPValue2Value[Entry.second] = Entry.first;
404
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000405 BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
406 BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
407 assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000408
409 // 1. Make room to generate basic-blocks inside loop body if needed.
Simon Pilgrimcced3ec2019-05-08 10:52:26 +0000410 BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000411 VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
412 Loop *L = State->LI->getLoopFor(VectorHeaderBB);
413 L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
414 // Remove the edge between Header and Latch to allow other connections.
415 // Temporarily terminate with unreachable until CFG is rewired.
416 // Note: this asserts the generated code's assumption that
417 // getFirstInsertionPt() can be dereferenced into an Instruction.
418 VectorHeaderBB->getTerminator()->eraseFromParent();
419 State->Builder.SetInsertPoint(VectorHeaderBB);
420 UnreachableInst *Terminator = State->Builder.CreateUnreachable();
421 State->Builder.SetInsertPoint(Terminator);
422
423 // 2. Generate code in loop body.
424 State->CFG.PrevVPBB = nullptr;
425 State->CFG.PrevBB = VectorHeaderBB;
426 State->CFG.LastBB = VectorLatchBB;
427
428 for (VPBlockBase *Block : depth_first(Entry))
429 Block->execute(State);
430
Hideki Saitoea7f3032018-09-14 00:36:00 +0000431 // Setup branch terminator successors for VPBBs in VPBBsToFix based on
432 // VPBB's successors.
433 for (auto VPBB : State->CFG.VPBBsToFix) {
434 assert(EnableVPlanNativePath &&
435 "Unexpected VPBBsToFix in non VPlan-native path");
436 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
437 assert(BB && "Unexpected null basic block for VPBB");
438
439 unsigned Idx = 0;
440 auto *BBTerminator = BB->getTerminator();
441
442 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
443 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
444 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
445 ++Idx;
446 }
447 }
448
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000449 // 3. Merge the temporary latch created with the last basic-block filled.
450 BasicBlock *LastBB = State->CFG.PrevBB;
451 // Connect LastBB to VectorLatchBB to facilitate their merge.
Hideki Saitoea7f3032018-09-14 00:36:00 +0000452 assert((EnableVPlanNativePath ||
453 isa<UnreachableInst>(LastBB->getTerminator())) &&
454 "Expected InnerLoop VPlan CFG to terminate with unreachable");
455 assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
456 "Expected VPlan CFG to terminate with branch in NativePath");
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000457 LastBB->getTerminator()->eraseFromParent();
458 BranchInst::Create(VectorLatchBB, LastBB);
459
460 // Merge LastBB with Latch.
461 bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
462 (void)Merged;
463 assert(Merged && "Could not merge last basic block with latch.");
464 VectorLatchBB = LastBB;
465
Hideki Saitoea7f3032018-09-14 00:36:00 +0000466 // We do not attempt to preserve DT for outer loop vectorization currently.
467 if (!EnableVPlanNativePath)
468 updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000469}
470
Florian Hahne9c68422019-12-03 11:58:31 +0000471#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
472LLVM_DUMP_METHOD
473void VPlan::dump() const { dbgs() << *this << '\n'; }
474#endif
475
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000476void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
477 BasicBlock *LoopLatchBB) {
478 BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
479 assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
480 DT->addNewBlock(LoopHeaderBB, LoopPreHeaderBB);
481 // The vector body may be more than a single basic-block by this point.
482 // Update the dominator tree information inside the vector body by propagating
483 // it from header to latch, expecting only triangular control-flow, if any.
484 BasicBlock *PostDomSucc = nullptr;
485 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
486 // Get the list of successors of this block.
487 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
488 assert(Succs.size() <= 2 &&
489 "Basic block in vector loop has more than 2 successors.");
490 PostDomSucc = Succs[0];
491 if (Succs.size() == 1) {
492 assert(PostDomSucc->getSinglePredecessor() &&
493 "PostDom successor has more than one predecessor.");
494 DT->addNewBlock(PostDomSucc, BB);
495 continue;
496 }
497 BasicBlock *InterimSucc = Succs[1];
498 if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
499 PostDomSucc = Succs[1];
500 InterimSucc = Succs[0];
501 }
502 assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
503 "One successor of a basic block does not lead to the other.");
504 assert(InterimSucc->getSinglePredecessor() &&
505 "Interim successor has more than one predecessor.");
Vedant Kumar4de31bb2018-11-19 19:54:27 +0000506 assert(PostDomSucc->hasNPredecessors(2) &&
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000507 "PostDom successor has more than two predecessors.");
508 DT->addNewBlock(InterimSucc, BB);
509 DT->addNewBlock(PostDomSucc, BB);
510 }
511}
512
513const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
514 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
515 Twine(getOrCreateBID(Block));
516}
517
518const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
519 const std::string &Name = Block->getName();
520 if (!Name.empty())
521 return Name;
522 return "VPB" + Twine(getOrCreateBID(Block));
523}
524
525void VPlanPrinter::dump() {
526 Depth = 1;
527 bumpIndent(0);
528 OS << "digraph VPlan {\n";
529 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
530 if (!Plan.getName().empty())
531 OS << "\\n" << DOT::EscapeString(Plan.getName());
Ayal Zaksb0b53122018-10-18 15:03:15 +0000532 if (!Plan.Value2VPValue.empty() || Plan.BackedgeTakenCount) {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000533 OS << ", where:";
Ayal Zaksb0b53122018-10-18 15:03:15 +0000534 if (Plan.BackedgeTakenCount)
Florian Hahne9c68422019-12-03 11:58:31 +0000535 OS << "\\n" << *Plan.BackedgeTakenCount << " := BackedgeTakenCount";
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000536 for (auto Entry : Plan.Value2VPValue) {
537 OS << "\\n" << *Entry.second;
538 OS << DOT::EscapeString(" := ");
539 Entry.first->printAsOperand(OS, false);
540 }
541 }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000542 OS << "\"]\n";
543 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
544 OS << "edge [fontname=Courier, fontsize=30]\n";
545 OS << "compound=true\n";
546
Florian Hahne9c68422019-12-03 11:58:31 +0000547 for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000548 dumpBlock(Block);
549
550 OS << "}\n";
551}
552
553void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
554 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
555 dumpBasicBlock(BasicBlock);
556 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
557 dumpRegion(Region);
558 else
559 llvm_unreachable("Unsupported kind of VPBlock.");
560}
561
562void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
563 bool Hidden, const Twine &Label) {
564 // Due to "dot" we print an edge between two regions as an edge between the
565 // exit basic block and the entry basic of the respective regions.
566 const VPBlockBase *Tail = From->getExitBasicBlock();
567 const VPBlockBase *Head = To->getEntryBasicBlock();
568 OS << Indent << getUID(Tail) << " -> " << getUID(Head);
569 OS << " [ label=\"" << Label << '\"';
570 if (Tail != From)
571 OS << " ltail=" << getUID(From);
572 if (Head != To)
573 OS << " lhead=" << getUID(To);
574 if (Hidden)
575 OS << "; splines=none";
576 OS << "]\n";
577}
578
579void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
580 auto &Successors = Block->getSuccessors();
581 if (Successors.size() == 1)
582 drawEdge(Block, Successors.front(), false, "");
583 else if (Successors.size() == 2) {
584 drawEdge(Block, Successors.front(), false, "T");
585 drawEdge(Block, Successors.back(), false, "F");
586 } else {
587 unsigned SuccessorNumber = 0;
588 for (auto *Successor : Successors)
589 drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
590 }
591}
592
593void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
594 OS << Indent << getUID(BasicBlock) << " [label =\n";
595 bumpIndent(1);
596 OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
597 bumpIndent(1);
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000598
599 // Dump the block predicate.
600 const VPValue *Pred = BasicBlock->getPredicate();
601 if (Pred) {
602 OS << " +\n" << Indent << " \"BlockPredicate: ";
603 if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
604 PredI->printAsOperand(OS);
605 OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
606 << ")\\l\"";
607 } else
608 Pred->printAsOperand(OS);
609 }
610
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000611 for (const VPRecipeBase &Recipe : *BasicBlock)
612 Recipe.print(OS, Indent);
Diego Caballerod0953012018-07-09 15:57:09 +0000613
614 // Dump the condition bit.
615 const VPValue *CBV = BasicBlock->getCondBit();
616 if (CBV) {
617 OS << " +\n" << Indent << " \"CondBit: ";
618 if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
619 CBI->printAsOperand(OS);
620 OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
Renato Golind8e7ca42018-10-10 17:55:21 +0000621 } else {
Diego Caballerod0953012018-07-09 15:57:09 +0000622 CBV->printAsOperand(OS);
Renato Golind8e7ca42018-10-10 17:55:21 +0000623 OS << "\"";
624 }
Diego Caballerod0953012018-07-09 15:57:09 +0000625 }
626
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000627 bumpIndent(-2);
628 OS << "\n" << Indent << "]\n";
629 dumpEdges(BasicBlock);
630}
631
632void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
633 OS << Indent << "subgraph " << getUID(Region) << " {\n";
634 bumpIndent(1);
635 OS << Indent << "fontname=Courier\n"
636 << Indent << "label=\""
637 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
638 << DOT::EscapeString(Region->getName()) << "\"\n";
639 // Dump the blocks of the region.
640 assert(Region->getEntry() && "Region contains no inner blocks.");
641 for (const VPBlockBase *Block : depth_first(Region->getEntry()))
642 dumpBlock(Block);
643 bumpIndent(-1);
644 OS << Indent << "}\n";
645 dumpEdges(Region);
646}
647
648void VPlanPrinter::printAsIngredient(raw_ostream &O, Value *V) {
649 std::string IngredientString;
650 raw_string_ostream RSO(IngredientString);
651 if (auto *Inst = dyn_cast<Instruction>(V)) {
652 if (!Inst->getType()->isVoidTy()) {
653 Inst->printAsOperand(RSO, false);
654 RSO << " = ";
655 }
656 RSO << Inst->getOpcodeName() << " ";
657 unsigned E = Inst->getNumOperands();
658 if (E > 0) {
659 Inst->getOperand(0)->printAsOperand(RSO, false);
660 for (unsigned I = 1; I < E; ++I)
661 Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
662 }
663 } else // !Inst
664 V->printAsOperand(RSO, false);
665 RSO.flush();
666 O << DOT::EscapeString(IngredientString);
667}
Hal Finkel7333aa92017-12-16 01:12:50 +0000668
669void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent) const {
670 O << " +\n" << Indent << "\"WIDEN\\l\"";
671 for (auto &Instr : make_range(Begin, End))
672 O << " +\n" << Indent << "\" " << VPlanIngredient(&Instr) << "\\l\"";
673}
674
675void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O,
676 const Twine &Indent) const {
677 O << " +\n" << Indent << "\"WIDEN-INDUCTION";
678 if (Trunc) {
679 O << "\\l\"";
680 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\"";
681 O << " +\n" << Indent << "\" " << VPlanIngredient(Trunc) << "\\l\"";
682 } else
683 O << " " << VPlanIngredient(IV) << "\\l\"";
684}
685
686void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent) const {
687 O << " +\n" << Indent << "\"WIDEN-PHI " << VPlanIngredient(Phi) << "\\l\"";
688}
689
690void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent) const {
691 O << " +\n" << Indent << "\"BLEND ";
692 Phi->printAsOperand(O, false);
693 O << " =";
694 if (!User) {
695 // Not a User of any mask: not really blending, this is a
696 // single-predecessor phi.
697 O << " ";
698 Phi->getIncomingValue(0)->printAsOperand(O, false);
699 } else {
700 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
701 O << " ";
702 Phi->getIncomingValue(I)->printAsOperand(O, false);
703 O << "/";
704 User->getOperand(I)->printAsOperand(O);
705 }
706 }
707 O << "\\l\"";
708}
709
710void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent) const {
711 O << " +\n"
712 << Indent << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
713 << VPlanIngredient(Ingredient);
714 if (AlsoPack)
715 O << " (S->V)";
716 O << "\\l\"";
717}
718
719void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent) const {
720 O << " +\n"
721 << Indent << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst)
722 << "\\l\"";
723}
724
725void VPWidenMemoryInstructionRecipe::print(raw_ostream &O,
726 const Twine &Indent) const {
727 O << " +\n" << Indent << "\"WIDEN " << VPlanIngredient(&Instr);
728 if (User) {
729 O << ", ";
730 User->getOperand(0)->printAsOperand(O);
731 }
732 O << "\\l\"";
733}
Diego Caballero2a34ac82018-07-30 21:33:31 +0000734
735template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000736
Florian Hahn09e516c2018-11-14 13:11:49 +0000737void VPValue::replaceAllUsesWith(VPValue *New) {
738 for (VPUser *User : users())
739 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
740 if (User->getOperand(I) == this)
741 User->setOperand(I, New);
742}
743
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000744void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
745 Old2NewTy &Old2New,
746 InterleavedAccessInfo &IAI) {
747 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
748 for (VPBlockBase *Base : RPOT) {
749 visitBlock(Base, Old2New, IAI);
750 }
751}
752
753void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
754 InterleavedAccessInfo &IAI) {
755 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
756 for (VPRecipeBase &VPI : *VPBB) {
757 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
758 auto *VPInst = cast<VPInstruction>(&VPI);
759 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
760 auto *IG = IAI.getInterleaveGroup(Inst);
761 if (!IG)
762 continue;
763
764 auto NewIGIter = Old2New.find(IG);
765 if (NewIGIter == Old2New.end())
766 Old2New[IG] = new InterleaveGroup<VPInstruction>(
Guillaume Chatelet837a1b82019-10-10 12:35:04 +0000767 IG->getFactor(), IG->isReverse(), Align(IG->getAlignment()));
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000768
769 if (Inst == IG->getInsertPos())
770 Old2New[IG]->setInsertPos(VPInst);
771
772 InterleaveGroupMap[VPInst] = Old2New[IG];
773 InterleaveGroupMap[VPInst]->insertMember(
774 VPInst, IG->getIndex(Inst),
Guillaume Chatelet837a1b82019-10-10 12:35:04 +0000775 Align(IG->isReverse() ? (-1) * int(IG->getFactor())
776 : IG->getFactor()));
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000777 }
778 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
779 visitRegion(Region, Old2New, IAI);
780 else
781 llvm_unreachable("Unsupported kind of VPBlock.");
782}
783
784VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
785 InterleavedAccessInfo &IAI) {
786 Old2NewTy Old2New;
787 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
788}