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