1 //===- HexagonVectorLoopCarriedReuse.cpp ----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // This pass removes the computation of provably redundant expressions that have
10 // been computed earlier in a previous iteration. It relies on the use of PHIs
11 // to identify loop carried dependences. This is scalar replacement for vector
12 // types.
13 //
14 //-----------------------------------------------------------------------------
15 // Motivation: Consider the case where we have the following loop structure.
16 //
17 // Loop:
18 //  t0 = a[i];
19 //  t1 = f(t0);
20 //  t2 = g(t1);
21 //  ...
22 //  t3 = a[i+1];
23 //  t4 = f(t3);
24 //  t5 = g(t4);
25 //  t6 = op(t2, t5)
26 //  cond_branch <Loop>
27 //
28 // This can be converted to
29 //  t00 = a[0];
30 //  t10 = f(t00);
31 //  t20 = g(t10);
32 // Loop:
33 //  t2 = t20;
34 //  t3 = a[i+1];
35 //  t4 = f(t3);
36 //  t5 = g(t4);
37 //  t6 = op(t2, t5)
38 //  t20 = t5
39 //  cond_branch <Loop>
40 //
41 // SROA does a good job of reusing a[i+1] as a[i] in the next iteration.
42 // Such a loop comes to this pass in the following form.
43 //
44 // LoopPreheader:
45 //  X0 = a[0];
46 // Loop:
47 //  X2 = PHI<(X0, LoopPreheader), (X1, Loop)>
48 //  t1 = f(X2)   <-- I1
49 //  t2 = g(t1)
50 //  ...
51 //  X1 = a[i+1]
52 //  t4 = f(X1)   <-- I2
53 //  t5 = g(t4)
54 //  t6 = op(t2, t5)
55 //  cond_branch <Loop>
56 //
57 // In this pass, we look for PHIs such as X2 whose incoming values come only
58 // from the Loop Preheader and over the backedge and additionaly, both these
59 // values are the results of the same operation in terms of opcode. We call such
60 // a PHI node a dependence chain or DepChain. In this case, the dependence of X2
61 // over X1 is carried over only one iteration and so the DepChain is only one
62 // PHI node long.
63 //
64 // Then, we traverse the uses of the PHI (X2) and the uses of the value of the
65 // PHI coming  over the backedge (X1). We stop at the first pair of such users
66 // I1 (of X2) and I2 (of X1) that meet the following conditions.
67 // 1. I1 and I2 are the same operation, but with different operands.
68 // 2. X2 and X1 are used at the same operand number in the two instructions.
69 // 3. All other operands Op1 of I1 and Op2 of I2 are also such that there is a
70 //    a DepChain from Op1 to Op2 of the same length as that between X2 and X1.
71 //
72 // We then make the following transformation
73 // LoopPreheader:
74 //  X0 = a[0];
75 //  Y0 = f(X0);
76 // Loop:
77 //  X2 = PHI<(X0, LoopPreheader), (X1, Loop)>
78 //  Y2 = PHI<(Y0, LoopPreheader), (t4, Loop)>
79 //  t1 = f(X2)   <-- Will be removed by DCE.
80 //  t2 = g(Y2)
81 //  ...
82 //  X1 = a[i+1]
83 //  t4 = f(X1)
84 //  t5 = g(t4)
85 //  t6 = op(t2, t5)
86 //  cond_branch <Loop>
87 //
88 // We proceed until we cannot find any more such instructions I1 and I2.
89 //
90 // --- DepChains & Loop carried dependences ---
91 // Consider a single basic block loop such as
92 //
93 // LoopPreheader:
94 //  X0 = ...
95 //  Y0 = ...
96 // Loop:
97 //  X2 = PHI<(X0, LoopPreheader), (X1, Loop)>
98 //  Y2 = PHI<(Y0, LoopPreheader), (X2, Loop)>
99 //  ...
100 //  X1 = ...
101 //  ...
102 //  cond_branch <Loop>
103 //
104 // Then there is a dependence between X2 and X1 that goes back one iteration,
105 // i.e. X1 is used as X2 in the very next iteration. We represent this as a
106 // DepChain from X2 to X1 (X2->X1).
107 // Similarly, there is a dependence between Y2 and X1 that goes back two
108 // iterations. X1 is used as Y2 two iterations after it is computed. This is
109 // represented by a DepChain as (Y2->X2->X1).
110 //
111 // A DepChain has the following properties.
112 // 1. Num of edges in DepChain = Number of Instructions in DepChain = Number of
113 //    iterations of carried dependence + 1.
114 // 2. All instructions in the DepChain except the last are PHIs.
115 //===----------------------------------------------------------------------===//
116 
117 #define DEBUG_TYPE "hexagon-vlcr"
118 
119 #include "llvm/ADT/SetVector.h"
120 #include "llvm/ADT/Triple.h"
121 #include "llvm/Analysis/LoopPass.h"
122 #include "llvm/Transforms/Scalar.h"
123 #include "llvm/IR/IRBuilder.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include "llvm/IR/Instructions.h"
126 #include "llvm/IR/IntrinsicInst.h"
127 #include "llvm/ADT/Statistic.h"
128 #include <set>
129 #include <map>
130 using namespace llvm;
131 
132 STATISTIC(HexagonNumVectorLoopCarriedReuse,
133           "Number of values that were reused from a previous iteration.");
134 
135 static cl::opt<int> HexagonVLCRIterationLim("hexagon-vlcr-iteration-lim",
136     cl::Hidden,
137     cl::desc("Maximum distance of loop carried dependences that are handled"),
138     cl::init(2), cl::ZeroOrMore);
139 namespace llvm {
140   void initializeHexagonVectorLoopCarriedReusePass(PassRegistry&);
141   Pass *createHexagonVectorLoopCarriedReusePass();
142 }
143 namespace {
144   // See info about DepChain in the comments at the top of this file.
145   typedef SmallVector<Instruction *, 4> ChainOfDependences;
146   class DepChain {
147     ChainOfDependences Chain;
148   public:
149     bool isIdentical(DepChain &Other) {
150       if (Other.size() != size())
151         return false;
152       ChainOfDependences &OtherChain = Other.getChain();
153       for (int i = 0; i < size(); ++i) {
154         if (Chain[i] != OtherChain[i])
155           return false;
156       }
157       return true;
158     }
159     ChainOfDependences &getChain() {
160       return Chain;
161     }
162     int size() {
163       return Chain.size();
164     }
165     void clear() {
166       Chain.clear();
167     }
168     void push_back(Instruction *I) {
169       Chain.push_back(I);
170     }
171     int iterations() {
172       return size() - 1;
173     }
174     Instruction *front() {
175       return Chain.front();
176     }
177     Instruction *back() {
178       return Chain.back();
179     }
180     Instruction *&operator[](const int index) {
181       return Chain[index];
182     }
183    friend raw_ostream &operator<< (raw_ostream &OS, const DepChain &D);
184   };
185 
186   LLVM_ATTRIBUTE_UNUSED
187   raw_ostream &operator<<(raw_ostream &OS, const DepChain &D) {
188     const ChainOfDependences &CD = D.Chain;
189     int ChainSize = CD.size();
190     OS << "**DepChain Start::**\n";
191     for (int i = 0; i < ChainSize -1; ++i) {
192       OS << *(CD[i]) << " -->\n";
193     }
194     OS << *CD[ChainSize-1] << "\n";
195     return OS;
196   }
197 }
198 namespace {
199   struct ReuseValue {
200     Instruction *Inst2Replace;
201     // In the new PHI node that we'll construct this is the value that'll be
202     // used over the backedge. This is teh value that gets reused from a
203     // previous iteration.
204     Instruction * BackedgeInst;
205     ReuseValue() : Inst2Replace(nullptr), BackedgeInst(nullptr) {};
206     void reset() { Inst2Replace = nullptr; BackedgeInst = nullptr; }
207     bool isDefined() { return Inst2Replace != nullptr; }
208   };
209   typedef struct ReuseValue ReuseValue;
210   LLVM_ATTRIBUTE_UNUSED
211   raw_ostream &operator<<(raw_ostream &OS, const ReuseValue &RU) {
212     OS << "** ReuseValue ***\n";
213     OS << "Instruction to Replace: " << *(RU.Inst2Replace) << "\n";
214     OS << "Backedge Instruction: " << *(RU.BackedgeInst) << "\n";
215     return OS;
216   }
217 }
218 
219 namespace {
220   class HexagonVectorLoopCarriedReuse : public LoopPass {
221   public:
222     static char ID;
223     explicit HexagonVectorLoopCarriedReuse() : LoopPass(ID) {
224       PassRegistry *PR = PassRegistry::getPassRegistry();
225       initializeHexagonVectorLoopCarriedReusePass(*PR);
226     }
227     StringRef getPassName() const override {
228       return "Hexagon-specific loop carried reuse for HVX vectors";
229     }
230 
231    void getAnalysisUsage(AnalysisUsage &AU) const override {
232       AU.addRequired<LoopInfoWrapperPass>();
233       AU.addRequiredID(LoopSimplifyID);
234       AU.addRequiredID(LCSSAID);
235       AU.addPreservedID(LCSSAID);
236       AU.setPreservesCFG();
237     }
238 
239     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
240 
241   private:
242     SetVector<DepChain *> Dependences;
243     std::set<Instruction *> ReplacedInsts;
244     Loop *CurLoop;
245     ReuseValue ReuseCandidate;
246 
247     bool doVLCR();
248     void findLoopCarriedDeps();
249     void findValueToReuse();
250     void findDepChainFromPHI(Instruction *I, DepChain &D);
251     void reuseValue();
252     Value *findValueInBlock(Value *Op, BasicBlock *BB);
253     bool isDepChainBtwn(Instruction *I1, Instruction *I2, int Iters);
254     DepChain *getDepChainBtwn(Instruction *I1, Instruction *I2);
255     bool isEquivalentOperation(Instruction *I1, Instruction *I2);
256     bool canReplace(Instruction *I);
257 
258   };
259 }
260 
261 char HexagonVectorLoopCarriedReuse::ID = 0;
262 
263 INITIALIZE_PASS_BEGIN(HexagonVectorLoopCarriedReuse, "hexagon-vlcr",
264     "Hexagon-specific predictive commoning for HVX vectors", false, false)
265 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
266 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
267 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
268 INITIALIZE_PASS_END(HexagonVectorLoopCarriedReuse, "hexagon-vlcr",
269     "Hexagon-specific predictive commoning for HVX vectors", false, false)
270 
271 bool HexagonVectorLoopCarriedReuse::runOnLoop(Loop *L, LPPassManager &LPM) {
272   if (skipLoop(L))
273     return false;
274 
275   if (!L->getLoopPreheader())
276     return false;
277 
278   // Work only on innermost loops.
279   if (L->getSubLoops().size() != 0)
280     return false;
281 
282   // Work only on single basic blocks loops.
283   if (L->getNumBlocks() != 1)
284     return false;
285 
286   CurLoop = L;
287 
288   return doVLCR();
289 }
290 
291 bool HexagonVectorLoopCarriedReuse::isEquivalentOperation(Instruction *I1,
292                                                           Instruction *I2) {
293   if (!I1->isSameOperationAs(I2))
294     return false;
295   // This check is in place specifically for intrinsics. isSameOperationAs will
296   // return two for any two hexagon intrinsics because they are essentially the
297   // same instruciton (CallInst). We need to scratch the surface to see if they
298   // are calls to the same function.
299   if (CallInst *C1 = dyn_cast<CallInst>(I1)) {
300     if (CallInst *C2 = dyn_cast<CallInst>(I2)) {
301       if (C1->getCalledFunction() != C2->getCalledFunction())
302         return false;
303     }
304   }
305 
306   // If both the Instructions are of Vector Type and any of the element
307   // is integer constant, check their values too for equivalence.
308   if (I1->getType()->isVectorTy() && I2->getType()->isVectorTy()) {
309     unsigned NumOperands = I1->getNumOperands();
310     for (unsigned i = 0; i < NumOperands; ++i) {
311       ConstantInt *C1 = dyn_cast<ConstantInt>(I1->getOperand(i));
312       ConstantInt *C2 = dyn_cast<ConstantInt>(I2->getOperand(i));
313       if(!C1) continue;
314       assert(C2);
315       if (C1->getSExtValue() != C2->getSExtValue())
316         return false;
317     }
318   }
319 
320   return true;
321 }
322 
323 bool HexagonVectorLoopCarriedReuse::canReplace(Instruction *I) {
324   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
325   if (II &&
326       (II->getIntrinsicID() == Intrinsic::hexagon_V6_hi ||
327        II->getIntrinsicID() == Intrinsic::hexagon_V6_lo)) {
328     DEBUG(dbgs() << "Not considering for reuse: " << *II << "\n");
329     return false;
330   }
331   return true;
332 }
333 void HexagonVectorLoopCarriedReuse::findValueToReuse() {
334   for (auto *D : Dependences) {
335     DEBUG(dbgs() << "Processing dependence " << *(D->front()) << "\n");
336     if (D->iterations() > HexagonVLCRIterationLim) {
337       DEBUG(dbgs() <<
338             ".. Skipping because number of iterations > than the limit\n");
339       continue;
340     }
341 
342     PHINode *PN = cast<PHINode>(D->front());
343     Instruction *BEInst = D->back();
344     int Iters = D->iterations();
345     BasicBlock *BB = PN->getParent();
346     DEBUG(dbgs() << "Checking if any uses of " << *PN << " can be reused\n");
347 
348     SmallVector<Instruction *, 4> PNUsers;
349     for (auto UI = PN->use_begin(), E = PN->use_end(); UI != E; ++UI) {
350       Use &U = *UI;
351       Instruction *User = cast<Instruction>(U.getUser());
352 
353       if (User->getParent() != BB)
354         continue;
355       if (ReplacedInsts.count(User)) {
356         DEBUG(dbgs() << *User << " has already been replaced. Skipping...\n");
357         continue;
358       }
359       if (isa<PHINode>(User))
360         continue;
361       if (User->mayHaveSideEffects())
362         continue;
363       if (!canReplace(User))
364         continue;
365 
366       PNUsers.push_back(User);
367     }
368     DEBUG(dbgs() << PNUsers.size() << " use(s) of the PHI in the block\n");
369 
370     // For each interesting use I of PN, find an Instruction BEUser that
371     // performs the same operation as I on BEInst and whose other operands,
372     // if any, can also be rematerialized in OtherBB. We stop when we find the
373     // first such Instruction BEUser. This is because once BEUser is
374     // rematerialized in OtherBB, we may find more such "fixup" opportunities
375     // in this block. So, we'll start over again.
376     for (Instruction *I : PNUsers) {
377       for (auto UI = BEInst->use_begin(), E = BEInst->use_end(); UI != E;
378            ++UI) {
379         Use &U = *UI;
380         Instruction *BEUser = cast<Instruction>(U.getUser());
381 
382         if (BEUser->getParent() != BB)
383           continue;
384         if (!isEquivalentOperation(I, BEUser))
385           continue;
386 
387         int NumOperands = I->getNumOperands();
388 
389         for (int OpNo = 0; OpNo < NumOperands; ++OpNo) {
390           Value *Op = I->getOperand(OpNo);
391           Instruction *OpInst = dyn_cast<Instruction>(Op);
392           if (!OpInst)
393             continue;
394 
395           Value *BEOp = BEUser->getOperand(OpNo);
396           Instruction *BEOpInst = dyn_cast<Instruction>(BEOp);
397 
398           if (!isDepChainBtwn(OpInst, BEOpInst, Iters)) {
399             BEUser = nullptr;
400             break;
401           }
402         }
403         if (BEUser) {
404           DEBUG(dbgs() << "Found Value for reuse.\n");
405           ReuseCandidate.Inst2Replace = I;
406           ReuseCandidate.BackedgeInst = BEUser;
407           return;
408         } else
409           ReuseCandidate.reset();
410       }
411     }
412   }
413   ReuseCandidate.reset();
414   return;
415 }
416 Value *HexagonVectorLoopCarriedReuse::findValueInBlock(Value *Op,
417                                                        BasicBlock *BB) {
418   PHINode *PN = dyn_cast<PHINode>(Op);
419   assert(PN);
420   Value *ValueInBlock = PN->getIncomingValueForBlock(BB);
421   return ValueInBlock;
422 }
423 void HexagonVectorLoopCarriedReuse::reuseValue() {
424   DEBUG(dbgs() << ReuseCandidate);
425   Instruction *Inst2Replace = ReuseCandidate.Inst2Replace;
426   Instruction *BEInst = ReuseCandidate.BackedgeInst;
427   int NumOperands = Inst2Replace->getNumOperands();
428   std::map<Instruction *, DepChain *> DepChains;
429   int Iterations = -1;
430   BasicBlock *LoopPH = CurLoop->getLoopPreheader();
431 
432   for (int i = 0; i < NumOperands; ++i) {
433     Instruction *I = dyn_cast<Instruction>(Inst2Replace->getOperand(i));
434     if(!I)
435       continue;
436     else {
437       Instruction *J = cast<Instruction>(BEInst->getOperand(i));
438       DepChain *D = getDepChainBtwn(I, J);
439 
440       assert(D &&
441              "No DepChain between corresponding operands in ReuseCandidate\n");
442       if (Iterations == -1)
443         Iterations = D->iterations();
444       assert(Iterations == D->iterations() && "Iterations mismatch");
445       DepChains[I] = D;
446     }
447   }
448 
449   DEBUG(dbgs() << "reuseValue is making the following changes\n");
450 
451   SmallVector<Instruction *, 4> InstsInPreheader;
452   for (int i = 0; i < Iterations; ++i) {
453     Instruction *InstInPreheader = Inst2Replace->clone();
454     SmallVector<Value *, 4> Ops;
455     for (int j = 0; j < NumOperands; ++j) {
456       Instruction *I = dyn_cast<Instruction>(Inst2Replace->getOperand(j));
457       if (!I)
458         continue;
459       // Get the DepChain corresponding to this operand.
460       DepChain &D = *DepChains[I];
461       // Get the PHI for the iteration number and find
462       // the incoming value from the Loop Preheader for
463       // that PHI.
464       Value *ValInPreheader = findValueInBlock(D[i], LoopPH);
465       InstInPreheader->setOperand(j, ValInPreheader);
466     }
467     InstsInPreheader.push_back(InstInPreheader);
468     InstInPreheader->setName(Inst2Replace->getName() + ".hexagon.vlcr");
469     InstInPreheader->insertBefore(LoopPH->getTerminator());
470     DEBUG(dbgs() << "Added " << *InstInPreheader << " to " << LoopPH->getName()
471           << "\n");
472   }
473   BasicBlock *BB = BEInst->getParent();
474   IRBuilder<> IRB(BB);
475   IRB.SetInsertPoint(BB->getFirstNonPHI());
476   Value *BEVal = BEInst;
477   PHINode *NewPhi;
478   for (int i = Iterations-1; i >=0 ; --i) {
479     Instruction *InstInPreheader = InstsInPreheader[i];
480     NewPhi = IRB.CreatePHI(InstInPreheader->getType(), 2);
481     NewPhi->addIncoming(InstInPreheader, LoopPH);
482     NewPhi->addIncoming(BEVal, BB);
483     DEBUG(dbgs() << "Adding " << *NewPhi << " to " << BB->getName() << "\n");
484     BEVal = NewPhi;
485   }
486   // We are in LCSSA form. So, a value defined inside the Loop is used only
487   // inside the loop. So, the following is safe.
488   Inst2Replace->replaceAllUsesWith(NewPhi);
489   ReplacedInsts.insert(Inst2Replace);
490   ++HexagonNumVectorLoopCarriedReuse;
491 }
492 
493 bool HexagonVectorLoopCarriedReuse::doVLCR() {
494   assert((CurLoop->getSubLoops().size() == 0) &&
495          "Can do VLCR on the innermost loop only");
496   assert((CurLoop->getNumBlocks() == 1) &&
497          "Can do VLCR only on single block loops");
498 
499   bool Changed;
500   bool Continue;
501 
502   DEBUG(dbgs() << "Working on Loop: " << *CurLoop->getHeader() << "\n");
503   do {
504     // Reset datastructures.
505     Dependences.clear();
506     Continue = false;
507 
508     findLoopCarriedDeps();
509     findValueToReuse();
510     if (ReuseCandidate.isDefined()) {
511       reuseValue();
512       Changed = true;
513       Continue = true;
514     }
515     std::for_each(Dependences.begin(), Dependences.end(),
516                   std::default_delete<DepChain>());
517   } while (Continue);
518   return Changed;
519 }
520 void HexagonVectorLoopCarriedReuse::findDepChainFromPHI(Instruction *I,
521                                                         DepChain &D) {
522   PHINode *PN = dyn_cast<PHINode>(I);
523   if (!PN) {
524     D.push_back(I);
525     return;
526   } else {
527     auto NumIncomingValues = PN->getNumIncomingValues();
528     if (NumIncomingValues != 2) {
529       D.clear();
530       return;
531     }
532 
533     BasicBlock *BB = PN->getParent();
534     if (BB != CurLoop->getHeader()) {
535       D.clear();
536       return;
537     }
538 
539     Value *BEVal = PN->getIncomingValueForBlock(BB);
540     Instruction *BEInst = dyn_cast<Instruction>(BEVal);
541     // This is a single block loop with a preheader, so at least
542     // one value should come over the backedge.
543     assert(BEInst && "There should be a value over the backedge");
544 
545     Value *PreHdrVal =
546       PN->getIncomingValueForBlock(CurLoop->getLoopPreheader());
547     if(!PreHdrVal || !isa<Instruction>(PreHdrVal)) {
548       D.clear();
549       return;
550     }
551     D.push_back(PN);
552     findDepChainFromPHI(BEInst, D);
553   }
554   return;
555 }
556 
557 bool HexagonVectorLoopCarriedReuse::isDepChainBtwn(Instruction *I1,
558                                                       Instruction *I2,
559                                                       int Iters) {
560   for (auto *D : Dependences) {
561     if (D->front() == I1 && D->back() == I2 && D->iterations() == Iters)
562       return true;
563   }
564   return false;
565 }
566 DepChain *HexagonVectorLoopCarriedReuse::getDepChainBtwn(Instruction *I1,
567                                                             Instruction *I2) {
568   for (auto *D : Dependences) {
569     if (D->front() == I1 && D->back() == I2)
570       return D;
571   }
572   return nullptr;
573 }
574 void HexagonVectorLoopCarriedReuse::findLoopCarriedDeps() {
575   BasicBlock *BB = CurLoop->getHeader();
576   for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
577     auto *PN = cast<PHINode>(I);
578     if (!isa<VectorType>(PN->getType()))
579       continue;
580 
581     DepChain *D = new DepChain();
582     findDepChainFromPHI(PN, *D);
583     if (D->size() != 0)
584       Dependences.insert(D);
585     else
586       delete D;
587   }
588   DEBUG(dbgs() << "Found " << Dependences.size() << " dependences\n");
589   DEBUG(for (size_t i = 0; i < Dependences.size(); ++i) {
590       dbgs() << *Dependences[i] << "\n";
591     });
592 }
593 Pass *llvm::createHexagonVectorLoopCarriedReusePass() {
594   return new HexagonVectorLoopCarriedReuse();
595 }
596