xref: /freebsd/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
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 // 3: common multiple chains for the load/stores with same offsets in the loop,
44 //    so that we can reuse the offsets and reduce the register pressure in the
45 //    loop. This transformation can also increase the loop ILP as now each chain
46 //    uses its own loop induction add/addi. But this will increase the number of
47 //    add/addi in the loop.
48 //
49 //    Generically, this means transforming loops like this:
50 //
51 //    char *p;
52 //    A1 = p + base1
53 //    A2 = p + base1 + offset
54 //    B1 = p + base2
55 //    B2 = p + base2 + offset
56 //
57 //    for (int i = 0; i < n; i++)
58 //      unsigned long x1 = *(unsigned long *)(A1 + i);
59 //      unsigned long x2 = *(unsigned long *)(A2 + i)
60 //      unsigned long x3 = *(unsigned long *)(B1 + i);
61 //      unsigned long x4 = *(unsigned long *)(B2 + i);
62 //    }
63 //
64 //    to look like this:
65 //
66 //    A1_new = p + base1 // chain 1
67 //    B1_new = p + base2 // chain 2, now inside the loop, common offset is
68 //                       // reused.
69 //
70 //    for (long long i = 0; i < n; i+=count) {
71 //      unsigned long x1 = *(unsigned long *)(A1_new + i);
72 //      unsigned long x2 = *(unsigned long *)((A1_new + i) + offset);
73 //      unsigned long x3 = *(unsigned long *)(B1_new + i);
74 //      unsigned long x4 = *(unsigned long *)((B1_new + i) + offset);
75 //    }
76 //===----------------------------------------------------------------------===//
77 
78 #include "PPC.h"
79 #include "PPCSubtarget.h"
80 #include "PPCTargetMachine.h"
81 #include "llvm/ADT/DepthFirstIterator.h"
82 #include "llvm/ADT/SmallPtrSet.h"
83 #include "llvm/ADT/SmallSet.h"
84 #include "llvm/ADT/SmallVector.h"
85 #include "llvm/ADT/Statistic.h"
86 #include "llvm/Analysis/LoopInfo.h"
87 #include "llvm/Analysis/ScalarEvolution.h"
88 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
89 #include "llvm/IR/BasicBlock.h"
90 #include "llvm/IR/CFG.h"
91 #include "llvm/IR/Dominators.h"
92 #include "llvm/IR/Instruction.h"
93 #include "llvm/IR/Instructions.h"
94 #include "llvm/IR/IntrinsicInst.h"
95 #include "llvm/IR/IntrinsicsPowerPC.h"
96 #include "llvm/IR/Module.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/InitializePasses.h"
100 #include "llvm/Pass.h"
101 #include "llvm/Support/Casting.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Transforms/Scalar.h"
105 #include "llvm/Transforms/Utils.h"
106 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
107 #include "llvm/Transforms/Utils/Local.h"
108 #include "llvm/Transforms/Utils/LoopUtils.h"
109 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
110 #include <cassert>
111 #include <iterator>
112 #include <utility>
113 
114 #define DEBUG_TYPE "ppc-loop-instr-form-prep"
115 
116 using namespace llvm;
117 
118 static cl::opt<unsigned>
119     MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
120                 cl::desc("Potential common base number threshold per function "
121                          "for PPC loop prep"));
122 
123 static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
124                                  cl::init(true), cl::Hidden,
125   cl::desc("prefer update form when ds form is also a update form"));
126 
127 static cl::opt<bool> EnableUpdateFormForNonConstInc(
128     "ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden,
129     cl::desc("prepare update form when the load/store increment is a loop "
130              "invariant non-const value."));
131 
132 static cl::opt<bool> EnableChainCommoning(
133     "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
134     cl::desc("Enable chain commoning in PPC loop prepare pass."));
135 
136 // Sum of following 3 per loop thresholds for all loops can not be larger
137 // than MaxVarsPrep.
138 // now the thresholds for each kind prep are exterimental values on Power9.
139 static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
140                                  cl::Hidden, cl::init(3),
141   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
142            "form"));
143 
144 static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
145                                  cl::Hidden, cl::init(3),
146   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
147 
148 static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
149                                  cl::Hidden, cl::init(8),
150   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
151 
152 // Commoning chain will reduce the register pressure, so we don't consider about
153 // the PHI nodes number.
154 // But commoning chain will increase the addi/add number in the loop and also
155 // increase loop ILP. Maximum chain number should be same with hardware
156 // IssueWidth, because we won't benefit from ILP if the parallel chains number
157 // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so
158 // there would be 4 buckets at most on P9(IssueWidth is 8).
159 static cl::opt<unsigned> MaxVarsChainCommon(
160     "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
161     cl::desc("Bucket number per loop for PPC loop chain common"));
162 
163 // If would not be profitable if the common base has only one load/store, ISEL
164 // should already be able to choose best load/store form based on offset for
165 // single load/store. Set minimal profitable value default to 2 and make it as
166 // an option.
167 static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
168                                     cl::Hidden, cl::init(2),
169   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
170            "preparation"));
171 
172 static cl::opt<unsigned> ChainCommonPrepMinThreshold(
173     "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
174     cl::desc("Minimal common base load/store instructions triggering chain "
175              "commoning preparation. Must be not smaller than 4"));
176 
177 STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
178 STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
179 STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
180 STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
181 STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
182 STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
183 STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
184 
185 namespace {
186   struct BucketElement {
187     BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
188     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
189 
190     const SCEV *Offset;
191     Instruction *Instr;
192   };
193 
194   struct Bucket {
195     Bucket(const SCEV *B, Instruction *I)
196         : BaseSCEV(B), Elements(1, BucketElement(I)) {
197       ChainSize = 0;
198     }
199 
200     // The base of the whole bucket.
201     const SCEV *BaseSCEV;
202 
203     // All elements in the bucket. In the bucket, the element with the BaseSCEV
204     // has no offset and all other elements are stored as offsets to the
205     // BaseSCEV.
206     SmallVector<BucketElement, 16> Elements;
207 
208     // The potential chains size. This is used for chain commoning only.
209     unsigned ChainSize;
210 
211     // The base for each potential chain. This is used for chain commoning only.
212     SmallVector<BucketElement, 16> ChainBases;
213   };
214 
215   // "UpdateForm" is not a real PPC instruction form, it stands for dform
216   // load/store with update like ldu/stdu, or Prefetch intrinsic.
217   // For DS form instructions, their displacements must be multiple of 4.
218   // For DQ form instructions, their displacements must be multiple of 16.
219   enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
220 
221   class PPCLoopInstrFormPrep : public FunctionPass {
222   public:
223     static char ID; // Pass ID, replacement for typeid
224 
225     PPCLoopInstrFormPrep() : FunctionPass(ID) {
226       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
227     }
228 
229     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
230       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
231     }
232 
233     void getAnalysisUsage(AnalysisUsage &AU) const override {
234       AU.addPreserved<DominatorTreeWrapperPass>();
235       AU.addRequired<LoopInfoWrapperPass>();
236       AU.addPreserved<LoopInfoWrapperPass>();
237       AU.addRequired<ScalarEvolutionWrapperPass>();
238     }
239 
240     bool runOnFunction(Function &F) override;
241 
242   private:
243     PPCTargetMachine *TM = nullptr;
244     const PPCSubtarget *ST;
245     DominatorTree *DT;
246     LoopInfo *LI;
247     ScalarEvolution *SE;
248     bool PreserveLCSSA;
249     bool HasCandidateForPrepare;
250 
251     /// Successful preparation number for Update/DS/DQ form in all inner most
252     /// loops. One successful preparation will put one common base out of loop,
253     /// this may leads to register presure like LICM does.
254     /// Make sure total preparation number can be controlled by option.
255     unsigned SuccPrepCount;
256 
257     bool runOnLoop(Loop *L);
258 
259     /// Check if required PHI node is already exist in Loop \p L.
260     bool alreadyPrepared(Loop *L, Instruction *MemI,
261                          const SCEV *BasePtrStartSCEV,
262                          const SCEV *BasePtrIncSCEV, PrepForm Form);
263 
264     /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
265     Value *getNodeForInc(Loop *L, Instruction *MemI,
266                          const SCEV *BasePtrIncSCEV);
267 
268     /// Common chains to reuse offsets for a loop to reduce register pressure.
269     bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
270 
271     /// Find out the potential commoning chains and their bases.
272     bool prepareBasesForCommoningChains(Bucket &BucketChain);
273 
274     /// Rewrite load/store according to the common chains.
275     bool
276     rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
277                                         SmallSet<BasicBlock *, 16> &BBChanged);
278 
279     /// Collect condition matched(\p isValidCandidate() returns true)
280     /// candidates in Loop \p L.
281     SmallVector<Bucket, 16> collectCandidates(
282         Loop *L,
283         std::function<bool(const Instruction *, Value *, const Type *)>
284             isValidCandidate,
285         std::function<bool(const SCEV *)> isValidDiff,
286         unsigned MaxCandidateNum);
287 
288     /// Add a candidate to candidates \p Buckets if diff between candidate and
289     /// one base in \p Buckets matches \p isValidDiff.
290     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
291                          SmallVector<Bucket, 16> &Buckets,
292                          std::function<bool(const SCEV *)> isValidDiff,
293                          unsigned MaxCandidateNum);
294 
295     /// Prepare all candidates in \p Buckets for update form.
296     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
297 
298     /// Prepare all candidates in \p Buckets for displacement form, now for
299     /// ds/dq.
300     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
301 
302     /// Prepare for one chain \p BucketChain, find the best base element and
303     /// update all other elements in \p BucketChain accordingly.
304     /// \p Form is used to find the best base element.
305     /// If success, best base element must be stored as the first element of
306     /// \p BucketChain.
307     /// Return false if no base element found, otherwise return true.
308     bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
309 
310     /// Prepare for one chain \p BucketChain, find the best base element and
311     /// update all other elements in \p BucketChain accordingly.
312     /// If success, best base element must be stored as the first element of
313     /// \p BucketChain.
314     /// Return false if no base element found, otherwise return true.
315     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
316 
317     /// Rewrite load/store instructions in \p BucketChain according to
318     /// preparation.
319     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
320                            SmallSet<BasicBlock *, 16> &BBChanged,
321                            PrepForm Form);
322 
323     /// Rewrite for the base load/store of a chain.
324     std::pair<Instruction *, Instruction *>
325     rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
326                    Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
327                    SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
328 
329     /// Rewrite for the other load/stores of a chain according to the new \p
330     /// Base.
331     Instruction *
332     rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
333                             const BucketElement &Element, Value *OffToBase,
334                             SmallPtrSet<Value *, 16> &DeletedPtrs);
335   };
336 
337 } // end anonymous namespace
338 
339 char PPCLoopInstrFormPrep::ID = 0;
340 static const char *name = "Prepare loop for ppc preferred instruction forms";
341 INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
342 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
343 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
344 INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
345 
346 static constexpr StringRef PHINodeNameSuffix    = ".phi";
347 static constexpr StringRef CastNodeNameSuffix   = ".cast";
348 static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
349 static constexpr StringRef GEPNodeOffNameSuffix = ".off";
350 
351 FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
352   return new PPCLoopInstrFormPrep(TM);
353 }
354 
355 static bool IsPtrInBounds(Value *BasePtr) {
356   Value *StrippedBasePtr = BasePtr;
357   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
358     StrippedBasePtr = BC->getOperand(0);
359   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
360     return GEP->isInBounds();
361 
362   return false;
363 }
364 
365 static std::string getInstrName(const Value *I, StringRef Suffix) {
366   assert(I && "Invalid paramater!");
367   if (I->hasName())
368     return (I->getName() + Suffix).str();
369   else
370     return "";
371 }
372 
373 static Value *getPointerOperandAndType(Value *MemI,
374                                        Type **PtrElementType = nullptr) {
375 
376   Value *PtrValue = nullptr;
377   Type *PointerElementType = nullptr;
378 
379   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
380     PtrValue = LMemI->getPointerOperand();
381     PointerElementType = LMemI->getType();
382   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
383     PtrValue = SMemI->getPointerOperand();
384     PointerElementType = SMemI->getValueOperand()->getType();
385   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
386     PointerElementType = Type::getInt8Ty(MemI->getContext());
387     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
388         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
389       PtrValue = IMemI->getArgOperand(0);
390     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
391       PtrValue = IMemI->getArgOperand(1);
392     }
393   }
394   /*Get ElementType if PtrElementType is not null.*/
395   if (PtrElementType)
396     *PtrElementType = PointerElementType;
397 
398   return PtrValue;
399 }
400 
401 bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
402   if (skipFunction(F))
403     return false;
404 
405   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
406   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
407   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
408   DT = DTWP ? &DTWP->getDomTree() : nullptr;
409   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
410   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
411   SuccPrepCount = 0;
412 
413   bool MadeChange = false;
414 
415   for (Loop *I : *LI)
416     for (Loop *L : depth_first(I))
417       MadeChange |= runOnLoop(L);
418 
419   return MadeChange;
420 }
421 
422 // Finding the minimal(chain_number + reusable_offset_number) is a complicated
423 // algorithmic problem.
424 // For now, the algorithm used here is simply adjusted to handle the case for
425 // manually unrolling cases.
426 // FIXME: use a more powerful algorithm to find minimal sum of chain_number and
427 // reusable_offset_number for one base with multiple offsets.
428 bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
429   // The minimal size for profitable chain commoning:
430   // A1 = base + offset1
431   // A2 = base + offset2 (offset2 - offset1 = X)
432   // A3 = base + offset3
433   // A4 = base + offset4 (offset4 - offset3 = X)
434   // ======>
435   // base1 = base + offset1
436   // base2 = base + offset3
437   // A1 = base1
438   // A2 = base1 + X
439   // A3 = base2
440   // A4 = base2 + X
441   //
442   // There is benefit because of reuse of offest 'X'.
443 
444   assert(ChainCommonPrepMinThreshold >= 4 &&
445          "Thredhold can not be smaller than 4!\n");
446   if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
447     return false;
448 
449   // We simply select the FirstOffset as the first reusable offset between each
450   // chain element 1 and element 0.
451   const SCEV *FirstOffset = CBucket.Elements[1].Offset;
452 
453   // Figure out how many times above FirstOffset is used in the chain.
454   // For a success commoning chain candidate, offset difference between each
455   // chain element 1 and element 0 must be also FirstOffset.
456   unsigned FirstOffsetReusedCount = 1;
457 
458   // Figure out how many times above FirstOffset is used in the first chain.
459   // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
460   unsigned FirstOffsetReusedCountInFirstChain = 1;
461 
462   unsigned EleNum = CBucket.Elements.size();
463   bool SawChainSeparater = false;
464   for (unsigned j = 2; j != EleNum; ++j) {
465     if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
466                          CBucket.Elements[j - 1].Offset) == FirstOffset) {
467       if (!SawChainSeparater)
468         FirstOffsetReusedCountInFirstChain++;
469       FirstOffsetReusedCount++;
470     } else
471       // For now, if we meet any offset which is not FirstOffset, we assume we
472       // find a new Chain.
473       // This makes us miss some opportunities.
474       // For example, we can common:
475       //
476       // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
477       //
478       // as two chains:
479       // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
480       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
481       //
482       // But we fail to common:
483       //
484       // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
485       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
486 
487       SawChainSeparater = true;
488   }
489 
490   // FirstOffset is not reused, skip this bucket.
491   if (FirstOffsetReusedCount == 1)
492     return false;
493 
494   unsigned ChainNum =
495       FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
496 
497   // All elements are increased by FirstOffset.
498   // The number of chains should be sqrt(EleNum).
499   if (!SawChainSeparater)
500     ChainNum = (unsigned)sqrt((double)EleNum);
501 
502   CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
503 
504   // If this is not a perfect chain(eg: not all elements can be put inside
505   // commoning chains.), skip now.
506   if (CBucket.ChainSize * ChainNum != EleNum)
507     return false;
508 
509   if (SawChainSeparater) {
510     // Check that the offset seqs are the same for all chains.
511     for (unsigned i = 1; i < CBucket.ChainSize; i++)
512       for (unsigned j = 1; j < ChainNum; j++)
513         if (CBucket.Elements[i].Offset !=
514             SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
515                              CBucket.Elements[j * CBucket.ChainSize].Offset))
516           return false;
517   }
518 
519   for (unsigned i = 0; i < ChainNum; i++)
520     CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
521 
522   LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
523 
524   return true;
525 }
526 
527 bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
528                                           SmallVector<Bucket, 16> &Buckets) {
529   bool MadeChange = false;
530 
531   if (Buckets.empty())
532     return MadeChange;
533 
534   SmallSet<BasicBlock *, 16> BBChanged;
535 
536   for (auto &Bucket : Buckets) {
537     if (prepareBasesForCommoningChains(Bucket))
538       MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
539   }
540 
541   if (MadeChange)
542     for (auto *BB : BBChanged)
543       DeleteDeadPHIs(BB);
544   return MadeChange;
545 }
546 
547 bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
548     Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
549   bool MadeChange = false;
550 
551   assert(Bucket.Elements.size() ==
552              Bucket.ChainBases.size() * Bucket.ChainSize &&
553          "invalid bucket for chain commoning!\n");
554   SmallPtrSet<Value *, 16> DeletedPtrs;
555 
556   BasicBlock *Header = L->getHeader();
557   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
558 
559   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
560                      "loopprepare-chaincommon");
561 
562   for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
563     unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
564     const SCEV *BaseSCEV =
565         ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
566                                   Bucket.Elements[BaseElemIdx].Offset)
567                  : Bucket.BaseSCEV;
568     const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
569 
570     // Make sure the base is able to expand.
571     if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
572       return MadeChange;
573 
574     assert(BasePtrSCEV->isAffine() &&
575            "Invalid SCEV type for the base ptr for a candidate chain!\n");
576 
577     std::pair<Instruction *, Instruction *> Base = rewriteForBase(
578         L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
579         false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs);
580 
581     if (!Base.first || !Base.second)
582       return MadeChange;
583 
584     // Keep track of the replacement pointer values we've inserted so that we
585     // don't generate more pointer values than necessary.
586     SmallPtrSet<Value *, 16> NewPtrs;
587     NewPtrs.insert(Base.first);
588 
589     for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
590          ++Idx) {
591       BucketElement &I = Bucket.Elements[Idx];
592       Value *Ptr = getPointerOperandAndType(I.Instr);
593       assert(Ptr && "No pointer operand");
594       if (NewPtrs.count(Ptr))
595         continue;
596 
597       const SCEV *OffsetSCEV =
598           BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
599                                          Bucket.Elements[BaseElemIdx].Offset)
600                       : Bucket.Elements[Idx].Offset;
601 
602       // Make sure offset is able to expand. Only need to check one time as the
603       // offsets are reused between different chains.
604       if (!BaseElemIdx)
605         if (!SCEVE.isSafeToExpand(OffsetSCEV))
606           return false;
607 
608       Value *OffsetValue = SCEVE.expandCodeFor(
609           OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
610 
611       Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
612                                                     OffsetValue, DeletedPtrs);
613 
614       assert(NewPtr && "Wrong rewrite!\n");
615       NewPtrs.insert(NewPtr);
616     }
617 
618     ++ChainCommoningRewritten;
619   }
620 
621   // Clear the rewriter cache, because values that are in the rewriter's cache
622   // can be deleted below, causing the AssertingVH in the cache to trigger.
623   SCEVE.clear();
624 
625   for (auto *Ptr : DeletedPtrs) {
626     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
627       BBChanged.insert(IDel->getParent());
628     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
629   }
630 
631   MadeChange = true;
632   return MadeChange;
633 }
634 
635 // Rewrite the new base according to BasePtrSCEV.
636 // bb.loop.preheader:
637 //   %newstart = ...
638 // bb.loop.body:
639 //   %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
640 //   ...
641 //   %add = getelementptr %phinode, %inc
642 //
643 // First returned instruciton is %phinode (or a type cast to %phinode), caller
644 // needs this value to rewrite other load/stores in the same chain.
645 // Second returned instruction is %add, caller needs this value to rewrite other
646 // load/stores in the same chain.
647 std::pair<Instruction *, Instruction *>
648 PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
649                                      Instruction *BaseMemI, bool CanPreInc,
650                                      PrepForm Form, SCEVExpander &SCEVE,
651                                      SmallPtrSet<Value *, 16> &DeletedPtrs) {
652 
653   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
654 
655   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
656 
657   Value *BasePtr = getPointerOperandAndType(BaseMemI);
658   assert(BasePtr && "No pointer operand");
659 
660   Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
661   Type *I8PtrTy =
662       Type::getInt8PtrTy(BaseMemI->getParent()->getContext(),
663                          BasePtr->getType()->getPointerAddressSpace());
664 
665   bool IsConstantInc = false;
666   const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
667   Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
668 
669   const SCEVConstant *BasePtrIncConstantSCEV =
670       dyn_cast<SCEVConstant>(BasePtrIncSCEV);
671   if (BasePtrIncConstantSCEV)
672     IsConstantInc = true;
673 
674   // No valid representation for the increment.
675   if (!IncNode) {
676     LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
677     return std::make_pair(nullptr, nullptr);
678   }
679 
680   if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) {
681     LLVM_DEBUG(
682         dbgs()
683         << "Update form prepare for non-const increment is not enabled!\n");
684     return std::make_pair(nullptr, nullptr);
685   }
686 
687   const SCEV *BasePtrStartSCEV = nullptr;
688   if (CanPreInc) {
689     assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
690            "Increment is not loop invariant!\n");
691     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
692                                         IsConstantInc ? BasePtrIncConstantSCEV
693                                                       : BasePtrIncSCEV);
694   } else
695     BasePtrStartSCEV = BasePtrSCEV->getStart();
696 
697   if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
698     LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
699     return std::make_pair(nullptr, nullptr);
700   }
701 
702   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
703 
704   BasicBlock *Header = L->getHeader();
705   unsigned HeaderLoopPredCount = pred_size(Header);
706   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
707 
708   PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
709                                     getInstrName(BaseMemI, PHINodeNameSuffix),
710                                     Header->getFirstNonPHI());
711 
712   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
713                                             LoopPredecessor->getTerminator());
714 
715   // Note that LoopPredecessor might occur in the predecessor list multiple
716   // times, and we need to add it the right number of times.
717   for (auto PI : predecessors(Header)) {
718     if (PI != LoopPredecessor)
719       continue;
720 
721     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
722   }
723 
724   Instruction *PtrInc = nullptr;
725   Instruction *NewBasePtr = nullptr;
726   if (CanPreInc) {
727     Instruction *InsPoint = &*Header->getFirstInsertionPt();
728     PtrInc = GetElementPtrInst::Create(
729         I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
730         InsPoint);
731     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
732     for (auto PI : predecessors(Header)) {
733       if (PI == LoopPredecessor)
734         continue;
735 
736       NewPHI->addIncoming(PtrInc, PI);
737     }
738     if (PtrInc->getType() != BasePtr->getType())
739       NewBasePtr =
740           new BitCastInst(PtrInc, BasePtr->getType(),
741                           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
742     else
743       NewBasePtr = PtrInc;
744   } else {
745     // Note that LoopPredecessor might occur in the predecessor list multiple
746     // times, and we need to make sure no more incoming value for them in PHI.
747     for (auto PI : predecessors(Header)) {
748       if (PI == LoopPredecessor)
749         continue;
750 
751       // For the latch predecessor, we need to insert a GEP just before the
752       // terminator to increase the address.
753       BasicBlock *BB = PI;
754       Instruction *InsPoint = BB->getTerminator();
755       PtrInc = GetElementPtrInst::Create(
756           I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
757           InsPoint);
758       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
759 
760       NewPHI->addIncoming(PtrInc, PI);
761     }
762     PtrInc = NewPHI;
763     if (NewPHI->getType() != BasePtr->getType())
764       NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
765                                    getInstrName(NewPHI, CastNodeNameSuffix),
766                                    &*Header->getFirstInsertionPt());
767     else
768       NewBasePtr = NewPHI;
769   }
770 
771   BasePtr->replaceAllUsesWith(NewBasePtr);
772 
773   DeletedPtrs.insert(BasePtr);
774 
775   return std::make_pair(NewBasePtr, PtrInc);
776 }
777 
778 Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
779     std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
780     Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
781   Instruction *NewBasePtr = Base.first;
782   Instruction *PtrInc = Base.second;
783   assert((NewBasePtr && PtrInc) && "base does not exist!\n");
784 
785   Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
786 
787   Value *Ptr = getPointerOperandAndType(Element.Instr);
788   assert(Ptr && "No pointer operand");
789 
790   Instruction *RealNewPtr;
791   if (!Element.Offset ||
792       (isa<SCEVConstant>(Element.Offset) &&
793        cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
794     RealNewPtr = NewBasePtr;
795   } else {
796     Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
797     if (PtrIP && isa<Instruction>(NewBasePtr) &&
798         cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
799       PtrIP = nullptr;
800     else if (PtrIP && isa<PHINode>(PtrIP))
801       PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
802     else if (!PtrIP)
803       PtrIP = Element.Instr;
804 
805     assert(OffToBase && "There should be an offset for non base element!\n");
806     GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
807         I8Ty, PtrInc, OffToBase,
808         getInstrName(Element.Instr, GEPNodeOffNameSuffix), PtrIP);
809     if (!PtrIP)
810       NewPtr->insertAfter(cast<Instruction>(PtrInc));
811     NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
812     RealNewPtr = NewPtr;
813   }
814 
815   Instruction *ReplNewPtr;
816   if (Ptr->getType() != RealNewPtr->getType()) {
817     ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
818                                  getInstrName(Ptr, CastNodeNameSuffix));
819     ReplNewPtr->insertAfter(RealNewPtr);
820   } else
821     ReplNewPtr = RealNewPtr;
822 
823   Ptr->replaceAllUsesWith(ReplNewPtr);
824   DeletedPtrs.insert(Ptr);
825 
826   return ReplNewPtr;
827 }
828 
829 void PPCLoopInstrFormPrep::addOneCandidate(
830     Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
831     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
832   assert((MemI && getPointerOperandAndType(MemI)) &&
833          "Candidate should be a memory instruction.");
834   assert(LSCEV && "Invalid SCEV for Ptr value.");
835 
836   bool FoundBucket = false;
837   for (auto &B : Buckets) {
838     if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
839         cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
840       continue;
841     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
842     if (isValidDiff(Diff)) {
843       B.Elements.push_back(BucketElement(Diff, MemI));
844       FoundBucket = true;
845       break;
846     }
847   }
848 
849   if (!FoundBucket) {
850     if (Buckets.size() == MaxCandidateNum) {
851       LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
852                         << MaxCandidateNum << "\n");
853       return;
854     }
855     Buckets.push_back(Bucket(LSCEV, MemI));
856   }
857 }
858 
859 SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
860     Loop *L,
861     std::function<bool(const Instruction *, Value *, const Type *)>
862         isValidCandidate,
863     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
864   SmallVector<Bucket, 16> Buckets;
865 
866   for (const auto &BB : L->blocks())
867     for (auto &J : *BB) {
868       Value *PtrValue = nullptr;
869       Type *PointerElementType = nullptr;
870       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
871 
872       if (!PtrValue)
873         continue;
874 
875       if (PtrValue->getType()->getPointerAddressSpace())
876         continue;
877 
878       if (L->isLoopInvariant(PtrValue))
879         continue;
880 
881       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
882       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
883       if (!LARSCEV || LARSCEV->getLoop() != L)
884         continue;
885 
886       // Mark that we have candidates for preparing.
887       HasCandidateForPrepare = true;
888 
889       if (isValidCandidate(&J, PtrValue, PointerElementType))
890         addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
891     }
892   return Buckets;
893 }
894 
895 bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
896                                                        PrepForm Form) {
897   // RemainderOffsetInfo details:
898   // key:            value of (Offset urem DispConstraint). For DSForm, it can
899   //                 be [0, 4).
900   // first of pair:  the index of first BucketElement whose remainder is equal
901   //                 to key. For key 0, this value must be 0.
902   // second of pair: number of load/stores with the same remainder.
903   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
904 
905   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
906     if (!BucketChain.Elements[j].Offset)
907       RemainderOffsetInfo[0] = std::make_pair(0, 1);
908     else {
909       unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
910                                ->getAPInt()
911                                .urem(Form);
912       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
913         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
914       else
915         RemainderOffsetInfo[Remainder].second++;
916     }
917   }
918   // Currently we choose the most profitable base as the one which has the max
919   // number of load/store with same remainder.
920   // FIXME: adjust the base selection strategy according to load/store offset
921   // distribution.
922   // For example, if we have one candidate chain for DS form preparation, which
923   // contains following load/stores with different remainders:
924   // 1: 10 load/store whose remainder is 1;
925   // 2: 9 load/store whose remainder is 2;
926   // 3: 1 for remainder 3 and 0 for remainder 0;
927   // Now we will choose the first load/store whose remainder is 1 as base and
928   // adjust all other load/stores according to new base, so we will get 10 DS
929   // form and 10 X form.
930   // But we should be more clever, for this case we could use two bases, one for
931   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
932   // 1 X form.
933   unsigned MaxCountRemainder = 0;
934   for (unsigned j = 0; j < (unsigned)Form; j++)
935     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
936         RemainderOffsetInfo[j].second >
937             RemainderOffsetInfo[MaxCountRemainder].second)
938       MaxCountRemainder = j;
939 
940   // Abort when there are too few insts with common base.
941   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
942     return false;
943 
944   // If the first value is most profitable, no needed to adjust BucketChain
945   // elements as they are substracted the first value when collecting.
946   if (MaxCountRemainder == 0)
947     return true;
948 
949   // Adjust load/store to the new chosen base.
950   const SCEV *Offset =
951       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
952   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
953   for (auto &E : BucketChain.Elements) {
954     if (E.Offset)
955       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
956     else
957       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
958   }
959 
960   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
961             BucketChain.Elements[0]);
962   return true;
963 }
964 
965 // FIXME: implement a more clever base choosing policy.
966 // Currently we always choose an exist load/store offset. This maybe lead to
967 // suboptimal code sequences. For example, for one DS chain with offsets
968 // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
969 // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
970 // multipler of 4, it cannot be represented by sint16.
971 bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
972   // We have a choice now of which instruction's memory operand we use as the
973   // base for the generated PHI. Always picking the first instruction in each
974   // bucket does not work well, specifically because that instruction might
975   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
976   // the choice is somewhat arbitrary, because the backend will happily
977   // generate direct offsets from both the pre-incremented and
978   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
979   // instruction in each bucket, and adjust the recurrence and other offsets
980   // accordingly.
981   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
982     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
983       if (II->getIntrinsicID() == Intrinsic::prefetch)
984         continue;
985 
986     // If we'd otherwise pick the first element anyway, there's nothing to do.
987     if (j == 0)
988       break;
989 
990     // If our chosen element has no offset from the base pointer, there's
991     // nothing to do.
992     if (!BucketChain.Elements[j].Offset ||
993         cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
994       break;
995 
996     const SCEV *Offset = BucketChain.Elements[j].Offset;
997     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
998     for (auto &E : BucketChain.Elements) {
999       if (E.Offset)
1000         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
1001       else
1002         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
1003     }
1004 
1005     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
1006     break;
1007   }
1008   return true;
1009 }
1010 
1011 bool PPCLoopInstrFormPrep::rewriteLoadStores(
1012     Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
1013     PrepForm Form) {
1014   bool MadeChange = false;
1015 
1016   const SCEVAddRecExpr *BasePtrSCEV =
1017       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
1018   if (!BasePtrSCEV->isAffine())
1019     return MadeChange;
1020 
1021   BasicBlock *Header = L->getHeader();
1022   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
1023                      "loopprepare-formrewrite");
1024   if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
1025     return MadeChange;
1026 
1027   SmallPtrSet<Value *, 16> DeletedPtrs;
1028 
1029   // For some DS form load/store instructions, it can also be an update form,
1030   // if the stride is constant and is a multipler of 4. Use update form if
1031   // prefer it.
1032   bool CanPreInc = (Form == UpdateForm ||
1033                     ((Form == DSForm) &&
1034                      isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
1035                      !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
1036                           ->getAPInt()
1037                           .urem(4) &&
1038                      PreferUpdateForm));
1039 
1040   std::pair<Instruction *, Instruction *> Base =
1041       rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
1042                      CanPreInc, Form, SCEVE, DeletedPtrs);
1043 
1044   if (!Base.first || !Base.second)
1045     return MadeChange;
1046 
1047   // Keep track of the replacement pointer values we've inserted so that we
1048   // don't generate more pointer values than necessary.
1049   SmallPtrSet<Value *, 16> NewPtrs;
1050   NewPtrs.insert(Base.first);
1051 
1052   for (auto I = std::next(BucketChain.Elements.begin()),
1053        IE = BucketChain.Elements.end(); I != IE; ++I) {
1054     Value *Ptr = getPointerOperandAndType(I->Instr);
1055     assert(Ptr && "No pointer operand");
1056     if (NewPtrs.count(Ptr))
1057       continue;
1058 
1059     Instruction *NewPtr = rewriteForBucketElement(
1060         Base, *I,
1061         I->Offset ? cast<SCEVConstant>(I->Offset)->getValue() : nullptr,
1062         DeletedPtrs);
1063     assert(NewPtr && "wrong rewrite!\n");
1064     NewPtrs.insert(NewPtr);
1065   }
1066 
1067   // Clear the rewriter cache, because values that are in the rewriter's cache
1068   // can be deleted below, causing the AssertingVH in the cache to trigger.
1069   SCEVE.clear();
1070 
1071   for (auto *Ptr : DeletedPtrs) {
1072     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
1073       BBChanged.insert(IDel->getParent());
1074     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
1075   }
1076 
1077   MadeChange = true;
1078 
1079   SuccPrepCount++;
1080 
1081   if (Form == DSForm && !CanPreInc)
1082     DSFormChainRewritten++;
1083   else if (Form == DQForm)
1084     DQFormChainRewritten++;
1085   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
1086     UpdFormChainRewritten++;
1087 
1088   return MadeChange;
1089 }
1090 
1091 bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
1092                                        SmallVector<Bucket, 16> &Buckets) {
1093   bool MadeChange = false;
1094   if (Buckets.empty())
1095     return MadeChange;
1096   SmallSet<BasicBlock *, 16> BBChanged;
1097   for (auto &Bucket : Buckets)
1098     // The base address of each bucket is transformed into a phi and the others
1099     // are rewritten based on new base.
1100     if (prepareBaseForUpdateFormChain(Bucket))
1101       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
1102 
1103   if (MadeChange)
1104     for (auto *BB : BBChanged)
1105       DeleteDeadPHIs(BB);
1106   return MadeChange;
1107 }
1108 
1109 bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L,
1110                                         SmallVector<Bucket, 16> &Buckets,
1111                                         PrepForm Form) {
1112   bool MadeChange = false;
1113 
1114   if (Buckets.empty())
1115     return MadeChange;
1116 
1117   SmallSet<BasicBlock *, 16> BBChanged;
1118   for (auto &Bucket : Buckets) {
1119     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
1120       continue;
1121     if (prepareBaseForDispFormChain(Bucket, Form))
1122       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
1123   }
1124 
1125   if (MadeChange)
1126     for (auto *BB : BBChanged)
1127       DeleteDeadPHIs(BB);
1128   return MadeChange;
1129 }
1130 
1131 // Find the loop invariant increment node for SCEV BasePtrIncSCEV.
1132 // bb.loop.preheader:
1133 //   %start = ...
1134 // bb.loop.body:
1135 //   %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ]
1136 //   ...
1137 //   %add = add %phinode, %inc  ; %inc is what we want to get.
1138 //
1139 Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
1140                                            const SCEV *BasePtrIncSCEV) {
1141   // If the increment is a constant, no definition is needed.
1142   // Return the value directly.
1143   if (isa<SCEVConstant>(BasePtrIncSCEV))
1144     return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
1145 
1146   if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
1147     return nullptr;
1148 
1149   BasicBlock *BB = MemI->getParent();
1150   if (!BB)
1151     return nullptr;
1152 
1153   BasicBlock *LatchBB = L->getLoopLatch();
1154 
1155   if (!LatchBB)
1156     return nullptr;
1157 
1158   // Run through the PHIs and check their operands to find valid representation
1159   // for the increment SCEV.
1160   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1161   for (auto &CurrentPHI : PHIIter) {
1162     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1163     if (!CurrentPHINode)
1164       continue;
1165 
1166     if (!SE->isSCEVable(CurrentPHINode->getType()))
1167       continue;
1168 
1169     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1170 
1171     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1172     if (!PHIBasePtrSCEV)
1173       continue;
1174 
1175     const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
1176 
1177     if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
1178       continue;
1179 
1180     // Get the incoming value from the loop latch and check if the value has
1181     // the add form with the required increment.
1182     if (Instruction *I = dyn_cast<Instruction>(
1183             CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1184       Value *StrippedBaseI = I;
1185       while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1186         StrippedBaseI = BC->getOperand(0);
1187 
1188       Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1189       if (!StrippedI)
1190         continue;
1191 
1192       // LSR pass may add a getelementptr instruction to do the loop increment,
1193       // also search in that getelementptr instruction.
1194       if (StrippedI->getOpcode() == Instruction::Add ||
1195           (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1196            StrippedI->getNumOperands() == 2)) {
1197         if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1198           return StrippedI->getOperand(0);
1199         if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1200           return StrippedI->getOperand(1);
1201       }
1202     }
1203   }
1204   return nullptr;
1205 }
1206 
1207 // In order to prepare for the preferred instruction form, a PHI is added.
1208 // This function will check to see if that PHI already exists and will return
1209 // true if it found an existing PHI with the matched start and increment as the
1210 // one we wanted to create.
1211 bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
1212                                            const SCEV *BasePtrStartSCEV,
1213                                            const SCEV *BasePtrIncSCEV,
1214                                            PrepForm Form) {
1215   BasicBlock *BB = MemI->getParent();
1216   if (!BB)
1217     return false;
1218 
1219   BasicBlock *PredBB = L->getLoopPredecessor();
1220   BasicBlock *LatchBB = L->getLoopLatch();
1221 
1222   if (!PredBB || !LatchBB)
1223     return false;
1224 
1225   // Run through the PHIs and see if we have some that looks like a preparation
1226   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1227   for (auto & CurrentPHI : PHIIter) {
1228     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1229     if (!CurrentPHINode)
1230       continue;
1231 
1232     if (!SE->isSCEVable(CurrentPHINode->getType()))
1233       continue;
1234 
1235     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1236 
1237     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1238     if (!PHIBasePtrSCEV)
1239       continue;
1240 
1241     const SCEVConstant *PHIBasePtrIncSCEV =
1242       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
1243     if (!PHIBasePtrIncSCEV)
1244       continue;
1245 
1246     if (CurrentPHINode->getNumIncomingValues() == 2) {
1247       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
1248            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
1249           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
1250            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
1251         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
1252           // The existing PHI (CurrentPHINode) has the same start and increment
1253           // as the PHI that we wanted to create.
1254           if ((Form == UpdateForm || Form == ChainCommoning ) &&
1255               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
1256             ++PHINodeAlreadyExistsUpdate;
1257             return true;
1258           }
1259           if (Form == DSForm || Form == DQForm) {
1260             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
1261                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
1262             if (Diff && !Diff->getAPInt().urem(Form)) {
1263               if (Form == DSForm)
1264                 ++PHINodeAlreadyExistsDS;
1265               else
1266                 ++PHINodeAlreadyExistsDQ;
1267               return true;
1268             }
1269           }
1270         }
1271       }
1272     }
1273   }
1274   return false;
1275 }
1276 
1277 bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
1278   bool MadeChange = false;
1279 
1280   // Only prep. the inner-most loop
1281   if (!L->isInnermost())
1282     return MadeChange;
1283 
1284   // Return if already done enough preparation.
1285   if (SuccPrepCount >= MaxVarsPrep)
1286     return MadeChange;
1287 
1288   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
1289 
1290   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
1291   // If there is no loop predecessor, or the loop predecessor's terminator
1292   // returns a value (which might contribute to determining the loop's
1293   // iteration space), insert a new preheader for the loop.
1294   if (!LoopPredecessor ||
1295       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
1296     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
1297     if (LoopPredecessor)
1298       MadeChange = true;
1299   }
1300   if (!LoopPredecessor) {
1301     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
1302     return MadeChange;
1303   }
1304   // Check if a load/store has update form. This lambda is used by function
1305   // collectCandidates which can collect candidates for types defined by lambda.
1306   auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1307                                    const Type *PointerElementType) {
1308     assert((PtrValue && I) && "Invalid parameter!");
1309     // There are no update forms for Altivec vector load/stores.
1310     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
1311       return false;
1312     // There are no update forms for P10 lxvp/stxvp intrinsic.
1313     auto *II = dyn_cast<IntrinsicInst>(I);
1314     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1315                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
1316       return false;
1317     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
1318     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
1319     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
1320     // useless and possible to break some original well-form addressing mode
1321     // to make this pre-inc prep for it.
1322     if (PointerElementType->isIntegerTy(64)) {
1323       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
1324       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
1325       if (!LARSCEV || LARSCEV->getLoop() != L)
1326         return false;
1327       if (const SCEVConstant *StepConst =
1328               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
1329         const APInt &ConstInt = StepConst->getValue()->getValue();
1330         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
1331           return false;
1332       }
1333     }
1334     return true;
1335   };
1336 
1337   // Check if a load/store has DS form.
1338   auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1339                               const Type *PointerElementType) {
1340     assert((PtrValue && I) && "Invalid parameter!");
1341     if (isa<IntrinsicInst>(I))
1342       return false;
1343     return (PointerElementType->isIntegerTy(64)) ||
1344            (PointerElementType->isFloatTy()) ||
1345            (PointerElementType->isDoubleTy()) ||
1346            (PointerElementType->isIntegerTy(32) &&
1347             llvm::any_of(I->users(),
1348                          [](const User *U) { return isa<SExtInst>(U); }));
1349   };
1350 
1351   // Check if a load/store has DQ form.
1352   auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1353                                const Type *PointerElementType) {
1354     assert((PtrValue && I) && "Invalid parameter!");
1355     // Check if it is a P10 lxvp/stxvp intrinsic.
1356     auto *II = dyn_cast<IntrinsicInst>(I);
1357     if (II)
1358       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1359              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
1360     // Check if it is a P9 vector load/store.
1361     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
1362   };
1363 
1364   // Check if a load/store is candidate for chain commoning.
1365   // If the SCEV is only with one ptr operand in its start, we can use that
1366   // start as a chain separator. Mark this load/store as a candidate.
1367   auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
1368                                        const Type *PointerElementType) {
1369     const SCEVAddRecExpr *ARSCEV =
1370         cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
1371     if (!ARSCEV)
1372       return false;
1373 
1374     if (!ARSCEV->isAffine())
1375       return false;
1376 
1377     const SCEV *Start = ARSCEV->getStart();
1378 
1379     // A single pointer. We can treat it as offset 0.
1380     if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
1381       return true;
1382 
1383     const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
1384 
1385     // We need a SCEVAddExpr to include both base and offset.
1386     if (!ASCEV)
1387       return false;
1388 
1389     // Make sure there is only one pointer operand(base) and all other operands
1390     // are integer type.
1391     bool SawPointer = false;
1392     for (const SCEV *Op : ASCEV->operands()) {
1393       if (Op->getType()->isPointerTy()) {
1394         if (SawPointer)
1395           return false;
1396         SawPointer = true;
1397       } else if (!Op->getType()->isIntegerTy())
1398         return false;
1399     }
1400 
1401     return SawPointer;
1402   };
1403 
1404   // Check if the diff is a constant type. This is used for update/DS/DQ form
1405   // preparation.
1406   auto isValidConstantDiff = [](const SCEV *Diff) {
1407     return dyn_cast<SCEVConstant>(Diff) != nullptr;
1408   };
1409 
1410   // Make sure the diff between the base and new candidate is required type.
1411   // This is used for chain commoning preparation.
1412   auto isValidChainCommoningDiff = [](const SCEV *Diff) {
1413     assert(Diff && "Invalid Diff!\n");
1414 
1415     // Don't mess up previous dform prepare.
1416     if (isa<SCEVConstant>(Diff))
1417       return false;
1418 
1419     // A single integer type offset.
1420     if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
1421       return true;
1422 
1423     const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
1424     if (!ADiff)
1425       return false;
1426 
1427     for (const SCEV *Op : ADiff->operands())
1428       if (!Op->getType()->isIntegerTy())
1429         return false;
1430 
1431     return true;
1432   };
1433 
1434   HasCandidateForPrepare = false;
1435 
1436   LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
1437   // Collect buckets of comparable addresses used by loads and stores for update
1438   // form.
1439   SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
1440       L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
1441 
1442   // Prepare for update form.
1443   if (!UpdateFormBuckets.empty())
1444     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
1445   else if (!HasCandidateForPrepare) {
1446     LLVM_DEBUG(
1447         dbgs()
1448         << "No prepare candidates found, stop praparation for current loop!\n");
1449     // If no candidate for preparing, return early.
1450     return MadeChange;
1451   }
1452 
1453   LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
1454   // Collect buckets of comparable addresses used by loads and stores for DS
1455   // form.
1456   SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
1457       L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
1458 
1459   // Prepare for DS form.
1460   if (!DSFormBuckets.empty())
1461     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
1462 
1463   LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
1464   // Collect buckets of comparable addresses used by loads and stores for DQ
1465   // form.
1466   SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
1467       L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
1468 
1469   // Prepare for DQ form.
1470   if (!DQFormBuckets.empty())
1471     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
1472 
1473   // Collect buckets of comparable addresses used by loads and stores for chain
1474   // commoning. With chain commoning, we reuse offsets between the chains, so
1475   // the register pressure will be reduced.
1476   if (!EnableChainCommoning) {
1477     LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
1478     return MadeChange;
1479   }
1480 
1481   LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
1482   SmallVector<Bucket, 16> Buckets =
1483       collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
1484                         MaxVarsChainCommon);
1485 
1486   // Prepare for chain commoning.
1487   if (!Buckets.empty())
1488     MadeChange |= chainCommoning(L, Buckets);
1489 
1490   return MadeChange;
1491 }
1492