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