xref: /llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (revision 25b2126b9e9c28e48ce4e6e40af624767e5fb146)
1 //===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a pass to prepare loops for ppc preferred addressing
10 // modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with
11 // update)
12 // Additional PHIs are created for loop induction variables used by load/store
13 // instructions so that preferred addressing modes can be used.
14 //
15 // 1: DS/DQ form preparation, prepare the load/store instructions so that they
16 //    can satisfy the DS/DQ form displacement requirements.
17 //    Generically, this means transforming loops like this:
18 //    for (int i = 0; i < n; ++i) {
19 //      unsigned long x1 = *(unsigned long *)(p + i + 5);
20 //      unsigned long x2 = *(unsigned long *)(p + i + 9);
21 //    }
22 //
23 //    to look like this:
24 //
25 //    unsigned NewP = p + 5;
26 //    for (int i = 0; i < n; ++i) {
27 //      unsigned long x1 = *(unsigned long *)(i + NewP);
28 //      unsigned long x2 = *(unsigned long *)(i + NewP + 4);
29 //    }
30 //
31 // 2: D/DS form with update preparation, prepare the load/store instructions so
32 //    that we can use update form to do pre-increment.
33 //    Generically, this means transforming loops like this:
34 //    for (int i = 0; i < n; ++i)
35 //      array[i] = c;
36 //
37 //    to look like this:
38 //
39 //    T *p = array[-1];
40 //    for (int i = 0; i < n; ++i)
41 //      *++p = c;
42 //===----------------------------------------------------------------------===//
43 
44 #include "PPC.h"
45 #include "PPCSubtarget.h"
46 #include "PPCTargetMachine.h"
47 #include "llvm/ADT/DepthFirstIterator.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallSet.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/Statistic.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/ScalarEvolution.h"
54 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
55 #include "llvm/IR/BasicBlock.h"
56 #include "llvm/IR/CFG.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/IntrinsicsPowerPC.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/Value.h"
65 #include "llvm/InitializePasses.h"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Transforms/Scalar.h"
71 #include "llvm/Transforms/Utils.h"
72 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
73 #include "llvm/Transforms/Utils/Local.h"
74 #include "llvm/Transforms/Utils/LoopUtils.h"
75 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
76 #include <cassert>
77 #include <iterator>
78 #include <utility>
79 
80 #define DEBUG_TYPE "ppc-loop-instr-form-prep"
81 
82 using namespace llvm;
83 
84 static cl::opt<unsigned> MaxVarsPrep("ppc-formprep-max-vars",
85                                  cl::Hidden, cl::init(24),
86   cl::desc("Potential common base number threshold per function for PPC loop "
87            "prep"));
88 
89 static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
90                                  cl::init(true), cl::Hidden,
91   cl::desc("prefer update form when ds form is also a update form"));
92 
93 // Sum of following 3 per loop thresholds for all loops can not be larger
94 // than MaxVarsPrep.
95 // now the thresholds for each kind prep are exterimental values on Power9.
96 static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
97                                  cl::Hidden, cl::init(3),
98   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
99            "form"));
100 
101 static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
102                                  cl::Hidden, cl::init(3),
103   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
104 
105 static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
106                                  cl::Hidden, cl::init(8),
107   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
108 
109 
110 // If would not be profitable if the common base has only one load/store, ISEL
111 // should already be able to choose best load/store form based on offset for
112 // single load/store. Set minimal profitable value default to 2 and make it as
113 // an option.
114 static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
115                                     cl::Hidden, cl::init(2),
116   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
117            "preparation"));
118 
119 STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
120 STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
121 STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
122 STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
123 STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
124 STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
125 
126 namespace {
127   struct BucketElement {
128     BucketElement(const SCEVConstant *O, Instruction *I) : Offset(O), Instr(I) {}
129     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
130 
131     const SCEVConstant *Offset;
132     Instruction *Instr;
133   };
134 
135   struct Bucket {
136     Bucket(const SCEV *B, Instruction *I) : BaseSCEV(B),
137                                             Elements(1, BucketElement(I)) {}
138 
139     const SCEV *BaseSCEV;
140     SmallVector<BucketElement, 16> Elements;
141   };
142 
143   // "UpdateForm" is not a real PPC instruction form, it stands for dform
144   // load/store with update like ldu/stdu, or Prefetch intrinsic.
145   // For DS form instructions, their displacements must be multiple of 4.
146   // For DQ form instructions, their displacements must be multiple of 16.
147   enum InstrForm { UpdateForm = 1, DSForm = 4, DQForm = 16 };
148 
149   class PPCLoopInstrFormPrep : public FunctionPass {
150   public:
151     static char ID; // Pass ID, replacement for typeid
152 
153     PPCLoopInstrFormPrep() : FunctionPass(ID) {
154       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
155     }
156 
157     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
158       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
159     }
160 
161     void getAnalysisUsage(AnalysisUsage &AU) const override {
162       AU.addPreserved<DominatorTreeWrapperPass>();
163       AU.addRequired<LoopInfoWrapperPass>();
164       AU.addPreserved<LoopInfoWrapperPass>();
165       AU.addRequired<ScalarEvolutionWrapperPass>();
166     }
167 
168     bool runOnFunction(Function &F) override;
169 
170   private:
171     PPCTargetMachine *TM = nullptr;
172     const PPCSubtarget *ST;
173     DominatorTree *DT;
174     LoopInfo *LI;
175     ScalarEvolution *SE;
176     bool PreserveLCSSA;
177 
178     /// Successful preparation number for Update/DS/DQ form in all inner most
179     /// loops. One successful preparation will put one common base out of loop,
180     /// this may leads to register presure like LICM does.
181     /// Make sure total preparation number can be controlled by option.
182     unsigned SuccPrepCount;
183 
184     bool runOnLoop(Loop *L);
185 
186     /// Check if required PHI node is already exist in Loop \p L.
187     bool alreadyPrepared(Loop *L, Instruction* MemI,
188                          const SCEV *BasePtrStartSCEV,
189                          const SCEVConstant *BasePtrIncSCEV,
190                          InstrForm Form);
191 
192     /// Collect condition matched(\p isValidCandidate() returns true)
193     /// candidates in Loop \p L.
194     SmallVector<Bucket, 16>
195     collectCandidates(Loop *L,
196                       std::function<bool(const Instruction *, const Value *)>
197                           isValidCandidate,
198                       unsigned MaxCandidateNum);
199 
200     /// Add a candidate to candidates \p Buckets.
201     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
202                          SmallVector<Bucket, 16> &Buckets,
203                          unsigned MaxCandidateNum);
204 
205     /// Prepare all candidates in \p Buckets for update form.
206     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
207 
208     /// Prepare all candidates in \p Buckets for displacement form, now for
209     /// ds/dq.
210     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
211                       InstrForm Form);
212 
213     /// Prepare for one chain \p BucketChain, find the best base element and
214     /// update all other elements in \p BucketChain accordingly.
215     /// \p Form is used to find the best base element.
216     /// If success, best base element must be stored as the first element of
217     /// \p BucketChain.
218     /// Return false if no base element found, otherwise return true.
219     bool prepareBaseForDispFormChain(Bucket &BucketChain,
220                                      InstrForm Form);
221 
222     /// Prepare for one chain \p BucketChain, find the best base element and
223     /// update all other elements in \p BucketChain accordingly.
224     /// If success, best base element must be stored as the first element of
225     /// \p BucketChain.
226     /// Return false if no base element found, otherwise return true.
227     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
228 
229     /// Rewrite load/store instructions in \p BucketChain according to
230     /// preparation.
231     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
232                            SmallSet<BasicBlock *, 16> &BBChanged,
233                            InstrForm Form);
234   };
235 
236 } // end anonymous namespace
237 
238 char PPCLoopInstrFormPrep::ID = 0;
239 static const char *name = "Prepare loop for ppc preferred instruction forms";
240 INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
241 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
242 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
243 INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
244 
245 static constexpr StringRef PHINodeNameSuffix    = ".phi";
246 static constexpr StringRef CastNodeNameSuffix   = ".cast";
247 static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
248 static constexpr StringRef GEPNodeOffNameSuffix = ".off";
249 
250 FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
251   return new PPCLoopInstrFormPrep(TM);
252 }
253 
254 static bool IsPtrInBounds(Value *BasePtr) {
255   Value *StrippedBasePtr = BasePtr;
256   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
257     StrippedBasePtr = BC->getOperand(0);
258   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
259     return GEP->isInBounds();
260 
261   return false;
262 }
263 
264 static std::string getInstrName(const Value *I, StringRef Suffix) {
265   assert(I && "Invalid paramater!");
266   if (I->hasName())
267     return (I->getName() + Suffix).str();
268   else
269     return "";
270 }
271 
272 static Value *GetPointerOperand(Value *MemI) {
273   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
274     return LMemI->getPointerOperand();
275   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
276     return SMemI->getPointerOperand();
277   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
278     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
279         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp)
280       return IMemI->getArgOperand(0);
281     if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp)
282       return IMemI->getArgOperand(1);
283   }
284 
285   return nullptr;
286 }
287 
288 bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
289   if (skipFunction(F))
290     return false;
291 
292   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
293   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
294   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
295   DT = DTWP ? &DTWP->getDomTree() : nullptr;
296   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
297   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
298   SuccPrepCount = 0;
299 
300   bool MadeChange = false;
301 
302   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
303     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
304       MadeChange |= runOnLoop(*L);
305 
306   return MadeChange;
307 }
308 
309 void PPCLoopInstrFormPrep::addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
310                                         SmallVector<Bucket, 16> &Buckets,
311                                         unsigned MaxCandidateNum) {
312   assert((MemI && GetPointerOperand(MemI)) &&
313          "Candidate should be a memory instruction.");
314   assert(LSCEV && "Invalid SCEV for Ptr value.");
315   bool FoundBucket = false;
316   for (auto &B : Buckets) {
317     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
318     if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
319       B.Elements.push_back(BucketElement(CDiff, MemI));
320       FoundBucket = true;
321       break;
322     }
323   }
324 
325   if (!FoundBucket) {
326     if (Buckets.size() == MaxCandidateNum)
327       return;
328     Buckets.push_back(Bucket(LSCEV, MemI));
329   }
330 }
331 
332 SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
333     Loop *L,
334     std::function<bool(const Instruction *, const Value *)> isValidCandidate,
335     unsigned MaxCandidateNum) {
336   SmallVector<Bucket, 16> Buckets;
337   for (const auto &BB : L->blocks())
338     for (auto &J : *BB) {
339       Value *PtrValue;
340 
341       if (LoadInst *LMemI = dyn_cast<LoadInst>(&J)) {
342         PtrValue = LMemI->getPointerOperand();
343       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(&J)) {
344         PtrValue = SMemI->getPointerOperand();
345       } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(&J)) {
346         if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
347             IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
348           PtrValue = IMemI->getArgOperand(0);
349         } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
350           PtrValue = IMemI->getArgOperand(1);
351         } else continue;
352       } else continue;
353 
354       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
355       if (PtrAddrSpace)
356         continue;
357 
358       if (L->isLoopInvariant(PtrValue))
359         continue;
360 
361       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
362       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
363       if (!LARSCEV || LARSCEV->getLoop() != L)
364         continue;
365 
366       if (isValidCandidate(&J, PtrValue))
367         addOneCandidate(&J, LSCEV, Buckets, MaxCandidateNum);
368     }
369   return Buckets;
370 }
371 
372 bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
373                                                     InstrForm Form) {
374   // RemainderOffsetInfo details:
375   // key:            value of (Offset urem DispConstraint). For DSForm, it can
376   //                 be [0, 4).
377   // first of pair:  the index of first BucketElement whose remainder is equal
378   //                 to key. For key 0, this value must be 0.
379   // second of pair: number of load/stores with the same remainder.
380   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
381 
382   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
383     if (!BucketChain.Elements[j].Offset)
384       RemainderOffsetInfo[0] = std::make_pair(0, 1);
385     else {
386       unsigned Remainder =
387           BucketChain.Elements[j].Offset->getAPInt().urem(Form);
388       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
389         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
390       else
391         RemainderOffsetInfo[Remainder].second++;
392     }
393   }
394   // Currently we choose the most profitable base as the one which has the max
395   // number of load/store with same remainder.
396   // FIXME: adjust the base selection strategy according to load/store offset
397   // distribution.
398   // For example, if we have one candidate chain for DS form preparation, which
399   // contains following load/stores with different remainders:
400   // 1: 10 load/store whose remainder is 1;
401   // 2: 9 load/store whose remainder is 2;
402   // 3: 1 for remainder 3 and 0 for remainder 0;
403   // Now we will choose the first load/store whose remainder is 1 as base and
404   // adjust all other load/stores according to new base, so we will get 10 DS
405   // form and 10 X form.
406   // But we should be more clever, for this case we could use two bases, one for
407   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and 1
408   // X form.
409   unsigned MaxCountRemainder = 0;
410   for (unsigned j = 0; j < (unsigned)Form; j++)
411     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
412         RemainderOffsetInfo[j].second >
413             RemainderOffsetInfo[MaxCountRemainder].second)
414       MaxCountRemainder = j;
415 
416   // Abort when there are too few insts with common base.
417   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
418     return false;
419 
420   // If the first value is most profitable, no needed to adjust BucketChain
421   // elements as they are substracted the first value when collecting.
422   if (MaxCountRemainder == 0)
423     return true;
424 
425   // Adjust load/store to the new chosen base.
426   const SCEV *Offset =
427       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
428   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
429   for (auto &E : BucketChain.Elements) {
430     if (E.Offset)
431       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
432     else
433       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
434   }
435 
436   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
437             BucketChain.Elements[0]);
438   return true;
439 }
440 
441 // FIXME: implement a more clever base choosing policy.
442 // Currently we always choose an exist load/store offset. This maybe lead to
443 // suboptimal code sequences. For example, for one DS chain with offsets
444 // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
445 // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
446 // multipler of 4, it cannot be represented by sint16.
447 bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
448   // We have a choice now of which instruction's memory operand we use as the
449   // base for the generated PHI. Always picking the first instruction in each
450   // bucket does not work well, specifically because that instruction might
451   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
452   // the choice is somewhat arbitrary, because the backend will happily
453   // generate direct offsets from both the pre-incremented and
454   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
455   // instruction in each bucket, and adjust the recurrence and other offsets
456   // accordingly.
457   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
458     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
459       if (II->getIntrinsicID() == Intrinsic::prefetch)
460         continue;
461 
462     // If we'd otherwise pick the first element anyway, there's nothing to do.
463     if (j == 0)
464       break;
465 
466     // If our chosen element has no offset from the base pointer, there's
467     // nothing to do.
468     if (!BucketChain.Elements[j].Offset ||
469         BucketChain.Elements[j].Offset->isZero())
470       break;
471 
472     const SCEV *Offset = BucketChain.Elements[j].Offset;
473     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
474     for (auto &E : BucketChain.Elements) {
475       if (E.Offset)
476         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
477       else
478         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
479     }
480 
481     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
482     break;
483   }
484   return true;
485 }
486 
487 bool PPCLoopInstrFormPrep::rewriteLoadStores(Loop *L, Bucket &BucketChain,
488                                           SmallSet<BasicBlock *, 16> &BBChanged,
489                                           InstrForm Form) {
490   bool MadeChange = false;
491   const SCEVAddRecExpr *BasePtrSCEV =
492       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
493   if (!BasePtrSCEV->isAffine())
494     return MadeChange;
495 
496   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
497 
498   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
499 
500   // The instruction corresponding to the Bucket's BaseSCEV must be the first
501   // in the vector of elements.
502   Instruction *MemI = BucketChain.Elements.begin()->Instr;
503   Value *BasePtr = GetPointerOperand(MemI);
504   assert(BasePtr && "No pointer operand");
505 
506   Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
507   Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
508     BasePtr->getType()->getPointerAddressSpace());
509 
510   if (!SE->isLoopInvariant(BasePtrSCEV->getStart(), L))
511     return MadeChange;
512 
513   const SCEVConstant *BasePtrIncSCEV =
514     dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
515   if (!BasePtrIncSCEV)
516     return MadeChange;
517 
518   // For some DS form load/store instructions, it can also be an update form,
519   // if the stride is a multipler of 4. Use update form if prefer it.
520   bool CanPreInc = (Form == UpdateForm ||
521                     ((Form == DSForm) && !BasePtrIncSCEV->getAPInt().urem(4) &&
522                      PreferUpdateForm));
523   const SCEV *BasePtrStartSCEV = nullptr;
524   if (CanPreInc)
525     BasePtrStartSCEV =
526         SE->getMinusSCEV(BasePtrSCEV->getStart(), BasePtrIncSCEV);
527   else
528     BasePtrStartSCEV = BasePtrSCEV->getStart();
529 
530   if (!isSafeToExpand(BasePtrStartSCEV, *SE))
531     return MadeChange;
532 
533   if (alreadyPrepared(L, MemI, BasePtrStartSCEV, BasePtrIncSCEV, Form))
534     return MadeChange;
535 
536   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
537 
538   BasicBlock *Header = L->getHeader();
539   unsigned HeaderLoopPredCount = pred_size(Header);
540   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
541 
542   PHINode *NewPHI =
543       PHINode::Create(I8PtrTy, HeaderLoopPredCount,
544                       getInstrName(MemI, PHINodeNameSuffix),
545                       Header->getFirstNonPHI());
546 
547   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
548   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
549                                             LoopPredecessor->getTerminator());
550 
551   // Note that LoopPredecessor might occur in the predecessor list multiple
552   // times, and we need to add it the right number of times.
553   for (auto PI : predecessors(Header)) {
554     if (PI != LoopPredecessor)
555       continue;
556 
557     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
558   }
559 
560   Instruction *PtrInc = nullptr;
561   Instruction *NewBasePtr = nullptr;
562   if (CanPreInc) {
563     Instruction *InsPoint = &*Header->getFirstInsertionPt();
564     PtrInc = GetElementPtrInst::Create(
565         I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
566         getInstrName(MemI, GEPNodeIncNameSuffix), InsPoint);
567     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
568     for (auto PI : predecessors(Header)) {
569       if (PI == LoopPredecessor)
570         continue;
571 
572       NewPHI->addIncoming(PtrInc, PI);
573     }
574     if (PtrInc->getType() != BasePtr->getType())
575       NewBasePtr = new BitCastInst(
576           PtrInc, BasePtr->getType(),
577           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
578     else
579       NewBasePtr = PtrInc;
580   } else {
581     // Note that LoopPredecessor might occur in the predecessor list multiple
582     // times, and we need to make sure no more incoming value for them in PHI.
583     for (auto PI : predecessors(Header)) {
584       if (PI == LoopPredecessor)
585         continue;
586 
587       // For the latch predecessor, we need to insert a GEP just before the
588       // terminator to increase the address.
589       BasicBlock *BB = PI;
590       Instruction *InsPoint = BB->getTerminator();
591       PtrInc = GetElementPtrInst::Create(
592           I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
593           getInstrName(MemI, GEPNodeIncNameSuffix), InsPoint);
594 
595       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
596 
597       NewPHI->addIncoming(PtrInc, PI);
598     }
599     PtrInc = NewPHI;
600     if (NewPHI->getType() != BasePtr->getType())
601       NewBasePtr =
602           new BitCastInst(NewPHI, BasePtr->getType(),
603                           getInstrName(NewPHI, CastNodeNameSuffix),
604                           &*Header->getFirstInsertionPt());
605     else
606       NewBasePtr = NewPHI;
607   }
608 
609   // Clear the rewriter cache, because values that are in the rewriter's cache
610   // can be deleted below, causing the AssertingVH in the cache to trigger.
611   SCEVE.clear();
612 
613   if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
614     BBChanged.insert(IDel->getParent());
615   BasePtr->replaceAllUsesWith(NewBasePtr);
616   RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
617 
618   // Keep track of the replacement pointer values we've inserted so that we
619   // don't generate more pointer values than necessary.
620   SmallPtrSet<Value *, 16> NewPtrs;
621   NewPtrs.insert(NewBasePtr);
622 
623   for (auto I = std::next(BucketChain.Elements.begin()),
624        IE = BucketChain.Elements.end(); I != IE; ++I) {
625     Value *Ptr = GetPointerOperand(I->Instr);
626     assert(Ptr && "No pointer operand");
627     if (NewPtrs.count(Ptr))
628       continue;
629 
630     Instruction *RealNewPtr;
631     if (!I->Offset || I->Offset->getValue()->isZero()) {
632       RealNewPtr = NewBasePtr;
633     } else {
634       Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
635       if (PtrIP && isa<Instruction>(NewBasePtr) &&
636           cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
637         PtrIP = nullptr;
638       else if (PtrIP && isa<PHINode>(PtrIP))
639         PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
640       else if (!PtrIP)
641         PtrIP = I->Instr;
642 
643       GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
644           I8Ty, PtrInc, I->Offset->getValue(),
645           getInstrName(I->Instr, GEPNodeOffNameSuffix), PtrIP);
646       if (!PtrIP)
647         NewPtr->insertAfter(cast<Instruction>(PtrInc));
648       NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
649       RealNewPtr = NewPtr;
650     }
651 
652     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
653       BBChanged.insert(IDel->getParent());
654 
655     Instruction *ReplNewPtr;
656     if (Ptr->getType() != RealNewPtr->getType()) {
657       ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
658         getInstrName(Ptr, CastNodeNameSuffix));
659       ReplNewPtr->insertAfter(RealNewPtr);
660     } else
661       ReplNewPtr = RealNewPtr;
662 
663     Ptr->replaceAllUsesWith(ReplNewPtr);
664     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
665 
666     NewPtrs.insert(RealNewPtr);
667   }
668 
669   MadeChange = true;
670 
671   SuccPrepCount++;
672 
673   if (Form == DSForm && !CanPreInc)
674     DSFormChainRewritten++;
675   else if (Form == DQForm)
676     DQFormChainRewritten++;
677   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
678     UpdFormChainRewritten++;
679 
680   return MadeChange;
681 }
682 
683 bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
684                                        SmallVector<Bucket, 16> &Buckets) {
685   bool MadeChange = false;
686   if (Buckets.empty())
687     return MadeChange;
688   SmallSet<BasicBlock *, 16> BBChanged;
689   for (auto &Bucket : Buckets)
690     // The base address of each bucket is transformed into a phi and the others
691     // are rewritten based on new base.
692     if (prepareBaseForUpdateFormChain(Bucket))
693       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
694 
695   if (MadeChange)
696     for (auto &BB : L->blocks())
697       if (BBChanged.count(BB))
698         DeleteDeadPHIs(BB);
699   return MadeChange;
700 }
701 
702 bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
703                                      InstrForm Form) {
704   bool MadeChange = false;
705 
706   if (Buckets.empty())
707     return MadeChange;
708 
709   SmallSet<BasicBlock *, 16> BBChanged;
710   for (auto &Bucket : Buckets) {
711     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
712       continue;
713     if (prepareBaseForDispFormChain(Bucket, Form))
714       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
715   }
716 
717   if (MadeChange)
718     for (auto &BB : L->blocks())
719       if (BBChanged.count(BB))
720         DeleteDeadPHIs(BB);
721   return MadeChange;
722 }
723 
724 // In order to prepare for the preferred instruction form, a PHI is added.
725 // This function will check to see if that PHI already exists and will return
726 // true if it found an existing PHI with the matched start and increment as the
727 // one we wanted to create.
728 bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction* MemI,
729                                         const SCEV *BasePtrStartSCEV,
730                                         const SCEVConstant *BasePtrIncSCEV,
731                                         InstrForm Form) {
732   BasicBlock *BB = MemI->getParent();
733   if (!BB)
734     return false;
735 
736   BasicBlock *PredBB = L->getLoopPredecessor();
737   BasicBlock *LatchBB = L->getLoopLatch();
738 
739   if (!PredBB || !LatchBB)
740     return false;
741 
742   // Run through the PHIs and see if we have some that looks like a preparation
743   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
744   for (auto & CurrentPHI : PHIIter) {
745     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
746     if (!CurrentPHINode)
747       continue;
748 
749     if (!SE->isSCEVable(CurrentPHINode->getType()))
750       continue;
751 
752     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
753 
754     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
755     if (!PHIBasePtrSCEV)
756       continue;
757 
758     const SCEVConstant *PHIBasePtrIncSCEV =
759       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
760     if (!PHIBasePtrIncSCEV)
761       continue;
762 
763     if (CurrentPHINode->getNumIncomingValues() == 2) {
764       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
765            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
766           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
767            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
768         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
769           // The existing PHI (CurrentPHINode) has the same start and increment
770           // as the PHI that we wanted to create.
771           if (Form == UpdateForm &&
772               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
773             ++PHINodeAlreadyExistsUpdate;
774             return true;
775           }
776           if (Form == DSForm || Form == DQForm) {
777             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
778                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
779             if (Diff && !Diff->getAPInt().urem(Form)) {
780               if (Form == DSForm)
781                 ++PHINodeAlreadyExistsDS;
782               else
783                 ++PHINodeAlreadyExistsDQ;
784               return true;
785             }
786           }
787         }
788       }
789     }
790   }
791   return false;
792 }
793 
794 bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
795   bool MadeChange = false;
796 
797   // Only prep. the inner-most loop
798   if (!L->isInnermost())
799     return MadeChange;
800 
801   // Return if already done enough preparation.
802   if (SuccPrepCount >= MaxVarsPrep)
803     return MadeChange;
804 
805   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
806 
807   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
808   // If there is no loop predecessor, or the loop predecessor's terminator
809   // returns a value (which might contribute to determining the loop's
810   // iteration space), insert a new preheader for the loop.
811   if (!LoopPredecessor ||
812       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
813     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
814     if (LoopPredecessor)
815       MadeChange = true;
816   }
817   if (!LoopPredecessor) {
818     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
819     return MadeChange;
820   }
821   // Check if a load/store has update form. This lambda is used by function
822   // collectCandidates which can collect candidates for types defined by lambda.
823   auto isUpdateFormCandidate = [&] (const Instruction *I,
824                                     const Value *PtrValue) {
825     assert((PtrValue && I) && "Invalid parameter!");
826     // There are no update forms for Altivec vector load/stores.
827     if (ST && ST->hasAltivec() &&
828         PtrValue->getType()->getPointerElementType()->isVectorTy())
829       return false;
830     // There are no update forms for P10 lxvp/stxvp intrinsic.
831     auto *II = dyn_cast<IntrinsicInst>(I);
832     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
833                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
834       return false;
835     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
836     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
837     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
838     // useless and possible to break some original well-form addressing mode
839     // to make this pre-inc prep for it.
840     if (PtrValue->getType()->getPointerElementType()->isIntegerTy(64)) {
841       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
842       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
843       if (!LARSCEV || LARSCEV->getLoop() != L)
844         return false;
845       if (const SCEVConstant *StepConst =
846               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
847         const APInt &ConstInt = StepConst->getValue()->getValue();
848         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
849           return false;
850       }
851     }
852     return true;
853   };
854 
855   // Check if a load/store has DS form.
856   auto isDSFormCandidate = [] (const Instruction *I, const Value *PtrValue) {
857     assert((PtrValue && I) && "Invalid parameter!");
858     if (isa<IntrinsicInst>(I))
859       return false;
860     Type *PointerElementType = PtrValue->getType()->getPointerElementType();
861     return (PointerElementType->isIntegerTy(64)) ||
862            (PointerElementType->isFloatTy()) ||
863            (PointerElementType->isDoubleTy()) ||
864            (PointerElementType->isIntegerTy(32) &&
865             llvm::any_of(I->users(),
866                          [](const User *U) { return isa<SExtInst>(U); }));
867   };
868 
869   // Check if a load/store has DQ form.
870   auto isDQFormCandidate = [&] (const Instruction *I, const Value *PtrValue) {
871     assert((PtrValue && I) && "Invalid parameter!");
872     // Check if it is a P10 lxvp/stxvp intrinsic.
873     auto *II = dyn_cast<IntrinsicInst>(I);
874     if (II)
875       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
876              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
877     // Check if it is a P9 vector load/store.
878     return ST && ST->hasP9Vector() &&
879            (PtrValue->getType()->getPointerElementType()->isVectorTy());
880   };
881 
882   // intrinsic for update form.
883   SmallVector<Bucket, 16> UpdateFormBuckets =
884       collectCandidates(L, isUpdateFormCandidate, MaxVarsUpdateForm);
885 
886   // Prepare for update form.
887   if (!UpdateFormBuckets.empty())
888     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
889 
890   // Collect buckets of comparable addresses used by loads and stores for DS
891   // form.
892   SmallVector<Bucket, 16> DSFormBuckets =
893       collectCandidates(L, isDSFormCandidate, MaxVarsDSForm);
894 
895   // Prepare for DS form.
896   if (!DSFormBuckets.empty())
897     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
898 
899   // Collect buckets of comparable addresses used by loads and stores for DQ
900   // form.
901   SmallVector<Bucket, 16> DQFormBuckets =
902       collectCandidates(L, isDQFormCandidate, MaxVarsDQForm);
903 
904   // Prepare for DQ form.
905   if (!DQFormBuckets.empty())
906     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
907 
908   return MadeChange;
909 }
910