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> collectCandidates(
195         Loop *L,
196         std::function<bool(const Instruction *, const Value *, const Type *)>
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 *getPointerOperandAndType(Value *MemI,
273                                        Type **PtrElementType = nullptr) {
274 
275   Value *PtrValue = nullptr;
276   Type *PointerElementType = nullptr;
277 
278   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
279     PtrValue = LMemI->getPointerOperand();
280     PointerElementType = LMemI->getType();
281   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
282     PtrValue = SMemI->getPointerOperand();
283     PointerElementType = SMemI->getValueOperand()->getType();
284   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
285     PointerElementType = Type::getInt8Ty(MemI->getContext());
286     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
287         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
288       PtrValue = IMemI->getArgOperand(0);
289     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
290       PtrValue = IMemI->getArgOperand(1);
291     }
292   }
293   /*Get ElementType if PtrElementType is not null.*/
294   if (PtrElementType)
295     *PtrElementType = PointerElementType;
296 
297   return PtrValue;
298 }
299 
300 bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
301   if (skipFunction(F))
302     return false;
303 
304   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
305   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
306   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
307   DT = DTWP ? &DTWP->getDomTree() : nullptr;
308   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
309   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
310   SuccPrepCount = 0;
311 
312   bool MadeChange = false;
313 
314   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
315     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
316       MadeChange |= runOnLoop(*L);
317 
318   return MadeChange;
319 }
320 
321 void PPCLoopInstrFormPrep::addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
322                                         SmallVector<Bucket, 16> &Buckets,
323                                         unsigned MaxCandidateNum) {
324   assert((MemI && getPointerOperandAndType(MemI)) &&
325          "Candidate should be a memory instruction.");
326   assert(LSCEV && "Invalid SCEV for Ptr value.");
327   bool FoundBucket = false;
328   for (auto &B : Buckets) {
329     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
330     if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
331       B.Elements.push_back(BucketElement(CDiff, MemI));
332       FoundBucket = true;
333       break;
334     }
335   }
336 
337   if (!FoundBucket) {
338     if (Buckets.size() == MaxCandidateNum)
339       return;
340     Buckets.push_back(Bucket(LSCEV, MemI));
341   }
342 }
343 
344 SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
345     Loop *L,
346     std::function<bool(const Instruction *, const Value *, const Type *)>
347         isValidCandidate,
348     unsigned MaxCandidateNum) {
349   SmallVector<Bucket, 16> Buckets;
350   for (const auto &BB : L->blocks())
351     for (auto &J : *BB) {
352       Value *PtrValue = nullptr;
353       Type *PointerElementType = nullptr;
354       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
355 
356       if (!PtrValue)
357         continue;
358 
359       if (PtrValue->getType()->getPointerAddressSpace())
360         continue;
361 
362       if (L->isLoopInvariant(PtrValue))
363         continue;
364 
365       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
366       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
367       if (!LARSCEV || LARSCEV->getLoop() != L)
368         continue;
369 
370       if (isValidCandidate(&J, PtrValue, PointerElementType))
371         addOneCandidate(&J, LSCEV, Buckets, MaxCandidateNum);
372     }
373   return Buckets;
374 }
375 
376 bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
377                                                     InstrForm Form) {
378   // RemainderOffsetInfo details:
379   // key:            value of (Offset urem DispConstraint). For DSForm, it can
380   //                 be [0, 4).
381   // first of pair:  the index of first BucketElement whose remainder is equal
382   //                 to key. For key 0, this value must be 0.
383   // second of pair: number of load/stores with the same remainder.
384   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
385 
386   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
387     if (!BucketChain.Elements[j].Offset)
388       RemainderOffsetInfo[0] = std::make_pair(0, 1);
389     else {
390       unsigned Remainder =
391           BucketChain.Elements[j].Offset->getAPInt().urem(Form);
392       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
393         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
394       else
395         RemainderOffsetInfo[Remainder].second++;
396     }
397   }
398   // Currently we choose the most profitable base as the one which has the max
399   // number of load/store with same remainder.
400   // FIXME: adjust the base selection strategy according to load/store offset
401   // distribution.
402   // For example, if we have one candidate chain for DS form preparation, which
403   // contains following load/stores with different remainders:
404   // 1: 10 load/store whose remainder is 1;
405   // 2: 9 load/store whose remainder is 2;
406   // 3: 1 for remainder 3 and 0 for remainder 0;
407   // Now we will choose the first load/store whose remainder is 1 as base and
408   // adjust all other load/stores according to new base, so we will get 10 DS
409   // form and 10 X form.
410   // But we should be more clever, for this case we could use two bases, one for
411   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
412   // 1 X form.
413   unsigned MaxCountRemainder = 0;
414   for (unsigned j = 0; j < (unsigned)Form; j++)
415     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
416         RemainderOffsetInfo[j].second >
417             RemainderOffsetInfo[MaxCountRemainder].second)
418       MaxCountRemainder = j;
419 
420   // Abort when there are too few insts with common base.
421   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
422     return false;
423 
424   // If the first value is most profitable, no needed to adjust BucketChain
425   // elements as they are substracted the first value when collecting.
426   if (MaxCountRemainder == 0)
427     return true;
428 
429   // Adjust load/store to the new chosen base.
430   const SCEV *Offset =
431       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
432   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
433   for (auto &E : BucketChain.Elements) {
434     if (E.Offset)
435       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
436     else
437       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
438   }
439 
440   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
441             BucketChain.Elements[0]);
442   return true;
443 }
444 
445 // FIXME: implement a more clever base choosing policy.
446 // Currently we always choose an exist load/store offset. This maybe lead to
447 // suboptimal code sequences. For example, for one DS chain with offsets
448 // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
449 // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
450 // multipler of 4, it cannot be represented by sint16.
451 bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
452   // We have a choice now of which instruction's memory operand we use as the
453   // base for the generated PHI. Always picking the first instruction in each
454   // bucket does not work well, specifically because that instruction might
455   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
456   // the choice is somewhat arbitrary, because the backend will happily
457   // generate direct offsets from both the pre-incremented and
458   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
459   // instruction in each bucket, and adjust the recurrence and other offsets
460   // accordingly.
461   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
462     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
463       if (II->getIntrinsicID() == Intrinsic::prefetch)
464         continue;
465 
466     // If we'd otherwise pick the first element anyway, there's nothing to do.
467     if (j == 0)
468       break;
469 
470     // If our chosen element has no offset from the base pointer, there's
471     // nothing to do.
472     if (!BucketChain.Elements[j].Offset ||
473         BucketChain.Elements[j].Offset->isZero())
474       break;
475 
476     const SCEV *Offset = BucketChain.Elements[j].Offset;
477     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
478     for (auto &E : BucketChain.Elements) {
479       if (E.Offset)
480         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
481       else
482         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
483     }
484 
485     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
486     break;
487   }
488   return true;
489 }
490 
491 bool PPCLoopInstrFormPrep::rewriteLoadStores(Loop *L, Bucket &BucketChain,
492                                           SmallSet<BasicBlock *, 16> &BBChanged,
493                                           InstrForm Form) {
494   bool MadeChange = false;
495   const SCEVAddRecExpr *BasePtrSCEV =
496       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
497   if (!BasePtrSCEV->isAffine())
498     return MadeChange;
499 
500   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
501 
502   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
503 
504   // The instruction corresponding to the Bucket's BaseSCEV must be the first
505   // in the vector of elements.
506   Instruction *MemI = BucketChain.Elements.begin()->Instr;
507   Value *BasePtr = getPointerOperandAndType(MemI);
508   assert(BasePtr && "No pointer operand");
509 
510   Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
511   Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
512     BasePtr->getType()->getPointerAddressSpace());
513 
514   if (!SE->isLoopInvariant(BasePtrSCEV->getStart(), L))
515     return MadeChange;
516 
517   const SCEVConstant *BasePtrIncSCEV =
518     dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
519   if (!BasePtrIncSCEV)
520     return MadeChange;
521 
522   // For some DS form load/store instructions, it can also be an update form,
523   // if the stride is a multipler of 4. Use update form if prefer it.
524   bool CanPreInc = (Form == UpdateForm ||
525                     ((Form == DSForm) && !BasePtrIncSCEV->getAPInt().urem(4) &&
526                      PreferUpdateForm));
527   const SCEV *BasePtrStartSCEV = nullptr;
528   if (CanPreInc)
529     BasePtrStartSCEV =
530         SE->getMinusSCEV(BasePtrSCEV->getStart(), BasePtrIncSCEV);
531   else
532     BasePtrStartSCEV = BasePtrSCEV->getStart();
533 
534   if (!isSafeToExpand(BasePtrStartSCEV, *SE))
535     return MadeChange;
536 
537   if (alreadyPrepared(L, MemI, BasePtrStartSCEV, BasePtrIncSCEV, Form))
538     return MadeChange;
539 
540   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
541 
542   BasicBlock *Header = L->getHeader();
543   unsigned HeaderLoopPredCount = pred_size(Header);
544   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
545 
546   PHINode *NewPHI =
547       PHINode::Create(I8PtrTy, HeaderLoopPredCount,
548                       getInstrName(MemI, PHINodeNameSuffix),
549                       Header->getFirstNonPHI());
550 
551   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
552   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
553                                             LoopPredecessor->getTerminator());
554 
555   // Note that LoopPredecessor might occur in the predecessor list multiple
556   // times, and we need to add it the right number of times.
557   for (auto PI : predecessors(Header)) {
558     if (PI != LoopPredecessor)
559       continue;
560 
561     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
562   }
563 
564   Instruction *PtrInc = nullptr;
565   Instruction *NewBasePtr = nullptr;
566   if (CanPreInc) {
567     Instruction *InsPoint = &*Header->getFirstInsertionPt();
568     PtrInc = GetElementPtrInst::Create(
569         I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
570         getInstrName(MemI, GEPNodeIncNameSuffix), InsPoint);
571     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
572     for (auto PI : predecessors(Header)) {
573       if (PI == LoopPredecessor)
574         continue;
575 
576       NewPHI->addIncoming(PtrInc, PI);
577     }
578     if (PtrInc->getType() != BasePtr->getType())
579       NewBasePtr = new BitCastInst(
580           PtrInc, BasePtr->getType(),
581           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
582     else
583       NewBasePtr = PtrInc;
584   } else {
585     // Note that LoopPredecessor might occur in the predecessor list multiple
586     // times, and we need to make sure no more incoming value for them in PHI.
587     for (auto PI : predecessors(Header)) {
588       if (PI == LoopPredecessor)
589         continue;
590 
591       // For the latch predecessor, we need to insert a GEP just before the
592       // terminator to increase the address.
593       BasicBlock *BB = PI;
594       Instruction *InsPoint = BB->getTerminator();
595       PtrInc = GetElementPtrInst::Create(
596           I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
597           getInstrName(MemI, GEPNodeIncNameSuffix), InsPoint);
598 
599       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
600 
601       NewPHI->addIncoming(PtrInc, PI);
602     }
603     PtrInc = NewPHI;
604     if (NewPHI->getType() != BasePtr->getType())
605       NewBasePtr =
606           new BitCastInst(NewPHI, BasePtr->getType(),
607                           getInstrName(NewPHI, CastNodeNameSuffix),
608                           &*Header->getFirstInsertionPt());
609     else
610       NewBasePtr = NewPHI;
611   }
612 
613   // Clear the rewriter cache, because values that are in the rewriter's cache
614   // can be deleted below, causing the AssertingVH in the cache to trigger.
615   SCEVE.clear();
616 
617   if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
618     BBChanged.insert(IDel->getParent());
619   BasePtr->replaceAllUsesWith(NewBasePtr);
620   RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
621 
622   // Keep track of the replacement pointer values we've inserted so that we
623   // don't generate more pointer values than necessary.
624   SmallPtrSet<Value *, 16> NewPtrs;
625   NewPtrs.insert(NewBasePtr);
626 
627   for (auto I = std::next(BucketChain.Elements.begin()),
628        IE = BucketChain.Elements.end(); I != IE; ++I) {
629     Value *Ptr = getPointerOperandAndType(I->Instr);
630     assert(Ptr && "No pointer operand");
631     if (NewPtrs.count(Ptr))
632       continue;
633 
634     Instruction *RealNewPtr;
635     if (!I->Offset || I->Offset->getValue()->isZero()) {
636       RealNewPtr = NewBasePtr;
637     } else {
638       Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
639       if (PtrIP && isa<Instruction>(NewBasePtr) &&
640           cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
641         PtrIP = nullptr;
642       else if (PtrIP && isa<PHINode>(PtrIP))
643         PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
644       else if (!PtrIP)
645         PtrIP = I->Instr;
646 
647       GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
648           I8Ty, PtrInc, I->Offset->getValue(),
649           getInstrName(I->Instr, GEPNodeOffNameSuffix), PtrIP);
650       if (!PtrIP)
651         NewPtr->insertAfter(cast<Instruction>(PtrInc));
652       NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
653       RealNewPtr = NewPtr;
654     }
655 
656     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
657       BBChanged.insert(IDel->getParent());
658 
659     Instruction *ReplNewPtr;
660     if (Ptr->getType() != RealNewPtr->getType()) {
661       ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
662         getInstrName(Ptr, CastNodeNameSuffix));
663       ReplNewPtr->insertAfter(RealNewPtr);
664     } else
665       ReplNewPtr = RealNewPtr;
666 
667     Ptr->replaceAllUsesWith(ReplNewPtr);
668     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
669 
670     NewPtrs.insert(RealNewPtr);
671   }
672 
673   MadeChange = true;
674 
675   SuccPrepCount++;
676 
677   if (Form == DSForm && !CanPreInc)
678     DSFormChainRewritten++;
679   else if (Form == DQForm)
680     DQFormChainRewritten++;
681   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
682     UpdFormChainRewritten++;
683 
684   return MadeChange;
685 }
686 
687 bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
688                                        SmallVector<Bucket, 16> &Buckets) {
689   bool MadeChange = false;
690   if (Buckets.empty())
691     return MadeChange;
692   SmallSet<BasicBlock *, 16> BBChanged;
693   for (auto &Bucket : Buckets)
694     // The base address of each bucket is transformed into a phi and the others
695     // are rewritten based on new base.
696     if (prepareBaseForUpdateFormChain(Bucket))
697       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
698 
699   if (MadeChange)
700     for (auto &BB : L->blocks())
701       if (BBChanged.count(BB))
702         DeleteDeadPHIs(BB);
703   return MadeChange;
704 }
705 
706 bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets,
707                                      InstrForm Form) {
708   bool MadeChange = false;
709 
710   if (Buckets.empty())
711     return MadeChange;
712 
713   SmallSet<BasicBlock *, 16> BBChanged;
714   for (auto &Bucket : Buckets) {
715     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
716       continue;
717     if (prepareBaseForDispFormChain(Bucket, Form))
718       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
719   }
720 
721   if (MadeChange)
722     for (auto &BB : L->blocks())
723       if (BBChanged.count(BB))
724         DeleteDeadPHIs(BB);
725   return MadeChange;
726 }
727 
728 // In order to prepare for the preferred instruction form, a PHI is added.
729 // This function will check to see if that PHI already exists and will return
730 // true if it found an existing PHI with the matched start and increment as the
731 // one we wanted to create.
732 bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
733                                         const SCEV *BasePtrStartSCEV,
734                                         const SCEVConstant *BasePtrIncSCEV,
735                                         InstrForm Form) {
736   BasicBlock *BB = MemI->getParent();
737   if (!BB)
738     return false;
739 
740   BasicBlock *PredBB = L->getLoopPredecessor();
741   BasicBlock *LatchBB = L->getLoopLatch();
742 
743   if (!PredBB || !LatchBB)
744     return false;
745 
746   // Run through the PHIs and see if we have some that looks like a preparation
747   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
748   for (auto & CurrentPHI : PHIIter) {
749     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
750     if (!CurrentPHINode)
751       continue;
752 
753     if (!SE->isSCEVable(CurrentPHINode->getType()))
754       continue;
755 
756     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
757 
758     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
759     if (!PHIBasePtrSCEV)
760       continue;
761 
762     const SCEVConstant *PHIBasePtrIncSCEV =
763       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
764     if (!PHIBasePtrIncSCEV)
765       continue;
766 
767     if (CurrentPHINode->getNumIncomingValues() == 2) {
768       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
769            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
770           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
771            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
772         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
773           // The existing PHI (CurrentPHINode) has the same start and increment
774           // as the PHI that we wanted to create.
775           if (Form == UpdateForm &&
776               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
777             ++PHINodeAlreadyExistsUpdate;
778             return true;
779           }
780           if (Form == DSForm || Form == DQForm) {
781             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
782                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
783             if (Diff && !Diff->getAPInt().urem(Form)) {
784               if (Form == DSForm)
785                 ++PHINodeAlreadyExistsDS;
786               else
787                 ++PHINodeAlreadyExistsDQ;
788               return true;
789             }
790           }
791         }
792       }
793     }
794   }
795   return false;
796 }
797 
798 bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
799   bool MadeChange = false;
800 
801   // Only prep. the inner-most loop
802   if (!L->isInnermost())
803     return MadeChange;
804 
805   // Return if already done enough preparation.
806   if (SuccPrepCount >= MaxVarsPrep)
807     return MadeChange;
808 
809   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
810 
811   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
812   // If there is no loop predecessor, or the loop predecessor's terminator
813   // returns a value (which might contribute to determining the loop's
814   // iteration space), insert a new preheader for the loop.
815   if (!LoopPredecessor ||
816       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
817     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
818     if (LoopPredecessor)
819       MadeChange = true;
820   }
821   if (!LoopPredecessor) {
822     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
823     return MadeChange;
824   }
825   // Check if a load/store has update form. This lambda is used by function
826   // collectCandidates which can collect candidates for types defined by lambda.
827   auto isUpdateFormCandidate = [&](const Instruction *I, const Value *PtrValue,
828                                    const Type *PointerElementType) {
829     assert((PtrValue && I) && "Invalid parameter!");
830     // There are no update forms for Altivec vector load/stores.
831     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
832       return false;
833     // There are no update forms for P10 lxvp/stxvp intrinsic.
834     auto *II = dyn_cast<IntrinsicInst>(I);
835     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
836                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
837       return false;
838     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
839     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
840     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
841     // useless and possible to break some original well-form addressing mode
842     // to make this pre-inc prep for it.
843     if (PointerElementType->isIntegerTy(64)) {
844       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
845       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
846       if (!LARSCEV || LARSCEV->getLoop() != L)
847         return false;
848       if (const SCEVConstant *StepConst =
849               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
850         const APInt &ConstInt = StepConst->getValue()->getValue();
851         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
852           return false;
853       }
854     }
855     return true;
856   };
857 
858   // Check if a load/store has DS form.
859   auto isDSFormCandidate = [](const Instruction *I, const Value *PtrValue,
860                               const Type *PointerElementType) {
861     assert((PtrValue && I) && "Invalid parameter!");
862     if (isa<IntrinsicInst>(I))
863       return false;
864     return (PointerElementType->isIntegerTy(64)) ||
865            (PointerElementType->isFloatTy()) ||
866            (PointerElementType->isDoubleTy()) ||
867            (PointerElementType->isIntegerTy(32) &&
868             llvm::any_of(I->users(),
869                          [](const User *U) { return isa<SExtInst>(U); }));
870   };
871 
872   // Check if a load/store has DQ form.
873   auto isDQFormCandidate = [&](const Instruction *I, const Value *PtrValue,
874                                const Type *PointerElementType) {
875     assert((PtrValue && I) && "Invalid parameter!");
876     // Check if it is a P10 lxvp/stxvp intrinsic.
877     auto *II = dyn_cast<IntrinsicInst>(I);
878     if (II)
879       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
880              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
881     // Check if it is a P9 vector load/store.
882     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
883   };
884 
885   // Collect buckets of comparable addresses used by loads and stores for update
886   // form.
887   SmallVector<Bucket, 16> UpdateFormBuckets =
888       collectCandidates(L, isUpdateFormCandidate, MaxVarsUpdateForm);
889 
890   // Prepare for update form.
891   if (!UpdateFormBuckets.empty())
892     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
893 
894   // Collect buckets of comparable addresses used by loads and stores for DS
895   // form.
896   SmallVector<Bucket, 16> DSFormBuckets =
897       collectCandidates(L, isDSFormCandidate, MaxVarsDSForm);
898 
899   // Prepare for DS form.
900   if (!DSFormBuckets.empty())
901     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
902 
903   // Collect buckets of comparable addresses used by loads and stores for DQ
904   // form.
905   SmallVector<Bucket, 16> DQFormBuckets =
906       collectCandidates(L, isDQFormCandidate, MaxVarsDQForm);
907 
908   // Prepare for DQ form.
909   if (!DQFormBuckets.empty())
910     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
911 
912   return MadeChange;
913 }
914