df65227233e66eccdce20b9e4b68c4be9567f830
[oota-llvm.git] / lib / Target / PowerPC / PPCLoopPreIncPrep.cpp
1 //===------ PPCLoopPreIncPrep.cpp - Loop Pre-Inc. AM Prep. Pass -----------===//
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 //
10 // This file implements a pass to prepare loops for pre-increment addressing
11 // modes. Additional PHIs are created for loop induction variables used by
12 // load/store instructions so that the pre-increment forms can be used.
13 // Generically, this means transforming loops like this:
14 //   for (int i = 0; i < n; ++i)
15 //     array[i] = c;
16 // to look like this:
17 //   T *p = array[-1];
18 //   for (int i = 0; i < n; ++i)
19 //     *++p = c;
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "ppc-loop-preinc-prep"
23 #include "PPC.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/CodeMetrics.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/Analysis/ScalarEvolution.h"
32 #include "llvm/Analysis/ScalarEvolutionExpander.h"
33 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/CFG.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/LoopUtils.h"
45 #include "llvm/Transforms/Utils/ValueMapper.h"
46 using namespace llvm;
47
48 // By default, we limit this to creating 16 PHIs (which is a little over half
49 // of the allocatable register set).
50 static cl::opt<unsigned> MaxVars("ppc-preinc-prep-max-vars",
51                                  cl::Hidden, cl::init(16),
52   cl::desc("Potential PHI threshold for PPC preinc loop prep"));
53
54 namespace llvm {
55   void initializePPCLoopPreIncPrepPass(PassRegistry&);
56 }
57
58 namespace {
59
60   class PPCLoopPreIncPrep : public FunctionPass {
61   public:
62     static char ID; // Pass ID, replacement for typeid
63     PPCLoopPreIncPrep() : FunctionPass(ID), TM(nullptr) {
64       initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
65     }
66     PPCLoopPreIncPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
67       initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
68     }
69
70     void getAnalysisUsage(AnalysisUsage &AU) const override {
71       AU.addPreserved<DominatorTreeWrapperPass>();
72       AU.addRequired<LoopInfoWrapperPass>();
73       AU.addPreserved<LoopInfoWrapperPass>();
74       AU.addRequired<ScalarEvolution>();
75     }
76
77     bool runOnFunction(Function &F) override;
78
79     bool runOnLoop(Loop *L);
80     void simplifyLoopLatch(Loop *L);
81     bool rotateLoop(Loop *L);
82
83   private:
84     PPCTargetMachine *TM;
85     LoopInfo *LI;
86     ScalarEvolution *SE;
87     const DataLayout *DL;
88   };
89 }
90
91 char PPCLoopPreIncPrep::ID = 0;
92 static const char *name = "Prepare loop for pre-inc. addressing modes";
93 INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
94 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
95 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
96 INITIALIZE_PASS_END(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
97
98 FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
99   return new PPCLoopPreIncPrep(TM);
100 }
101
102 namespace {
103   struct SCEVLess : std::binary_function<const SCEV *, const SCEV *, bool>
104   {
105     SCEVLess(ScalarEvolution *SE) : SE(SE) {}
106
107     bool operator() (const SCEV *X, const SCEV *Y) const {
108       const SCEV *Diff = SE->getMinusSCEV(X, Y);
109       return cast<SCEVConstant>(Diff)->getValue()->getSExtValue() < 0;
110     }
111
112   protected:
113     ScalarEvolution *SE;
114   };
115 }
116
117 static bool IsPtrInBounds(Value *BasePtr) {
118   Value *StrippedBasePtr = BasePtr;
119   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
120     StrippedBasePtr = BC->getOperand(0);
121   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
122     return GEP->isInBounds();
123
124   return false;
125 }
126
127 static Value *GetPointerOperand(Value *MemI) {
128   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
129     return LMemI->getPointerOperand();
130   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
131     return SMemI->getPointerOperand();
132   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
133     if (IMemI->getIntrinsicID() == Intrinsic::prefetch)
134       return IMemI->getArgOperand(0);
135   }
136
137   return 0;
138 }
139
140 bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
141   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
142   SE = &getAnalysis<ScalarEvolution>();
143
144   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
145   DL = DLP ? &DLP->getDataLayout() : 0;
146
147   bool MadeChange = false;
148
149   for (LoopInfo::iterator I = LI->begin(), E = LI->end();
150        I != E; ++I) {
151     Loop *L = *I;
152     MadeChange |= runOnLoop(L);
153   }
154
155   return MadeChange;
156 }
157
158 bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
159   bool MadeChange = false;
160
161   if (!DL)
162     return MadeChange;
163
164   // Only prep. the inner-most loop
165   if (!L->empty())
166     return MadeChange;
167
168   BasicBlock *Header = L->getHeader();
169
170   const PPCSubtarget *ST =
171     TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
172
173   unsigned HeaderLoopPredCount = 0;
174   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
175        PI != PE; ++PI) {
176     ++HeaderLoopPredCount;
177   }
178
179   // Collect buckets of comparable addresses used by loads and stores.
180   typedef std::multimap<const SCEV *, Instruction *, SCEVLess> Bucket;
181   SmallVector<Bucket, 16> Buckets;
182   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
183        I != IE; ++I) {
184     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
185         J != JE; ++J) {
186       Value *PtrValue;
187       Instruction *MemI;
188
189       if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
190         MemI = LMemI;
191         PtrValue = LMemI->getPointerOperand();
192       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
193         MemI = SMemI;
194         PtrValue = SMemI->getPointerOperand();
195       } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
196         if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
197           MemI = IMemI;
198           PtrValue = IMemI->getArgOperand(0);
199         } else continue;
200       } else continue;
201
202       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
203       if (PtrAddrSpace)
204         continue;
205
206       // There are no update forms for Altivec vector load/stores.
207       if (ST && ST->hasAltivec() &&
208           PtrValue->getType()->getPointerElementType()->isVectorTy())
209         continue;
210
211       if (L->isLoopInvariant(PtrValue))
212         continue;
213
214       const SCEV *LSCEV = SE->getSCEV(PtrValue);
215       if (!isa<SCEVAddRecExpr>(LSCEV))
216         continue;
217
218       bool FoundBucket = false;
219       for (unsigned i = 0, e = Buckets.size(); i != e; ++i)
220         for (Bucket::iterator K = Buckets[i].begin(), KE = Buckets[i].end();
221              K != KE; ++K) {
222           const SCEV *Diff = SE->getMinusSCEV(K->first, LSCEV);
223           if (isa<SCEVConstant>(Diff)) {
224             Buckets[i].insert(std::make_pair(LSCEV, MemI));
225             FoundBucket = true;
226             break;
227           }
228         }
229
230       if (!FoundBucket) {
231         Buckets.push_back(Bucket(SCEVLess(SE)));
232         Buckets[Buckets.size()-1].insert(std::make_pair(LSCEV, MemI));
233       }
234     }
235   }
236
237   if (Buckets.empty() || Buckets.size() > MaxVars)
238     return MadeChange;
239
240   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
241   // If there is no loop predecessor, or the loop predecessor's terminator
242   // returns a value (which might contribute to determining the loop's
243   // iteration space), insert a new preheader for the loop.
244   if (!LoopPredecessor ||
245       !LoopPredecessor->getTerminator()->getType()->isVoidTy())
246     LoopPredecessor = InsertPreheaderForLoop(L, this);
247   if (!LoopPredecessor)
248     return MadeChange;
249
250   SmallSet<BasicBlock *, 16> BBChanged;
251   for (unsigned i = 0, e = Buckets.size(); i != e; ++i) {
252     // The base address of each bucket is transformed into a phi and the others
253     // are rewritten as offsets of that variable.
254
255     const SCEVAddRecExpr *BasePtrSCEV =
256       cast<SCEVAddRecExpr>(Buckets[i].begin()->first);
257     if (!BasePtrSCEV->isAffine())
258       continue;
259
260     Instruction *MemI = Buckets[i].begin()->second;
261     Value *BasePtr = GetPointerOperand(MemI);
262     assert(BasePtr && "No pointer operand");
263
264     Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
265       BasePtr->getType()->getPointerAddressSpace());
266
267     const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
268     if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
269       continue;
270
271     const SCEVConstant *BasePtrIncSCEV =
272       dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
273     if (!BasePtrIncSCEV)
274       continue;
275     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
276     if (!isSafeToExpand(BasePtrStartSCEV, *SE))
277       continue;
278
279     PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
280       MemI->hasName() ? MemI->getName() + ".phi" : "",
281       Header->getFirstNonPHI());
282
283     SCEVExpander SCEVE(*SE, "pistart");
284     Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
285       LoopPredecessor->getTerminator());
286
287     // Note that LoopPredecessor might occur in the predecessor list multiple
288     // times, and we need to add it the right number of times.
289     for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
290          PI != PE; ++PI) {
291       if (*PI != LoopPredecessor)
292         continue;
293
294       NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
295     }
296
297     Instruction *InsPoint = Header->getFirstInsertionPt();
298     GetElementPtrInst *PtrInc =
299       GetElementPtrInst::Create(NewPHI, BasePtrIncSCEV->getValue(),
300         MemI->hasName() ? MemI->getName() + ".inc" : "", InsPoint);
301     PtrInc->setIsInBounds(IsPtrInBounds(BasePtr));
302     for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
303          PI != PE; ++PI) {
304       if (*PI == LoopPredecessor)
305         continue;
306
307       NewPHI->addIncoming(PtrInc, *PI);
308     }
309
310     Instruction *NewBasePtr;
311     if (PtrInc->getType() != BasePtr->getType())
312       NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
313         PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
314     else
315       NewBasePtr = PtrInc;
316
317     if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
318       BBChanged.insert(IDel->getParent());
319     BasePtr->replaceAllUsesWith(NewBasePtr);
320     RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
321
322     Value *LastNewPtr = NewBasePtr;
323     for (Bucket::iterator I = std::next(Buckets[i].begin()),
324          IE = Buckets[i].end(); I != IE; ++I) {
325       Value *Ptr = GetPointerOperand(I->second);
326       assert(Ptr && "No pointer operand");
327       if (Ptr == LastNewPtr)
328         continue;
329
330       Instruction *RealNewPtr;
331       const SCEVConstant *Diff =
332         cast<SCEVConstant>(SE->getMinusSCEV(I->first, BasePtrSCEV));
333       if (Diff->isZero()) {
334         RealNewPtr = NewBasePtr;
335       } else {
336         Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
337         if (PtrIP && isa<Instruction>(NewBasePtr) &&
338             cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
339           PtrIP = 0;
340         else if (isa<PHINode>(PtrIP))
341           PtrIP = PtrIP->getParent()->getFirstInsertionPt();
342         else if (!PtrIP)
343           PtrIP = I->second;
344   
345         GetElementPtrInst *NewPtr =
346           GetElementPtrInst::Create(PtrInc, Diff->getValue(),
347             I->second->hasName() ? I->second->getName() + ".off" : "", PtrIP);
348         if (!PtrIP)
349           NewPtr->insertAfter(cast<Instruction>(PtrInc));
350         NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
351         RealNewPtr = NewPtr;
352       }
353
354       if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
355         BBChanged.insert(IDel->getParent());
356
357       Instruction *ReplNewPtr;
358       if (Ptr->getType() != RealNewPtr->getType()) {
359         ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
360           Ptr->hasName() ? Ptr->getName() + ".cast" : "");
361         ReplNewPtr->insertAfter(RealNewPtr);
362       } else
363         ReplNewPtr = RealNewPtr;
364
365       Ptr->replaceAllUsesWith(ReplNewPtr);
366       RecursivelyDeleteTriviallyDeadInstructions(Ptr);
367
368       LastNewPtr = RealNewPtr;
369     }
370
371     MadeChange = true;
372   }
373
374   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
375        I != IE; ++I) {
376     if (BBChanged.count(*I))
377       DeleteDeadPHIs(*I);
378   }
379
380   return MadeChange;
381 }
382