xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
1480093f4SDimitry Andric //===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===//
2480093f4SDimitry Andric //
3480093f4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4480093f4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5480093f4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6480093f4SDimitry Andric //
7480093f4SDimitry Andric //===----------------------------------------------------------------------===//
8480093f4SDimitry Andric //
9480093f4SDimitry Andric // This file implements a pass to prepare loops for ppc preferred addressing
10480093f4SDimitry Andric // modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with
11480093f4SDimitry Andric // update)
12480093f4SDimitry Andric // Additional PHIs are created for loop induction variables used by load/store
13480093f4SDimitry Andric // instructions so that preferred addressing modes can be used.
14480093f4SDimitry Andric //
15480093f4SDimitry Andric // 1: DS/DQ form preparation, prepare the load/store instructions so that they
16480093f4SDimitry Andric //    can satisfy the DS/DQ form displacement requirements.
17480093f4SDimitry Andric //    Generically, this means transforming loops like this:
18480093f4SDimitry Andric //    for (int i = 0; i < n; ++i) {
19480093f4SDimitry Andric //      unsigned long x1 = *(unsigned long *)(p + i + 5);
20480093f4SDimitry Andric //      unsigned long x2 = *(unsigned long *)(p + i + 9);
21480093f4SDimitry Andric //    }
22480093f4SDimitry Andric //
23480093f4SDimitry Andric //    to look like this:
24480093f4SDimitry Andric //
25480093f4SDimitry Andric //    unsigned NewP = p + 5;
26480093f4SDimitry Andric //    for (int i = 0; i < n; ++i) {
27480093f4SDimitry Andric //      unsigned long x1 = *(unsigned long *)(i + NewP);
28480093f4SDimitry Andric //      unsigned long x2 = *(unsigned long *)(i + NewP + 4);
29480093f4SDimitry Andric //    }
30480093f4SDimitry Andric //
31480093f4SDimitry Andric // 2: D/DS form with update preparation, prepare the load/store instructions so
32480093f4SDimitry Andric //    that we can use update form to do pre-increment.
33480093f4SDimitry Andric //    Generically, this means transforming loops like this:
34480093f4SDimitry Andric //    for (int i = 0; i < n; ++i)
35480093f4SDimitry Andric //      array[i] = c;
36480093f4SDimitry Andric //
37480093f4SDimitry Andric //    to look like this:
38480093f4SDimitry Andric //
39480093f4SDimitry Andric //    T *p = array[-1];
40480093f4SDimitry Andric //    for (int i = 0; i < n; ++i)
41480093f4SDimitry Andric //      *++p = c;
42349cc55cSDimitry Andric //
43349cc55cSDimitry Andric // 3: common multiple chains for the load/stores with same offsets in the loop,
44349cc55cSDimitry Andric //    so that we can reuse the offsets and reduce the register pressure in the
45349cc55cSDimitry Andric //    loop. This transformation can also increase the loop ILP as now each chain
46349cc55cSDimitry Andric //    uses its own loop induction add/addi. But this will increase the number of
47349cc55cSDimitry Andric //    add/addi in the loop.
48349cc55cSDimitry Andric //
49349cc55cSDimitry Andric //    Generically, this means transforming loops like this:
50349cc55cSDimitry Andric //
51349cc55cSDimitry Andric //    char *p;
52349cc55cSDimitry Andric //    A1 = p + base1
53349cc55cSDimitry Andric //    A2 = p + base1 + offset
54349cc55cSDimitry Andric //    B1 = p + base2
55349cc55cSDimitry Andric //    B2 = p + base2 + offset
56349cc55cSDimitry Andric //
57349cc55cSDimitry Andric //    for (int i = 0; i < n; i++)
58349cc55cSDimitry Andric //      unsigned long x1 = *(unsigned long *)(A1 + i);
59349cc55cSDimitry Andric //      unsigned long x2 = *(unsigned long *)(A2 + i)
60349cc55cSDimitry Andric //      unsigned long x3 = *(unsigned long *)(B1 + i);
61349cc55cSDimitry Andric //      unsigned long x4 = *(unsigned long *)(B2 + i);
62349cc55cSDimitry Andric //    }
63349cc55cSDimitry Andric //
64349cc55cSDimitry Andric //    to look like this:
65349cc55cSDimitry Andric //
66349cc55cSDimitry Andric //    A1_new = p + base1 // chain 1
67349cc55cSDimitry Andric //    B1_new = p + base2 // chain 2, now inside the loop, common offset is
68349cc55cSDimitry Andric //                       // reused.
69349cc55cSDimitry Andric //
70349cc55cSDimitry Andric //    for (long long i = 0; i < n; i+=count) {
71349cc55cSDimitry Andric //      unsigned long x1 = *(unsigned long *)(A1_new + i);
72349cc55cSDimitry Andric //      unsigned long x2 = *(unsigned long *)((A1_new + i) + offset);
73349cc55cSDimitry Andric //      unsigned long x3 = *(unsigned long *)(B1_new + i);
74349cc55cSDimitry Andric //      unsigned long x4 = *(unsigned long *)((B1_new + i) + offset);
75349cc55cSDimitry Andric //    }
76480093f4SDimitry Andric //===----------------------------------------------------------------------===//
77480093f4SDimitry Andric 
78480093f4SDimitry Andric #include "PPC.h"
79480093f4SDimitry Andric #include "PPCSubtarget.h"
80480093f4SDimitry Andric #include "PPCTargetMachine.h"
81480093f4SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
82480093f4SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
83480093f4SDimitry Andric #include "llvm/ADT/SmallSet.h"
84480093f4SDimitry Andric #include "llvm/ADT/SmallVector.h"
85480093f4SDimitry Andric #include "llvm/ADT/Statistic.h"
86480093f4SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
87480093f4SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
88480093f4SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
89480093f4SDimitry Andric #include "llvm/IR/BasicBlock.h"
90480093f4SDimitry Andric #include "llvm/IR/CFG.h"
91480093f4SDimitry Andric #include "llvm/IR/Dominators.h"
92480093f4SDimitry Andric #include "llvm/IR/Instruction.h"
93480093f4SDimitry Andric #include "llvm/IR/Instructions.h"
94480093f4SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
95e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsPowerPC.h"
96480093f4SDimitry Andric #include "llvm/IR/Module.h"
97480093f4SDimitry Andric #include "llvm/IR/Type.h"
98480093f4SDimitry Andric #include "llvm/IR/Value.h"
99480093f4SDimitry Andric #include "llvm/InitializePasses.h"
100480093f4SDimitry Andric #include "llvm/Pass.h"
101480093f4SDimitry Andric #include "llvm/Support/Casting.h"
102480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
103480093f4SDimitry Andric #include "llvm/Support/Debug.h"
104480093f4SDimitry Andric #include "llvm/Transforms/Scalar.h"
105480093f4SDimitry Andric #include "llvm/Transforms/Utils.h"
106480093f4SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
107480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
108480093f4SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
1095ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
110480093f4SDimitry Andric #include <cassert>
111480093f4SDimitry Andric #include <iterator>
112480093f4SDimitry Andric #include <utility>
113480093f4SDimitry Andric 
114fe6060f1SDimitry Andric #define DEBUG_TYPE "ppc-loop-instr-form-prep"
115fe6060f1SDimitry Andric 
116480093f4SDimitry Andric using namespace llvm;
117480093f4SDimitry Andric 
118349cc55cSDimitry Andric static cl::opt<unsigned>
119349cc55cSDimitry Andric     MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
120349cc55cSDimitry Andric                 cl::desc("Potential common base number threshold per function "
121349cc55cSDimitry Andric                          "for PPC loop prep"));
122480093f4SDimitry Andric 
123480093f4SDimitry Andric static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
124480093f4SDimitry Andric                                  cl::init(true), cl::Hidden,
125480093f4SDimitry Andric   cl::desc("prefer update form when ds form is also a update form"));
126480093f4SDimitry Andric 
127349cc55cSDimitry Andric static cl::opt<bool> EnableUpdateFormForNonConstInc(
128349cc55cSDimitry Andric     "ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden,
129349cc55cSDimitry Andric     cl::desc("prepare update form when the load/store increment is a loop "
130349cc55cSDimitry Andric              "invariant non-const value."));
131349cc55cSDimitry Andric 
132349cc55cSDimitry Andric static cl::opt<bool> EnableChainCommoning(
133349cc55cSDimitry Andric     "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
134349cc55cSDimitry Andric     cl::desc("Enable chain commoning in PPC loop prepare pass."));
135349cc55cSDimitry Andric 
136480093f4SDimitry Andric // Sum of following 3 per loop thresholds for all loops can not be larger
137480093f4SDimitry Andric // than MaxVarsPrep.
138e8d8bef9SDimitry Andric // now the thresholds for each kind prep are exterimental values on Power9.
139480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
140480093f4SDimitry Andric                                  cl::Hidden, cl::init(3),
141480093f4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
142480093f4SDimitry Andric            "form"));
143480093f4SDimitry Andric 
144480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
145480093f4SDimitry Andric                                  cl::Hidden, cl::init(3),
146480093f4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
147480093f4SDimitry Andric 
148480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
149e8d8bef9SDimitry Andric                                  cl::Hidden, cl::init(8),
150480093f4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
151480093f4SDimitry Andric 
152349cc55cSDimitry Andric // Commoning chain will reduce the register pressure, so we don't consider about
153349cc55cSDimitry Andric // the PHI nodes number.
154349cc55cSDimitry Andric // But commoning chain will increase the addi/add number in the loop and also
155349cc55cSDimitry Andric // increase loop ILP. Maximum chain number should be same with hardware
156349cc55cSDimitry Andric // IssueWidth, because we won't benefit from ILP if the parallel chains number
157349cc55cSDimitry Andric // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so
158349cc55cSDimitry Andric // there would be 4 buckets at most on P9(IssueWidth is 8).
159349cc55cSDimitry Andric static cl::opt<unsigned> MaxVarsChainCommon(
160349cc55cSDimitry Andric     "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
161349cc55cSDimitry Andric     cl::desc("Bucket number per loop for PPC loop chain common"));
162480093f4SDimitry Andric 
163480093f4SDimitry Andric // If would not be profitable if the common base has only one load/store, ISEL
164480093f4SDimitry Andric // should already be able to choose best load/store form based on offset for
165480093f4SDimitry Andric // single load/store. Set minimal profitable value default to 2 and make it as
166480093f4SDimitry Andric // an option.
167480093f4SDimitry Andric static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
168480093f4SDimitry Andric                                     cl::Hidden, cl::init(2),
169480093f4SDimitry Andric   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
170480093f4SDimitry Andric            "preparation"));
171480093f4SDimitry Andric 
172349cc55cSDimitry Andric static cl::opt<unsigned> ChainCommonPrepMinThreshold(
173349cc55cSDimitry Andric     "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
174349cc55cSDimitry Andric     cl::desc("Minimal common base load/store instructions triggering chain "
175349cc55cSDimitry Andric              "commoning preparation. Must be not smaller than 4"));
176349cc55cSDimitry Andric 
177480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
178480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
179480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
180480093f4SDimitry Andric STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
181480093f4SDimitry Andric STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
182480093f4SDimitry Andric STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
183349cc55cSDimitry Andric STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
184480093f4SDimitry Andric 
185480093f4SDimitry Andric namespace {
186480093f4SDimitry Andric   struct BucketElement {
187349cc55cSDimitry Andric     BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
188480093f4SDimitry Andric     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
189480093f4SDimitry Andric 
190349cc55cSDimitry Andric     const SCEV *Offset;
191480093f4SDimitry Andric     Instruction *Instr;
192480093f4SDimitry Andric   };
193480093f4SDimitry Andric 
194480093f4SDimitry Andric   struct Bucket {
195349cc55cSDimitry Andric     Bucket(const SCEV *B, Instruction *I)
196349cc55cSDimitry Andric         : BaseSCEV(B), Elements(1, BucketElement(I)) {
197349cc55cSDimitry Andric       ChainSize = 0;
198349cc55cSDimitry Andric     }
199480093f4SDimitry Andric 
200349cc55cSDimitry Andric     // The base of the whole bucket.
201480093f4SDimitry Andric     const SCEV *BaseSCEV;
202349cc55cSDimitry Andric 
203349cc55cSDimitry Andric     // All elements in the bucket. In the bucket, the element with the BaseSCEV
204349cc55cSDimitry Andric     // has no offset and all other elements are stored as offsets to the
205349cc55cSDimitry Andric     // BaseSCEV.
206480093f4SDimitry Andric     SmallVector<BucketElement, 16> Elements;
207349cc55cSDimitry Andric 
208349cc55cSDimitry Andric     // The potential chains size. This is used for chain commoning only.
209349cc55cSDimitry Andric     unsigned ChainSize;
210349cc55cSDimitry Andric 
211349cc55cSDimitry Andric     // The base for each potential chain. This is used for chain commoning only.
212349cc55cSDimitry Andric     SmallVector<BucketElement, 16> ChainBases;
213480093f4SDimitry Andric   };
214480093f4SDimitry Andric 
215480093f4SDimitry Andric   // "UpdateForm" is not a real PPC instruction form, it stands for dform
216480093f4SDimitry Andric   // load/store with update like ldu/stdu, or Prefetch intrinsic.
217480093f4SDimitry Andric   // For DS form instructions, their displacements must be multiple of 4.
218480093f4SDimitry Andric   // For DQ form instructions, their displacements must be multiple of 16.
219349cc55cSDimitry Andric   enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
220480093f4SDimitry Andric 
221480093f4SDimitry Andric   class PPCLoopInstrFormPrep : public FunctionPass {
222480093f4SDimitry Andric   public:
223480093f4SDimitry Andric     static char ID; // Pass ID, replacement for typeid
224480093f4SDimitry Andric 
225480093f4SDimitry Andric     PPCLoopInstrFormPrep() : FunctionPass(ID) {
226480093f4SDimitry Andric       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
227480093f4SDimitry Andric     }
228480093f4SDimitry Andric 
229480093f4SDimitry Andric     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
230480093f4SDimitry Andric       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
231480093f4SDimitry Andric     }
232480093f4SDimitry Andric 
233480093f4SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
234480093f4SDimitry Andric       AU.addPreserved<DominatorTreeWrapperPass>();
235480093f4SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
236480093f4SDimitry Andric       AU.addPreserved<LoopInfoWrapperPass>();
237480093f4SDimitry Andric       AU.addRequired<ScalarEvolutionWrapperPass>();
238480093f4SDimitry Andric     }
239480093f4SDimitry Andric 
240480093f4SDimitry Andric     bool runOnFunction(Function &F) override;
241480093f4SDimitry Andric 
242480093f4SDimitry Andric   private:
243480093f4SDimitry Andric     PPCTargetMachine *TM = nullptr;
244480093f4SDimitry Andric     const PPCSubtarget *ST;
245480093f4SDimitry Andric     DominatorTree *DT;
246480093f4SDimitry Andric     LoopInfo *LI;
247480093f4SDimitry Andric     ScalarEvolution *SE;
248480093f4SDimitry Andric     bool PreserveLCSSA;
249349cc55cSDimitry Andric     bool HasCandidateForPrepare;
250480093f4SDimitry Andric 
251480093f4SDimitry Andric     /// Successful preparation number for Update/DS/DQ form in all inner most
252480093f4SDimitry Andric     /// loops. One successful preparation will put one common base out of loop,
253480093f4SDimitry Andric     /// this may leads to register presure like LICM does.
254480093f4SDimitry Andric     /// Make sure total preparation number can be controlled by option.
255480093f4SDimitry Andric     unsigned SuccPrepCount;
256480093f4SDimitry Andric 
257480093f4SDimitry Andric     bool runOnLoop(Loop *L);
258480093f4SDimitry Andric 
259480093f4SDimitry Andric     /// Check if required PHI node is already exist in Loop \p L.
260480093f4SDimitry Andric     bool alreadyPrepared(Loop *L, Instruction *MemI,
261480093f4SDimitry Andric                          const SCEV *BasePtrStartSCEV,
262349cc55cSDimitry Andric                          const SCEV *BasePtrIncSCEV, PrepForm Form);
263349cc55cSDimitry Andric 
264349cc55cSDimitry Andric     /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
265349cc55cSDimitry Andric     Value *getNodeForInc(Loop *L, Instruction *MemI,
266349cc55cSDimitry Andric                          const SCEV *BasePtrIncSCEV);
267349cc55cSDimitry Andric 
268349cc55cSDimitry Andric     /// Common chains to reuse offsets for a loop to reduce register pressure.
269349cc55cSDimitry Andric     bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
270349cc55cSDimitry Andric 
271349cc55cSDimitry Andric     /// Find out the potential commoning chains and their bases.
272349cc55cSDimitry Andric     bool prepareBasesForCommoningChains(Bucket &BucketChain);
273349cc55cSDimitry Andric 
274349cc55cSDimitry Andric     /// Rewrite load/store according to the common chains.
275349cc55cSDimitry Andric     bool
276349cc55cSDimitry Andric     rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
277349cc55cSDimitry Andric                                         SmallSet<BasicBlock *, 16> &BBChanged);
278480093f4SDimitry Andric 
279480093f4SDimitry Andric     /// Collect condition matched(\p isValidCandidate() returns true)
280480093f4SDimitry Andric     /// candidates in Loop \p L.
281fe6060f1SDimitry Andric     SmallVector<Bucket, 16> collectCandidates(
282fe6060f1SDimitry Andric         Loop *L,
283349cc55cSDimitry Andric         std::function<bool(const Instruction *, Value *, const Type *)>
284480093f4SDimitry Andric             isValidCandidate,
285349cc55cSDimitry Andric         std::function<bool(const SCEV *)> isValidDiff,
286480093f4SDimitry Andric         unsigned MaxCandidateNum);
287480093f4SDimitry Andric 
288349cc55cSDimitry Andric     /// Add a candidate to candidates \p Buckets if diff between candidate and
289349cc55cSDimitry Andric     /// one base in \p Buckets matches \p isValidDiff.
290480093f4SDimitry Andric     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
291480093f4SDimitry Andric                          SmallVector<Bucket, 16> &Buckets,
292349cc55cSDimitry Andric                          std::function<bool(const SCEV *)> isValidDiff,
293480093f4SDimitry Andric                          unsigned MaxCandidateNum);
294480093f4SDimitry Andric 
295480093f4SDimitry Andric     /// Prepare all candidates in \p Buckets for update form.
296480093f4SDimitry Andric     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
297480093f4SDimitry Andric 
298480093f4SDimitry Andric     /// Prepare all candidates in \p Buckets for displacement form, now for
299480093f4SDimitry Andric     /// ds/dq.
300349cc55cSDimitry Andric     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
301480093f4SDimitry Andric 
302480093f4SDimitry Andric     /// Prepare for one chain \p BucketChain, find the best base element and
303480093f4SDimitry Andric     /// update all other elements in \p BucketChain accordingly.
304480093f4SDimitry Andric     /// \p Form is used to find the best base element.
305480093f4SDimitry Andric     /// If success, best base element must be stored as the first element of
306480093f4SDimitry Andric     /// \p BucketChain.
307480093f4SDimitry Andric     /// Return false if no base element found, otherwise return true.
308349cc55cSDimitry Andric     bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
309480093f4SDimitry Andric 
310480093f4SDimitry Andric     /// Prepare for one chain \p BucketChain, find the best base element and
311480093f4SDimitry Andric     /// update all other elements in \p BucketChain accordingly.
312480093f4SDimitry Andric     /// If success, best base element must be stored as the first element of
313480093f4SDimitry Andric     /// \p BucketChain.
314480093f4SDimitry Andric     /// Return false if no base element found, otherwise return true.
315480093f4SDimitry Andric     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
316480093f4SDimitry Andric 
317480093f4SDimitry Andric     /// Rewrite load/store instructions in \p BucketChain according to
318480093f4SDimitry Andric     /// preparation.
319480093f4SDimitry Andric     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
320480093f4SDimitry Andric                            SmallSet<BasicBlock *, 16> &BBChanged,
321349cc55cSDimitry Andric                            PrepForm Form);
322349cc55cSDimitry Andric 
323349cc55cSDimitry Andric     /// Rewrite for the base load/store of a chain.
324349cc55cSDimitry Andric     std::pair<Instruction *, Instruction *>
325349cc55cSDimitry Andric     rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
326349cc55cSDimitry Andric                    Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
327349cc55cSDimitry Andric                    SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
328349cc55cSDimitry Andric 
329349cc55cSDimitry Andric     /// Rewrite for the other load/stores of a chain according to the new \p
330349cc55cSDimitry Andric     /// Base.
331349cc55cSDimitry Andric     Instruction *
332349cc55cSDimitry Andric     rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
333349cc55cSDimitry Andric                             const BucketElement &Element, Value *OffToBase,
334349cc55cSDimitry Andric                             SmallPtrSet<Value *, 16> &DeletedPtrs);
335480093f4SDimitry Andric   };
336480093f4SDimitry Andric 
337480093f4SDimitry Andric } // end anonymous namespace
338480093f4SDimitry Andric 
339480093f4SDimitry Andric char PPCLoopInstrFormPrep::ID = 0;
340480093f4SDimitry Andric static const char *name = "Prepare loop for ppc preferred instruction forms";
341480093f4SDimitry Andric INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
342480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
343480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
344480093f4SDimitry Andric INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
345480093f4SDimitry Andric 
3465ffd83dbSDimitry Andric static constexpr StringRef PHINodeNameSuffix    = ".phi";
3475ffd83dbSDimitry Andric static constexpr StringRef CastNodeNameSuffix   = ".cast";
3485ffd83dbSDimitry Andric static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
3495ffd83dbSDimitry Andric static constexpr StringRef GEPNodeOffNameSuffix = ".off";
350480093f4SDimitry Andric 
351480093f4SDimitry Andric FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
352480093f4SDimitry Andric   return new PPCLoopInstrFormPrep(TM);
353480093f4SDimitry Andric }
354480093f4SDimitry Andric 
355480093f4SDimitry Andric static bool IsPtrInBounds(Value *BasePtr) {
356480093f4SDimitry Andric   Value *StrippedBasePtr = BasePtr;
357480093f4SDimitry Andric   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
358480093f4SDimitry Andric     StrippedBasePtr = BC->getOperand(0);
359480093f4SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
360480093f4SDimitry Andric     return GEP->isInBounds();
361480093f4SDimitry Andric 
362480093f4SDimitry Andric   return false;
363480093f4SDimitry Andric }
364480093f4SDimitry Andric 
3655ffd83dbSDimitry Andric static std::string getInstrName(const Value *I, StringRef Suffix) {
366480093f4SDimitry Andric   assert(I && "Invalid paramater!");
367480093f4SDimitry Andric   if (I->hasName())
368480093f4SDimitry Andric     return (I->getName() + Suffix).str();
369480093f4SDimitry Andric   else
370480093f4SDimitry Andric     return "";
371480093f4SDimitry Andric }
372480093f4SDimitry Andric 
373349cc55cSDimitry Andric static Value *getPointerOperandAndType(Value *MemI,
374349cc55cSDimitry Andric                                        Type **PtrElementType = nullptr) {
375480093f4SDimitry Andric 
376349cc55cSDimitry Andric   Value *PtrValue = nullptr;
377349cc55cSDimitry Andric   Type *PointerElementType = nullptr;
378349cc55cSDimitry Andric 
379349cc55cSDimitry Andric   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
380349cc55cSDimitry Andric     PtrValue = LMemI->getPointerOperand();
381349cc55cSDimitry Andric     PointerElementType = LMemI->getType();
382349cc55cSDimitry Andric   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
383349cc55cSDimitry Andric     PtrValue = SMemI->getPointerOperand();
384349cc55cSDimitry Andric     PointerElementType = SMemI->getValueOperand()->getType();
385349cc55cSDimitry Andric   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
386349cc55cSDimitry Andric     PointerElementType = Type::getInt8Ty(MemI->getContext());
387349cc55cSDimitry Andric     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
388349cc55cSDimitry Andric         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
389349cc55cSDimitry Andric       PtrValue = IMemI->getArgOperand(0);
390349cc55cSDimitry Andric     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
391349cc55cSDimitry Andric       PtrValue = IMemI->getArgOperand(1);
392349cc55cSDimitry Andric     }
393349cc55cSDimitry Andric   }
394349cc55cSDimitry Andric   /*Get ElementType if PtrElementType is not null.*/
395349cc55cSDimitry Andric   if (PtrElementType)
396349cc55cSDimitry Andric     *PtrElementType = PointerElementType;
397349cc55cSDimitry Andric 
398349cc55cSDimitry Andric   return PtrValue;
399480093f4SDimitry Andric }
400480093f4SDimitry Andric 
401480093f4SDimitry Andric bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
402480093f4SDimitry Andric   if (skipFunction(F))
403480093f4SDimitry Andric     return false;
404480093f4SDimitry Andric 
405480093f4SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
406480093f4SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
407480093f4SDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
408480093f4SDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
409480093f4SDimitry Andric   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
410480093f4SDimitry Andric   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
411480093f4SDimitry Andric   SuccPrepCount = 0;
412480093f4SDimitry Andric 
413480093f4SDimitry Andric   bool MadeChange = false;
414480093f4SDimitry Andric 
4150eae32dcSDimitry Andric   for (Loop *I : *LI)
4160eae32dcSDimitry Andric     for (Loop *L : depth_first(I))
4170eae32dcSDimitry Andric       MadeChange |= runOnLoop(L);
418480093f4SDimitry Andric 
419480093f4SDimitry Andric   return MadeChange;
420480093f4SDimitry Andric }
421480093f4SDimitry Andric 
422349cc55cSDimitry Andric // Finding the minimal(chain_number + reusable_offset_number) is a complicated
423349cc55cSDimitry Andric // algorithmic problem.
424349cc55cSDimitry Andric // For now, the algorithm used here is simply adjusted to handle the case for
425349cc55cSDimitry Andric // manually unrolling cases.
426349cc55cSDimitry Andric // FIXME: use a more powerful algorithm to find minimal sum of chain_number and
427349cc55cSDimitry Andric // reusable_offset_number for one base with multiple offsets.
428349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
429349cc55cSDimitry Andric   // The minimal size for profitable chain commoning:
430349cc55cSDimitry Andric   // A1 = base + offset1
431349cc55cSDimitry Andric   // A2 = base + offset2 (offset2 - offset1 = X)
432349cc55cSDimitry Andric   // A3 = base + offset3
433349cc55cSDimitry Andric   // A4 = base + offset4 (offset4 - offset3 = X)
434349cc55cSDimitry Andric   // ======>
435349cc55cSDimitry Andric   // base1 = base + offset1
436349cc55cSDimitry Andric   // base2 = base + offset3
437349cc55cSDimitry Andric   // A1 = base1
438349cc55cSDimitry Andric   // A2 = base1 + X
439349cc55cSDimitry Andric   // A3 = base2
440349cc55cSDimitry Andric   // A4 = base2 + X
441349cc55cSDimitry Andric   //
442349cc55cSDimitry Andric   // There is benefit because of reuse of offest 'X'.
443349cc55cSDimitry Andric 
444349cc55cSDimitry Andric   assert(ChainCommonPrepMinThreshold >= 4 &&
445349cc55cSDimitry Andric          "Thredhold can not be smaller than 4!\n");
446349cc55cSDimitry Andric   if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
447349cc55cSDimitry Andric     return false;
448349cc55cSDimitry Andric 
449349cc55cSDimitry Andric   // We simply select the FirstOffset as the first reusable offset between each
450349cc55cSDimitry Andric   // chain element 1 and element 0.
451349cc55cSDimitry Andric   const SCEV *FirstOffset = CBucket.Elements[1].Offset;
452349cc55cSDimitry Andric 
453349cc55cSDimitry Andric   // Figure out how many times above FirstOffset is used in the chain.
454349cc55cSDimitry Andric   // For a success commoning chain candidate, offset difference between each
455349cc55cSDimitry Andric   // chain element 1 and element 0 must be also FirstOffset.
456349cc55cSDimitry Andric   unsigned FirstOffsetReusedCount = 1;
457349cc55cSDimitry Andric 
458349cc55cSDimitry Andric   // Figure out how many times above FirstOffset is used in the first chain.
459349cc55cSDimitry Andric   // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
460349cc55cSDimitry Andric   unsigned FirstOffsetReusedCountInFirstChain = 1;
461349cc55cSDimitry Andric 
462349cc55cSDimitry Andric   unsigned EleNum = CBucket.Elements.size();
463349cc55cSDimitry Andric   bool SawChainSeparater = false;
464349cc55cSDimitry Andric   for (unsigned j = 2; j != EleNum; ++j) {
465349cc55cSDimitry Andric     if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
466349cc55cSDimitry Andric                          CBucket.Elements[j - 1].Offset) == FirstOffset) {
467349cc55cSDimitry Andric       if (!SawChainSeparater)
468349cc55cSDimitry Andric         FirstOffsetReusedCountInFirstChain++;
469349cc55cSDimitry Andric       FirstOffsetReusedCount++;
470349cc55cSDimitry Andric     } else
471349cc55cSDimitry Andric       // For now, if we meet any offset which is not FirstOffset, we assume we
472349cc55cSDimitry Andric       // find a new Chain.
473349cc55cSDimitry Andric       // This makes us miss some opportunities.
474349cc55cSDimitry Andric       // For example, we can common:
475349cc55cSDimitry Andric       //
476349cc55cSDimitry Andric       // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
477349cc55cSDimitry Andric       //
478349cc55cSDimitry Andric       // as two chains:
479349cc55cSDimitry Andric       // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
480349cc55cSDimitry Andric       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
481349cc55cSDimitry Andric       //
482349cc55cSDimitry Andric       // But we fail to common:
483349cc55cSDimitry Andric       //
484349cc55cSDimitry Andric       // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
485349cc55cSDimitry Andric       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
486349cc55cSDimitry Andric 
487349cc55cSDimitry Andric       SawChainSeparater = true;
488349cc55cSDimitry Andric   }
489349cc55cSDimitry Andric 
490349cc55cSDimitry Andric   // FirstOffset is not reused, skip this bucket.
491349cc55cSDimitry Andric   if (FirstOffsetReusedCount == 1)
492349cc55cSDimitry Andric     return false;
493349cc55cSDimitry Andric 
494349cc55cSDimitry Andric   unsigned ChainNum =
495349cc55cSDimitry Andric       FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
496349cc55cSDimitry Andric 
497349cc55cSDimitry Andric   // All elements are increased by FirstOffset.
498349cc55cSDimitry Andric   // The number of chains should be sqrt(EleNum).
499349cc55cSDimitry Andric   if (!SawChainSeparater)
500349cc55cSDimitry Andric     ChainNum = (unsigned)sqrt((double)EleNum);
501349cc55cSDimitry Andric 
502349cc55cSDimitry Andric   CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
503349cc55cSDimitry Andric 
504349cc55cSDimitry Andric   // If this is not a perfect chain(eg: not all elements can be put inside
505349cc55cSDimitry Andric   // commoning chains.), skip now.
506349cc55cSDimitry Andric   if (CBucket.ChainSize * ChainNum != EleNum)
507349cc55cSDimitry Andric     return false;
508349cc55cSDimitry Andric 
509349cc55cSDimitry Andric   if (SawChainSeparater) {
510349cc55cSDimitry Andric     // Check that the offset seqs are the same for all chains.
511349cc55cSDimitry Andric     for (unsigned i = 1; i < CBucket.ChainSize; i++)
512349cc55cSDimitry Andric       for (unsigned j = 1; j < ChainNum; j++)
513349cc55cSDimitry Andric         if (CBucket.Elements[i].Offset !=
514349cc55cSDimitry Andric             SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
515349cc55cSDimitry Andric                              CBucket.Elements[j * CBucket.ChainSize].Offset))
516349cc55cSDimitry Andric           return false;
517349cc55cSDimitry Andric   }
518349cc55cSDimitry Andric 
519349cc55cSDimitry Andric   for (unsigned i = 0; i < ChainNum; i++)
520349cc55cSDimitry Andric     CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
521349cc55cSDimitry Andric 
522349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
523349cc55cSDimitry Andric 
524349cc55cSDimitry Andric   return true;
525349cc55cSDimitry Andric }
526349cc55cSDimitry Andric 
527349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
528349cc55cSDimitry Andric                                           SmallVector<Bucket, 16> &Buckets) {
529349cc55cSDimitry Andric   bool MadeChange = false;
530349cc55cSDimitry Andric 
531349cc55cSDimitry Andric   if (Buckets.empty())
532349cc55cSDimitry Andric     return MadeChange;
533349cc55cSDimitry Andric 
534349cc55cSDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
535349cc55cSDimitry Andric 
536349cc55cSDimitry Andric   for (auto &Bucket : Buckets) {
537349cc55cSDimitry Andric     if (prepareBasesForCommoningChains(Bucket))
538349cc55cSDimitry Andric       MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
539349cc55cSDimitry Andric   }
540349cc55cSDimitry Andric 
541349cc55cSDimitry Andric   if (MadeChange)
542349cc55cSDimitry Andric     for (auto *BB : BBChanged)
543349cc55cSDimitry Andric       DeleteDeadPHIs(BB);
544349cc55cSDimitry Andric   return MadeChange;
545349cc55cSDimitry Andric }
546349cc55cSDimitry Andric 
547349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
548349cc55cSDimitry Andric     Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
549349cc55cSDimitry Andric   bool MadeChange = false;
550349cc55cSDimitry Andric 
551349cc55cSDimitry Andric   assert(Bucket.Elements.size() ==
552349cc55cSDimitry Andric              Bucket.ChainBases.size() * Bucket.ChainSize &&
553349cc55cSDimitry Andric          "invalid bucket for chain commoning!\n");
554349cc55cSDimitry Andric   SmallPtrSet<Value *, 16> DeletedPtrs;
555349cc55cSDimitry Andric 
556349cc55cSDimitry Andric   BasicBlock *Header = L->getHeader();
557349cc55cSDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
558349cc55cSDimitry Andric 
559349cc55cSDimitry Andric   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
560349cc55cSDimitry Andric                      "loopprepare-chaincommon");
561349cc55cSDimitry Andric 
562349cc55cSDimitry Andric   for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
563349cc55cSDimitry Andric     unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
564349cc55cSDimitry Andric     const SCEV *BaseSCEV =
565349cc55cSDimitry Andric         ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
566349cc55cSDimitry Andric                                   Bucket.Elements[BaseElemIdx].Offset)
567349cc55cSDimitry Andric                  : Bucket.BaseSCEV;
568349cc55cSDimitry Andric     const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
569349cc55cSDimitry Andric 
570349cc55cSDimitry Andric     // Make sure the base is able to expand.
571*fcaf7f86SDimitry Andric     if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
572349cc55cSDimitry Andric       return MadeChange;
573349cc55cSDimitry Andric 
574349cc55cSDimitry Andric     assert(BasePtrSCEV->isAffine() &&
575349cc55cSDimitry Andric            "Invalid SCEV type for the base ptr for a candidate chain!\n");
576349cc55cSDimitry Andric 
577349cc55cSDimitry Andric     std::pair<Instruction *, Instruction *> Base = rewriteForBase(
578349cc55cSDimitry Andric         L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
579349cc55cSDimitry Andric         false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs);
580349cc55cSDimitry Andric 
581349cc55cSDimitry Andric     if (!Base.first || !Base.second)
582349cc55cSDimitry Andric       return MadeChange;
583349cc55cSDimitry Andric 
584349cc55cSDimitry Andric     // Keep track of the replacement pointer values we've inserted so that we
585349cc55cSDimitry Andric     // don't generate more pointer values than necessary.
586349cc55cSDimitry Andric     SmallPtrSet<Value *, 16> NewPtrs;
587349cc55cSDimitry Andric     NewPtrs.insert(Base.first);
588349cc55cSDimitry Andric 
589349cc55cSDimitry Andric     for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
590349cc55cSDimitry Andric          ++Idx) {
591349cc55cSDimitry Andric       BucketElement &I = Bucket.Elements[Idx];
592349cc55cSDimitry Andric       Value *Ptr = getPointerOperandAndType(I.Instr);
593349cc55cSDimitry Andric       assert(Ptr && "No pointer operand");
594349cc55cSDimitry Andric       if (NewPtrs.count(Ptr))
595349cc55cSDimitry Andric         continue;
596349cc55cSDimitry Andric 
597349cc55cSDimitry Andric       const SCEV *OffsetSCEV =
598349cc55cSDimitry Andric           BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
599349cc55cSDimitry Andric                                          Bucket.Elements[BaseElemIdx].Offset)
600349cc55cSDimitry Andric                       : Bucket.Elements[Idx].Offset;
601349cc55cSDimitry Andric 
602349cc55cSDimitry Andric       // Make sure offset is able to expand. Only need to check one time as the
603349cc55cSDimitry Andric       // offsets are reused between different chains.
604349cc55cSDimitry Andric       if (!BaseElemIdx)
605*fcaf7f86SDimitry Andric         if (!SCEVE.isSafeToExpand(OffsetSCEV))
606349cc55cSDimitry Andric           return false;
607349cc55cSDimitry Andric 
608349cc55cSDimitry Andric       Value *OffsetValue = SCEVE.expandCodeFor(
609349cc55cSDimitry Andric           OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
610349cc55cSDimitry Andric 
611349cc55cSDimitry Andric       Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
612349cc55cSDimitry Andric                                                     OffsetValue, DeletedPtrs);
613349cc55cSDimitry Andric 
614349cc55cSDimitry Andric       assert(NewPtr && "Wrong rewrite!\n");
615349cc55cSDimitry Andric       NewPtrs.insert(NewPtr);
616349cc55cSDimitry Andric     }
617349cc55cSDimitry Andric 
618349cc55cSDimitry Andric     ++ChainCommoningRewritten;
619349cc55cSDimitry Andric   }
620349cc55cSDimitry Andric 
621349cc55cSDimitry Andric   // Clear the rewriter cache, because values that are in the rewriter's cache
622349cc55cSDimitry Andric   // can be deleted below, causing the AssertingVH in the cache to trigger.
623349cc55cSDimitry Andric   SCEVE.clear();
624349cc55cSDimitry Andric 
625349cc55cSDimitry Andric   for (auto *Ptr : DeletedPtrs) {
626349cc55cSDimitry Andric     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
627349cc55cSDimitry Andric       BBChanged.insert(IDel->getParent());
628349cc55cSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
629349cc55cSDimitry Andric   }
630349cc55cSDimitry Andric 
631349cc55cSDimitry Andric   MadeChange = true;
632349cc55cSDimitry Andric   return MadeChange;
633349cc55cSDimitry Andric }
634349cc55cSDimitry Andric 
635349cc55cSDimitry Andric // Rewrite the new base according to BasePtrSCEV.
636349cc55cSDimitry Andric // bb.loop.preheader:
637349cc55cSDimitry Andric //   %newstart = ...
638349cc55cSDimitry Andric // bb.loop.body:
639349cc55cSDimitry Andric //   %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
640349cc55cSDimitry Andric //   ...
641349cc55cSDimitry Andric //   %add = getelementptr %phinode, %inc
642349cc55cSDimitry Andric //
643349cc55cSDimitry Andric // First returned instruciton is %phinode (or a type cast to %phinode), caller
644349cc55cSDimitry Andric // needs this value to rewrite other load/stores in the same chain.
645349cc55cSDimitry Andric // Second returned instruction is %add, caller needs this value to rewrite other
646349cc55cSDimitry Andric // load/stores in the same chain.
647349cc55cSDimitry Andric std::pair<Instruction *, Instruction *>
648349cc55cSDimitry Andric PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
649349cc55cSDimitry Andric                                      Instruction *BaseMemI, bool CanPreInc,
650349cc55cSDimitry Andric                                      PrepForm Form, SCEVExpander &SCEVE,
651349cc55cSDimitry Andric                                      SmallPtrSet<Value *, 16> &DeletedPtrs) {
652349cc55cSDimitry Andric 
653349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
654349cc55cSDimitry Andric 
655349cc55cSDimitry Andric   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
656349cc55cSDimitry Andric 
657349cc55cSDimitry Andric   Value *BasePtr = getPointerOperandAndType(BaseMemI);
658349cc55cSDimitry Andric   assert(BasePtr && "No pointer operand");
659349cc55cSDimitry Andric 
660349cc55cSDimitry Andric   Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
661349cc55cSDimitry Andric   Type *I8PtrTy =
662349cc55cSDimitry Andric       Type::getInt8PtrTy(BaseMemI->getParent()->getContext(),
663349cc55cSDimitry Andric                          BasePtr->getType()->getPointerAddressSpace());
664349cc55cSDimitry Andric 
665349cc55cSDimitry Andric   bool IsConstantInc = false;
666349cc55cSDimitry Andric   const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
667349cc55cSDimitry Andric   Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
668349cc55cSDimitry Andric 
669349cc55cSDimitry Andric   const SCEVConstant *BasePtrIncConstantSCEV =
670349cc55cSDimitry Andric       dyn_cast<SCEVConstant>(BasePtrIncSCEV);
671349cc55cSDimitry Andric   if (BasePtrIncConstantSCEV)
672349cc55cSDimitry Andric     IsConstantInc = true;
673349cc55cSDimitry Andric 
674349cc55cSDimitry Andric   // No valid representation for the increment.
675349cc55cSDimitry Andric   if (!IncNode) {
676349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
677349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
678349cc55cSDimitry Andric   }
679349cc55cSDimitry Andric 
680349cc55cSDimitry Andric   if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) {
681349cc55cSDimitry Andric     LLVM_DEBUG(
682349cc55cSDimitry Andric         dbgs()
683349cc55cSDimitry Andric         << "Update form prepare for non-const increment is not enabled!\n");
684349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
685349cc55cSDimitry Andric   }
686349cc55cSDimitry Andric 
687349cc55cSDimitry Andric   const SCEV *BasePtrStartSCEV = nullptr;
688349cc55cSDimitry Andric   if (CanPreInc) {
689349cc55cSDimitry Andric     assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
690349cc55cSDimitry Andric            "Increment is not loop invariant!\n");
691349cc55cSDimitry Andric     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
692349cc55cSDimitry Andric                                         IsConstantInc ? BasePtrIncConstantSCEV
693349cc55cSDimitry Andric                                                       : BasePtrIncSCEV);
694349cc55cSDimitry Andric   } else
695349cc55cSDimitry Andric     BasePtrStartSCEV = BasePtrSCEV->getStart();
696349cc55cSDimitry Andric 
697349cc55cSDimitry Andric   if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
698349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
699349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
700349cc55cSDimitry Andric   }
701349cc55cSDimitry Andric 
702349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
703349cc55cSDimitry Andric 
704349cc55cSDimitry Andric   BasicBlock *Header = L->getHeader();
705349cc55cSDimitry Andric   unsigned HeaderLoopPredCount = pred_size(Header);
706349cc55cSDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
707349cc55cSDimitry Andric 
708349cc55cSDimitry Andric   PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
709349cc55cSDimitry Andric                                     getInstrName(BaseMemI, PHINodeNameSuffix),
710349cc55cSDimitry Andric                                     Header->getFirstNonPHI());
711349cc55cSDimitry Andric 
712349cc55cSDimitry Andric   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
713349cc55cSDimitry Andric                                             LoopPredecessor->getTerminator());
714349cc55cSDimitry Andric 
715349cc55cSDimitry Andric   // Note that LoopPredecessor might occur in the predecessor list multiple
716349cc55cSDimitry Andric   // times, and we need to add it the right number of times.
717349cc55cSDimitry Andric   for (auto PI : predecessors(Header)) {
718349cc55cSDimitry Andric     if (PI != LoopPredecessor)
719349cc55cSDimitry Andric       continue;
720349cc55cSDimitry Andric 
721349cc55cSDimitry Andric     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
722349cc55cSDimitry Andric   }
723349cc55cSDimitry Andric 
724349cc55cSDimitry Andric   Instruction *PtrInc = nullptr;
725349cc55cSDimitry Andric   Instruction *NewBasePtr = nullptr;
726349cc55cSDimitry Andric   if (CanPreInc) {
727349cc55cSDimitry Andric     Instruction *InsPoint = &*Header->getFirstInsertionPt();
728349cc55cSDimitry Andric     PtrInc = GetElementPtrInst::Create(
729349cc55cSDimitry Andric         I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
730349cc55cSDimitry Andric         InsPoint);
731349cc55cSDimitry Andric     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
732349cc55cSDimitry Andric     for (auto PI : predecessors(Header)) {
733349cc55cSDimitry Andric       if (PI == LoopPredecessor)
734349cc55cSDimitry Andric         continue;
735349cc55cSDimitry Andric 
736349cc55cSDimitry Andric       NewPHI->addIncoming(PtrInc, PI);
737349cc55cSDimitry Andric     }
738349cc55cSDimitry Andric     if (PtrInc->getType() != BasePtr->getType())
739349cc55cSDimitry Andric       NewBasePtr =
740349cc55cSDimitry Andric           new BitCastInst(PtrInc, BasePtr->getType(),
741349cc55cSDimitry Andric                           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
742349cc55cSDimitry Andric     else
743349cc55cSDimitry Andric       NewBasePtr = PtrInc;
744349cc55cSDimitry Andric   } else {
745349cc55cSDimitry Andric     // Note that LoopPredecessor might occur in the predecessor list multiple
746349cc55cSDimitry Andric     // times, and we need to make sure no more incoming value for them in PHI.
747349cc55cSDimitry Andric     for (auto PI : predecessors(Header)) {
748349cc55cSDimitry Andric       if (PI == LoopPredecessor)
749349cc55cSDimitry Andric         continue;
750349cc55cSDimitry Andric 
751349cc55cSDimitry Andric       // For the latch predecessor, we need to insert a GEP just before the
752349cc55cSDimitry Andric       // terminator to increase the address.
753349cc55cSDimitry Andric       BasicBlock *BB = PI;
754349cc55cSDimitry Andric       Instruction *InsPoint = BB->getTerminator();
755349cc55cSDimitry Andric       PtrInc = GetElementPtrInst::Create(
756349cc55cSDimitry Andric           I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
757349cc55cSDimitry Andric           InsPoint);
758349cc55cSDimitry Andric       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
759349cc55cSDimitry Andric 
760349cc55cSDimitry Andric       NewPHI->addIncoming(PtrInc, PI);
761349cc55cSDimitry Andric     }
762349cc55cSDimitry Andric     PtrInc = NewPHI;
763349cc55cSDimitry Andric     if (NewPHI->getType() != BasePtr->getType())
764349cc55cSDimitry Andric       NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
765349cc55cSDimitry Andric                                    getInstrName(NewPHI, CastNodeNameSuffix),
766349cc55cSDimitry Andric                                    &*Header->getFirstInsertionPt());
767349cc55cSDimitry Andric     else
768349cc55cSDimitry Andric       NewBasePtr = NewPHI;
769349cc55cSDimitry Andric   }
770349cc55cSDimitry Andric 
771349cc55cSDimitry Andric   BasePtr->replaceAllUsesWith(NewBasePtr);
772349cc55cSDimitry Andric 
773349cc55cSDimitry Andric   DeletedPtrs.insert(BasePtr);
774349cc55cSDimitry Andric 
775349cc55cSDimitry Andric   return std::make_pair(NewBasePtr, PtrInc);
776349cc55cSDimitry Andric }
777349cc55cSDimitry Andric 
778349cc55cSDimitry Andric Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
779349cc55cSDimitry Andric     std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
780349cc55cSDimitry Andric     Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
781349cc55cSDimitry Andric   Instruction *NewBasePtr = Base.first;
782349cc55cSDimitry Andric   Instruction *PtrInc = Base.second;
783349cc55cSDimitry Andric   assert((NewBasePtr && PtrInc) && "base does not exist!\n");
784349cc55cSDimitry Andric 
785349cc55cSDimitry Andric   Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
786349cc55cSDimitry Andric 
787349cc55cSDimitry Andric   Value *Ptr = getPointerOperandAndType(Element.Instr);
788349cc55cSDimitry Andric   assert(Ptr && "No pointer operand");
789349cc55cSDimitry Andric 
790349cc55cSDimitry Andric   Instruction *RealNewPtr;
791349cc55cSDimitry Andric   if (!Element.Offset ||
792349cc55cSDimitry Andric       (isa<SCEVConstant>(Element.Offset) &&
793349cc55cSDimitry Andric        cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
794349cc55cSDimitry Andric     RealNewPtr = NewBasePtr;
795349cc55cSDimitry Andric   } else {
796349cc55cSDimitry Andric     Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
797349cc55cSDimitry Andric     if (PtrIP && isa<Instruction>(NewBasePtr) &&
798349cc55cSDimitry Andric         cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
799349cc55cSDimitry Andric       PtrIP = nullptr;
800349cc55cSDimitry Andric     else if (PtrIP && isa<PHINode>(PtrIP))
801349cc55cSDimitry Andric       PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
802349cc55cSDimitry Andric     else if (!PtrIP)
803349cc55cSDimitry Andric       PtrIP = Element.Instr;
804349cc55cSDimitry Andric 
805349cc55cSDimitry Andric     assert(OffToBase && "There should be an offset for non base element!\n");
806349cc55cSDimitry Andric     GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
807349cc55cSDimitry Andric         I8Ty, PtrInc, OffToBase,
808349cc55cSDimitry Andric         getInstrName(Element.Instr, GEPNodeOffNameSuffix), PtrIP);
809349cc55cSDimitry Andric     if (!PtrIP)
810349cc55cSDimitry Andric       NewPtr->insertAfter(cast<Instruction>(PtrInc));
811349cc55cSDimitry Andric     NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
812349cc55cSDimitry Andric     RealNewPtr = NewPtr;
813349cc55cSDimitry Andric   }
814349cc55cSDimitry Andric 
815349cc55cSDimitry Andric   Instruction *ReplNewPtr;
816349cc55cSDimitry Andric   if (Ptr->getType() != RealNewPtr->getType()) {
817349cc55cSDimitry Andric     ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
818349cc55cSDimitry Andric                                  getInstrName(Ptr, CastNodeNameSuffix));
819349cc55cSDimitry Andric     ReplNewPtr->insertAfter(RealNewPtr);
820349cc55cSDimitry Andric   } else
821349cc55cSDimitry Andric     ReplNewPtr = RealNewPtr;
822349cc55cSDimitry Andric 
823349cc55cSDimitry Andric   Ptr->replaceAllUsesWith(ReplNewPtr);
824349cc55cSDimitry Andric   DeletedPtrs.insert(Ptr);
825349cc55cSDimitry Andric 
826349cc55cSDimitry Andric   return ReplNewPtr;
827349cc55cSDimitry Andric }
828349cc55cSDimitry Andric 
829349cc55cSDimitry Andric void PPCLoopInstrFormPrep::addOneCandidate(
830349cc55cSDimitry Andric     Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
831349cc55cSDimitry Andric     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
832349cc55cSDimitry Andric   assert((MemI && getPointerOperandAndType(MemI)) &&
833480093f4SDimitry Andric          "Candidate should be a memory instruction.");
834480093f4SDimitry Andric   assert(LSCEV && "Invalid SCEV for Ptr value.");
835349cc55cSDimitry Andric 
836480093f4SDimitry Andric   bool FoundBucket = false;
837480093f4SDimitry Andric   for (auto &B : Buckets) {
838349cc55cSDimitry Andric     if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
839349cc55cSDimitry Andric         cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
840349cc55cSDimitry Andric       continue;
841480093f4SDimitry Andric     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
842349cc55cSDimitry Andric     if (isValidDiff(Diff)) {
843349cc55cSDimitry Andric       B.Elements.push_back(BucketElement(Diff, MemI));
844480093f4SDimitry Andric       FoundBucket = true;
845480093f4SDimitry Andric       break;
846480093f4SDimitry Andric     }
847480093f4SDimitry Andric   }
848480093f4SDimitry Andric 
849480093f4SDimitry Andric   if (!FoundBucket) {
850349cc55cSDimitry Andric     if (Buckets.size() == MaxCandidateNum) {
851349cc55cSDimitry Andric       LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
852349cc55cSDimitry Andric                         << MaxCandidateNum << "\n");
853480093f4SDimitry Andric       return;
854349cc55cSDimitry Andric     }
855480093f4SDimitry Andric     Buckets.push_back(Bucket(LSCEV, MemI));
856480093f4SDimitry Andric   }
857480093f4SDimitry Andric }
858480093f4SDimitry Andric 
859480093f4SDimitry Andric SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
860480093f4SDimitry Andric     Loop *L,
861349cc55cSDimitry Andric     std::function<bool(const Instruction *, Value *, const Type *)>
862fe6060f1SDimitry Andric         isValidCandidate,
863349cc55cSDimitry Andric     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
864480093f4SDimitry Andric   SmallVector<Bucket, 16> Buckets;
865349cc55cSDimitry Andric 
866480093f4SDimitry Andric   for (const auto &BB : L->blocks())
867480093f4SDimitry Andric     for (auto &J : *BB) {
868349cc55cSDimitry Andric       Value *PtrValue = nullptr;
869349cc55cSDimitry Andric       Type *PointerElementType = nullptr;
870349cc55cSDimitry Andric       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
871480093f4SDimitry Andric 
872349cc55cSDimitry Andric       if (!PtrValue)
873349cc55cSDimitry Andric         continue;
874480093f4SDimitry Andric 
875349cc55cSDimitry Andric       if (PtrValue->getType()->getPointerAddressSpace())
876480093f4SDimitry Andric         continue;
877480093f4SDimitry Andric 
878480093f4SDimitry Andric       if (L->isLoopInvariant(PtrValue))
879480093f4SDimitry Andric         continue;
880480093f4SDimitry Andric 
881480093f4SDimitry Andric       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
882480093f4SDimitry Andric       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
883480093f4SDimitry Andric       if (!LARSCEV || LARSCEV->getLoop() != L)
884480093f4SDimitry Andric         continue;
885480093f4SDimitry Andric 
886349cc55cSDimitry Andric       // Mark that we have candidates for preparing.
887349cc55cSDimitry Andric       HasCandidateForPrepare = true;
888349cc55cSDimitry Andric 
889fe6060f1SDimitry Andric       if (isValidCandidate(&J, PtrValue, PointerElementType))
890349cc55cSDimitry Andric         addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
891480093f4SDimitry Andric     }
892480093f4SDimitry Andric   return Buckets;
893480093f4SDimitry Andric }
894480093f4SDimitry Andric 
895480093f4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
896349cc55cSDimitry Andric                                                        PrepForm Form) {
897480093f4SDimitry Andric   // RemainderOffsetInfo details:
898480093f4SDimitry Andric   // key:            value of (Offset urem DispConstraint). For DSForm, it can
899480093f4SDimitry Andric   //                 be [0, 4).
900480093f4SDimitry Andric   // first of pair:  the index of first BucketElement whose remainder is equal
901480093f4SDimitry Andric   //                 to key. For key 0, this value must be 0.
902480093f4SDimitry Andric   // second of pair: number of load/stores with the same remainder.
903480093f4SDimitry Andric   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
904480093f4SDimitry Andric 
905480093f4SDimitry Andric   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
906480093f4SDimitry Andric     if (!BucketChain.Elements[j].Offset)
907480093f4SDimitry Andric       RemainderOffsetInfo[0] = std::make_pair(0, 1);
908480093f4SDimitry Andric     else {
909349cc55cSDimitry Andric       unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
910349cc55cSDimitry Andric                                ->getAPInt()
911349cc55cSDimitry Andric                                .urem(Form);
912480093f4SDimitry Andric       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
913480093f4SDimitry Andric         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
914480093f4SDimitry Andric       else
915480093f4SDimitry Andric         RemainderOffsetInfo[Remainder].second++;
916480093f4SDimitry Andric     }
917480093f4SDimitry Andric   }
918480093f4SDimitry Andric   // Currently we choose the most profitable base as the one which has the max
919480093f4SDimitry Andric   // number of load/store with same remainder.
920480093f4SDimitry Andric   // FIXME: adjust the base selection strategy according to load/store offset
921480093f4SDimitry Andric   // distribution.
922480093f4SDimitry Andric   // For example, if we have one candidate chain for DS form preparation, which
923480093f4SDimitry Andric   // contains following load/stores with different remainders:
924480093f4SDimitry Andric   // 1: 10 load/store whose remainder is 1;
925480093f4SDimitry Andric   // 2: 9 load/store whose remainder is 2;
926480093f4SDimitry Andric   // 3: 1 for remainder 3 and 0 for remainder 0;
927480093f4SDimitry Andric   // Now we will choose the first load/store whose remainder is 1 as base and
928480093f4SDimitry Andric   // adjust all other load/stores according to new base, so we will get 10 DS
929480093f4SDimitry Andric   // form and 10 X form.
930480093f4SDimitry Andric   // But we should be more clever, for this case we could use two bases, one for
931349cc55cSDimitry Andric   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
932349cc55cSDimitry Andric   // 1 X form.
933480093f4SDimitry Andric   unsigned MaxCountRemainder = 0;
934480093f4SDimitry Andric   for (unsigned j = 0; j < (unsigned)Form; j++)
935480093f4SDimitry Andric     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
936480093f4SDimitry Andric         RemainderOffsetInfo[j].second >
937480093f4SDimitry Andric             RemainderOffsetInfo[MaxCountRemainder].second)
938480093f4SDimitry Andric       MaxCountRemainder = j;
939480093f4SDimitry Andric 
940480093f4SDimitry Andric   // Abort when there are too few insts with common base.
941480093f4SDimitry Andric   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
942480093f4SDimitry Andric     return false;
943480093f4SDimitry Andric 
944480093f4SDimitry Andric   // If the first value is most profitable, no needed to adjust BucketChain
945480093f4SDimitry Andric   // elements as they are substracted the first value when collecting.
946480093f4SDimitry Andric   if (MaxCountRemainder == 0)
947480093f4SDimitry Andric     return true;
948480093f4SDimitry Andric 
949480093f4SDimitry Andric   // Adjust load/store to the new chosen base.
950480093f4SDimitry Andric   const SCEV *Offset =
951480093f4SDimitry Andric       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
952480093f4SDimitry Andric   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
953480093f4SDimitry Andric   for (auto &E : BucketChain.Elements) {
954480093f4SDimitry Andric     if (E.Offset)
955480093f4SDimitry Andric       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
956480093f4SDimitry Andric     else
957480093f4SDimitry Andric       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
958480093f4SDimitry Andric   }
959480093f4SDimitry Andric 
960480093f4SDimitry Andric   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
961480093f4SDimitry Andric             BucketChain.Elements[0]);
962480093f4SDimitry Andric   return true;
963480093f4SDimitry Andric }
964480093f4SDimitry Andric 
965480093f4SDimitry Andric // FIXME: implement a more clever base choosing policy.
966480093f4SDimitry Andric // Currently we always choose an exist load/store offset. This maybe lead to
967480093f4SDimitry Andric // suboptimal code sequences. For example, for one DS chain with offsets
968480093f4SDimitry Andric // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
969480093f4SDimitry Andric // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
970480093f4SDimitry Andric // multipler of 4, it cannot be represented by sint16.
971480093f4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
972480093f4SDimitry Andric   // We have a choice now of which instruction's memory operand we use as the
973480093f4SDimitry Andric   // base for the generated PHI. Always picking the first instruction in each
974480093f4SDimitry Andric   // bucket does not work well, specifically because that instruction might
975480093f4SDimitry Andric   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
976480093f4SDimitry Andric   // the choice is somewhat arbitrary, because the backend will happily
977480093f4SDimitry Andric   // generate direct offsets from both the pre-incremented and
978480093f4SDimitry Andric   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
979480093f4SDimitry Andric   // instruction in each bucket, and adjust the recurrence and other offsets
980480093f4SDimitry Andric   // accordingly.
981480093f4SDimitry Andric   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
982480093f4SDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
983480093f4SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::prefetch)
984480093f4SDimitry Andric         continue;
985480093f4SDimitry Andric 
986480093f4SDimitry Andric     // If we'd otherwise pick the first element anyway, there's nothing to do.
987480093f4SDimitry Andric     if (j == 0)
988480093f4SDimitry Andric       break;
989480093f4SDimitry Andric 
990480093f4SDimitry Andric     // If our chosen element has no offset from the base pointer, there's
991480093f4SDimitry Andric     // nothing to do.
992480093f4SDimitry Andric     if (!BucketChain.Elements[j].Offset ||
993349cc55cSDimitry Andric         cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
994480093f4SDimitry Andric       break;
995480093f4SDimitry Andric 
996480093f4SDimitry Andric     const SCEV *Offset = BucketChain.Elements[j].Offset;
997480093f4SDimitry Andric     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
998480093f4SDimitry Andric     for (auto &E : BucketChain.Elements) {
999480093f4SDimitry Andric       if (E.Offset)
1000480093f4SDimitry Andric         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
1001480093f4SDimitry Andric       else
1002480093f4SDimitry Andric         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
1003480093f4SDimitry Andric     }
1004480093f4SDimitry Andric 
1005480093f4SDimitry Andric     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
1006480093f4SDimitry Andric     break;
1007480093f4SDimitry Andric   }
1008480093f4SDimitry Andric   return true;
1009480093f4SDimitry Andric }
1010480093f4SDimitry Andric 
1011349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStores(
1012349cc55cSDimitry Andric     Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
1013349cc55cSDimitry Andric     PrepForm Form) {
1014480093f4SDimitry Andric   bool MadeChange = false;
1015349cc55cSDimitry Andric 
1016480093f4SDimitry Andric   const SCEVAddRecExpr *BasePtrSCEV =
1017480093f4SDimitry Andric       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
1018480093f4SDimitry Andric   if (!BasePtrSCEV->isAffine())
1019480093f4SDimitry Andric     return MadeChange;
1020480093f4SDimitry Andric 
1021480093f4SDimitry Andric   BasicBlock *Header = L->getHeader();
1022349cc55cSDimitry Andric   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
1023349cc55cSDimitry Andric                      "loopprepare-formrewrite");
1024*fcaf7f86SDimitry Andric   if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
1025*fcaf7f86SDimitry Andric     return MadeChange;
1026*fcaf7f86SDimitry Andric 
1027*fcaf7f86SDimitry Andric   SmallPtrSet<Value *, 16> DeletedPtrs;
1028480093f4SDimitry Andric 
1029349cc55cSDimitry Andric   // For some DS form load/store instructions, it can also be an update form,
1030349cc55cSDimitry Andric   // if the stride is constant and is a multipler of 4. Use update form if
1031349cc55cSDimitry Andric   // prefer it.
1032349cc55cSDimitry Andric   bool CanPreInc = (Form == UpdateForm ||
1033349cc55cSDimitry Andric                     ((Form == DSForm) &&
1034349cc55cSDimitry Andric                      isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
1035349cc55cSDimitry Andric                      !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
1036349cc55cSDimitry Andric                           ->getAPInt()
1037349cc55cSDimitry Andric                           .urem(4) &&
1038349cc55cSDimitry Andric                      PreferUpdateForm));
1039480093f4SDimitry Andric 
1040349cc55cSDimitry Andric   std::pair<Instruction *, Instruction *> Base =
1041349cc55cSDimitry Andric       rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
1042349cc55cSDimitry Andric                      CanPreInc, Form, SCEVE, DeletedPtrs);
1043480093f4SDimitry Andric 
1044349cc55cSDimitry Andric   if (!Base.first || !Base.second)
1045349cc55cSDimitry Andric     return MadeChange;
1046349cc55cSDimitry Andric 
1047349cc55cSDimitry Andric   // Keep track of the replacement pointer values we've inserted so that we
1048349cc55cSDimitry Andric   // don't generate more pointer values than necessary.
1049349cc55cSDimitry Andric   SmallPtrSet<Value *, 16> NewPtrs;
1050349cc55cSDimitry Andric   NewPtrs.insert(Base.first);
1051349cc55cSDimitry Andric 
1052349cc55cSDimitry Andric   for (auto I = std::next(BucketChain.Elements.begin()),
1053349cc55cSDimitry Andric        IE = BucketChain.Elements.end(); I != IE; ++I) {
1054349cc55cSDimitry Andric     Value *Ptr = getPointerOperandAndType(I->Instr);
1055349cc55cSDimitry Andric     assert(Ptr && "No pointer operand");
1056349cc55cSDimitry Andric     if (NewPtrs.count(Ptr))
1057480093f4SDimitry Andric       continue;
1058480093f4SDimitry Andric 
1059349cc55cSDimitry Andric     Instruction *NewPtr = rewriteForBucketElement(
1060349cc55cSDimitry Andric         Base, *I,
1061349cc55cSDimitry Andric         I->Offset ? cast<SCEVConstant>(I->Offset)->getValue() : nullptr,
1062349cc55cSDimitry Andric         DeletedPtrs);
1063349cc55cSDimitry Andric     assert(NewPtr && "wrong rewrite!\n");
1064349cc55cSDimitry Andric     NewPtrs.insert(NewPtr);
1065480093f4SDimitry Andric   }
1066480093f4SDimitry Andric 
1067e8d8bef9SDimitry Andric   // Clear the rewriter cache, because values that are in the rewriter's cache
1068e8d8bef9SDimitry Andric   // can be deleted below, causing the AssertingVH in the cache to trigger.
1069e8d8bef9SDimitry Andric   SCEVE.clear();
1070e8d8bef9SDimitry Andric 
1071349cc55cSDimitry Andric   for (auto *Ptr : DeletedPtrs) {
1072480093f4SDimitry Andric     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
1073480093f4SDimitry Andric       BBChanged.insert(IDel->getParent());
1074480093f4SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
1075480093f4SDimitry Andric   }
1076480093f4SDimitry Andric 
1077480093f4SDimitry Andric   MadeChange = true;
1078480093f4SDimitry Andric 
1079480093f4SDimitry Andric   SuccPrepCount++;
1080480093f4SDimitry Andric 
1081480093f4SDimitry Andric   if (Form == DSForm && !CanPreInc)
1082480093f4SDimitry Andric     DSFormChainRewritten++;
1083480093f4SDimitry Andric   else if (Form == DQForm)
1084480093f4SDimitry Andric     DQFormChainRewritten++;
1085480093f4SDimitry Andric   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
1086480093f4SDimitry Andric     UpdFormChainRewritten++;
1087480093f4SDimitry Andric 
1088480093f4SDimitry Andric   return MadeChange;
1089480093f4SDimitry Andric }
1090480093f4SDimitry Andric 
1091480093f4SDimitry Andric bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
1092480093f4SDimitry Andric                                        SmallVector<Bucket, 16> &Buckets) {
1093480093f4SDimitry Andric   bool MadeChange = false;
1094480093f4SDimitry Andric   if (Buckets.empty())
1095480093f4SDimitry Andric     return MadeChange;
1096480093f4SDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
1097480093f4SDimitry Andric   for (auto &Bucket : Buckets)
1098480093f4SDimitry Andric     // The base address of each bucket is transformed into a phi and the others
1099480093f4SDimitry Andric     // are rewritten based on new base.
1100480093f4SDimitry Andric     if (prepareBaseForUpdateFormChain(Bucket))
1101480093f4SDimitry Andric       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
1102480093f4SDimitry Andric 
1103480093f4SDimitry Andric   if (MadeChange)
1104349cc55cSDimitry Andric     for (auto *BB : BBChanged)
1105480093f4SDimitry Andric       DeleteDeadPHIs(BB);
1106480093f4SDimitry Andric   return MadeChange;
1107480093f4SDimitry Andric }
1108480093f4SDimitry Andric 
1109349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L,
1110349cc55cSDimitry Andric                                         SmallVector<Bucket, 16> &Buckets,
1111349cc55cSDimitry Andric                                         PrepForm Form) {
1112480093f4SDimitry Andric   bool MadeChange = false;
1113480093f4SDimitry Andric 
1114480093f4SDimitry Andric   if (Buckets.empty())
1115480093f4SDimitry Andric     return MadeChange;
1116480093f4SDimitry Andric 
1117480093f4SDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
1118480093f4SDimitry Andric   for (auto &Bucket : Buckets) {
1119480093f4SDimitry Andric     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
1120480093f4SDimitry Andric       continue;
1121480093f4SDimitry Andric     if (prepareBaseForDispFormChain(Bucket, Form))
1122480093f4SDimitry Andric       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
1123480093f4SDimitry Andric   }
1124480093f4SDimitry Andric 
1125480093f4SDimitry Andric   if (MadeChange)
1126349cc55cSDimitry Andric     for (auto *BB : BBChanged)
1127480093f4SDimitry Andric       DeleteDeadPHIs(BB);
1128480093f4SDimitry Andric   return MadeChange;
1129480093f4SDimitry Andric }
1130480093f4SDimitry Andric 
1131349cc55cSDimitry Andric // Find the loop invariant increment node for SCEV BasePtrIncSCEV.
1132349cc55cSDimitry Andric // bb.loop.preheader:
1133349cc55cSDimitry Andric //   %start = ...
1134349cc55cSDimitry Andric // bb.loop.body:
1135349cc55cSDimitry Andric //   %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ]
1136349cc55cSDimitry Andric //   ...
1137349cc55cSDimitry Andric //   %add = add %phinode, %inc  ; %inc is what we want to get.
1138349cc55cSDimitry Andric //
1139349cc55cSDimitry Andric Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
1140349cc55cSDimitry Andric                                            const SCEV *BasePtrIncSCEV) {
1141349cc55cSDimitry Andric   // If the increment is a constant, no definition is needed.
1142349cc55cSDimitry Andric   // Return the value directly.
1143349cc55cSDimitry Andric   if (isa<SCEVConstant>(BasePtrIncSCEV))
1144349cc55cSDimitry Andric     return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
1145349cc55cSDimitry Andric 
1146349cc55cSDimitry Andric   if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
1147349cc55cSDimitry Andric     return nullptr;
1148349cc55cSDimitry Andric 
1149349cc55cSDimitry Andric   BasicBlock *BB = MemI->getParent();
1150349cc55cSDimitry Andric   if (!BB)
1151349cc55cSDimitry Andric     return nullptr;
1152349cc55cSDimitry Andric 
1153349cc55cSDimitry Andric   BasicBlock *LatchBB = L->getLoopLatch();
1154349cc55cSDimitry Andric 
1155349cc55cSDimitry Andric   if (!LatchBB)
1156349cc55cSDimitry Andric     return nullptr;
1157349cc55cSDimitry Andric 
1158349cc55cSDimitry Andric   // Run through the PHIs and check their operands to find valid representation
1159349cc55cSDimitry Andric   // for the increment SCEV.
1160349cc55cSDimitry Andric   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1161349cc55cSDimitry Andric   for (auto &CurrentPHI : PHIIter) {
1162349cc55cSDimitry Andric     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1163349cc55cSDimitry Andric     if (!CurrentPHINode)
1164349cc55cSDimitry Andric       continue;
1165349cc55cSDimitry Andric 
1166349cc55cSDimitry Andric     if (!SE->isSCEVable(CurrentPHINode->getType()))
1167349cc55cSDimitry Andric       continue;
1168349cc55cSDimitry Andric 
1169349cc55cSDimitry Andric     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1170349cc55cSDimitry Andric 
1171349cc55cSDimitry Andric     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1172349cc55cSDimitry Andric     if (!PHIBasePtrSCEV)
1173349cc55cSDimitry Andric       continue;
1174349cc55cSDimitry Andric 
1175349cc55cSDimitry Andric     const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
1176349cc55cSDimitry Andric 
1177349cc55cSDimitry Andric     if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
1178349cc55cSDimitry Andric       continue;
1179349cc55cSDimitry Andric 
1180349cc55cSDimitry Andric     // Get the incoming value from the loop latch and check if the value has
1181349cc55cSDimitry Andric     // the add form with the required increment.
1182349cc55cSDimitry Andric     if (Instruction *I = dyn_cast<Instruction>(
1183349cc55cSDimitry Andric             CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1184349cc55cSDimitry Andric       Value *StrippedBaseI = I;
1185349cc55cSDimitry Andric       while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1186349cc55cSDimitry Andric         StrippedBaseI = BC->getOperand(0);
1187349cc55cSDimitry Andric 
1188349cc55cSDimitry Andric       Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1189349cc55cSDimitry Andric       if (!StrippedI)
1190349cc55cSDimitry Andric         continue;
1191349cc55cSDimitry Andric 
1192349cc55cSDimitry Andric       // LSR pass may add a getelementptr instruction to do the loop increment,
1193349cc55cSDimitry Andric       // also search in that getelementptr instruction.
1194349cc55cSDimitry Andric       if (StrippedI->getOpcode() == Instruction::Add ||
1195349cc55cSDimitry Andric           (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1196349cc55cSDimitry Andric            StrippedI->getNumOperands() == 2)) {
1197349cc55cSDimitry Andric         if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1198349cc55cSDimitry Andric           return StrippedI->getOperand(0);
1199349cc55cSDimitry Andric         if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1200349cc55cSDimitry Andric           return StrippedI->getOperand(1);
1201349cc55cSDimitry Andric       }
1202349cc55cSDimitry Andric     }
1203349cc55cSDimitry Andric   }
1204349cc55cSDimitry Andric   return nullptr;
1205349cc55cSDimitry Andric }
1206349cc55cSDimitry Andric 
1207480093f4SDimitry Andric // In order to prepare for the preferred instruction form, a PHI is added.
1208480093f4SDimitry Andric // This function will check to see if that PHI already exists and will return
1209480093f4SDimitry Andric // true if it found an existing PHI with the matched start and increment as the
1210480093f4SDimitry Andric // one we wanted to create.
1211480093f4SDimitry Andric bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
1212480093f4SDimitry Andric                                            const SCEV *BasePtrStartSCEV,
1213349cc55cSDimitry Andric                                            const SCEV *BasePtrIncSCEV,
1214349cc55cSDimitry Andric                                            PrepForm Form) {
1215480093f4SDimitry Andric   BasicBlock *BB = MemI->getParent();
1216480093f4SDimitry Andric   if (!BB)
1217480093f4SDimitry Andric     return false;
1218480093f4SDimitry Andric 
1219480093f4SDimitry Andric   BasicBlock *PredBB = L->getLoopPredecessor();
1220480093f4SDimitry Andric   BasicBlock *LatchBB = L->getLoopLatch();
1221480093f4SDimitry Andric 
1222480093f4SDimitry Andric   if (!PredBB || !LatchBB)
1223480093f4SDimitry Andric     return false;
1224480093f4SDimitry Andric 
1225480093f4SDimitry Andric   // Run through the PHIs and see if we have some that looks like a preparation
1226480093f4SDimitry Andric   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1227480093f4SDimitry Andric   for (auto & CurrentPHI : PHIIter) {
1228480093f4SDimitry Andric     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1229480093f4SDimitry Andric     if (!CurrentPHINode)
1230480093f4SDimitry Andric       continue;
1231480093f4SDimitry Andric 
1232480093f4SDimitry Andric     if (!SE->isSCEVable(CurrentPHINode->getType()))
1233480093f4SDimitry Andric       continue;
1234480093f4SDimitry Andric 
1235480093f4SDimitry Andric     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1236480093f4SDimitry Andric 
1237480093f4SDimitry Andric     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1238480093f4SDimitry Andric     if (!PHIBasePtrSCEV)
1239480093f4SDimitry Andric       continue;
1240480093f4SDimitry Andric 
1241480093f4SDimitry Andric     const SCEVConstant *PHIBasePtrIncSCEV =
1242480093f4SDimitry Andric       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
1243480093f4SDimitry Andric     if (!PHIBasePtrIncSCEV)
1244480093f4SDimitry Andric       continue;
1245480093f4SDimitry Andric 
1246480093f4SDimitry Andric     if (CurrentPHINode->getNumIncomingValues() == 2) {
1247480093f4SDimitry Andric       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
1248480093f4SDimitry Andric            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
1249480093f4SDimitry Andric           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
1250480093f4SDimitry Andric            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
1251480093f4SDimitry Andric         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
1252480093f4SDimitry Andric           // The existing PHI (CurrentPHINode) has the same start and increment
1253480093f4SDimitry Andric           // as the PHI that we wanted to create.
1254349cc55cSDimitry Andric           if ((Form == UpdateForm || Form == ChainCommoning ) &&
1255480093f4SDimitry Andric               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
1256480093f4SDimitry Andric             ++PHINodeAlreadyExistsUpdate;
1257480093f4SDimitry Andric             return true;
1258480093f4SDimitry Andric           }
1259480093f4SDimitry Andric           if (Form == DSForm || Form == DQForm) {
1260480093f4SDimitry Andric             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
1261480093f4SDimitry Andric                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
1262480093f4SDimitry Andric             if (Diff && !Diff->getAPInt().urem(Form)) {
1263480093f4SDimitry Andric               if (Form == DSForm)
1264480093f4SDimitry Andric                 ++PHINodeAlreadyExistsDS;
1265480093f4SDimitry Andric               else
1266480093f4SDimitry Andric                 ++PHINodeAlreadyExistsDQ;
1267480093f4SDimitry Andric               return true;
1268480093f4SDimitry Andric             }
1269480093f4SDimitry Andric           }
1270480093f4SDimitry Andric         }
1271480093f4SDimitry Andric       }
1272480093f4SDimitry Andric     }
1273480093f4SDimitry Andric   }
1274480093f4SDimitry Andric   return false;
1275480093f4SDimitry Andric }
1276480093f4SDimitry Andric 
1277480093f4SDimitry Andric bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
1278480093f4SDimitry Andric   bool MadeChange = false;
1279480093f4SDimitry Andric 
1280480093f4SDimitry Andric   // Only prep. the inner-most loop
1281e8d8bef9SDimitry Andric   if (!L->isInnermost())
1282480093f4SDimitry Andric     return MadeChange;
1283480093f4SDimitry Andric 
1284480093f4SDimitry Andric   // Return if already done enough preparation.
1285480093f4SDimitry Andric   if (SuccPrepCount >= MaxVarsPrep)
1286480093f4SDimitry Andric     return MadeChange;
1287480093f4SDimitry Andric 
1288480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
1289480093f4SDimitry Andric 
1290480093f4SDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
1291480093f4SDimitry Andric   // If there is no loop predecessor, or the loop predecessor's terminator
1292480093f4SDimitry Andric   // returns a value (which might contribute to determining the loop's
1293480093f4SDimitry Andric   // iteration space), insert a new preheader for the loop.
1294480093f4SDimitry Andric   if (!LoopPredecessor ||
1295480093f4SDimitry Andric       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
1296480093f4SDimitry Andric     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
1297480093f4SDimitry Andric     if (LoopPredecessor)
1298480093f4SDimitry Andric       MadeChange = true;
1299480093f4SDimitry Andric   }
1300480093f4SDimitry Andric   if (!LoopPredecessor) {
1301480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
1302480093f4SDimitry Andric     return MadeChange;
1303480093f4SDimitry Andric   }
1304480093f4SDimitry Andric   // Check if a load/store has update form. This lambda is used by function
1305480093f4SDimitry Andric   // collectCandidates which can collect candidates for types defined by lambda.
1306349cc55cSDimitry Andric   auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1307fe6060f1SDimitry Andric                                    const Type *PointerElementType) {
1308480093f4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1309480093f4SDimitry Andric     // There are no update forms for Altivec vector load/stores.
1310fe6060f1SDimitry Andric     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
1311480093f4SDimitry Andric       return false;
1312e8d8bef9SDimitry Andric     // There are no update forms for P10 lxvp/stxvp intrinsic.
1313e8d8bef9SDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
1314e8d8bef9SDimitry Andric     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1315e8d8bef9SDimitry Andric                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
1316e8d8bef9SDimitry Andric       return false;
1317480093f4SDimitry Andric     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
1318480093f4SDimitry Andric     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
1319480093f4SDimitry Andric     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
1320480093f4SDimitry Andric     // useless and possible to break some original well-form addressing mode
1321480093f4SDimitry Andric     // to make this pre-inc prep for it.
1322fe6060f1SDimitry Andric     if (PointerElementType->isIntegerTy(64)) {
1323480093f4SDimitry Andric       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
1324480093f4SDimitry Andric       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
1325480093f4SDimitry Andric       if (!LARSCEV || LARSCEV->getLoop() != L)
1326480093f4SDimitry Andric         return false;
1327480093f4SDimitry Andric       if (const SCEVConstant *StepConst =
1328480093f4SDimitry Andric               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
1329480093f4SDimitry Andric         const APInt &ConstInt = StepConst->getValue()->getValue();
1330480093f4SDimitry Andric         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
1331480093f4SDimitry Andric           return false;
1332480093f4SDimitry Andric       }
1333480093f4SDimitry Andric     }
1334480093f4SDimitry Andric     return true;
1335480093f4SDimitry Andric   };
1336480093f4SDimitry Andric 
1337480093f4SDimitry Andric   // Check if a load/store has DS form.
1338349cc55cSDimitry Andric   auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1339fe6060f1SDimitry Andric                               const Type *PointerElementType) {
1340480093f4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1341480093f4SDimitry Andric     if (isa<IntrinsicInst>(I))
1342480093f4SDimitry Andric       return false;
1343480093f4SDimitry Andric     return (PointerElementType->isIntegerTy(64)) ||
1344480093f4SDimitry Andric            (PointerElementType->isFloatTy()) ||
1345480093f4SDimitry Andric            (PointerElementType->isDoubleTy()) ||
1346480093f4SDimitry Andric            (PointerElementType->isIntegerTy(32) &&
1347480093f4SDimitry Andric             llvm::any_of(I->users(),
1348480093f4SDimitry Andric                          [](const User *U) { return isa<SExtInst>(U); }));
1349480093f4SDimitry Andric   };
1350480093f4SDimitry Andric 
1351480093f4SDimitry Andric   // Check if a load/store has DQ form.
1352349cc55cSDimitry Andric   auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1353fe6060f1SDimitry Andric                                const Type *PointerElementType) {
1354480093f4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1355e8d8bef9SDimitry Andric     // Check if it is a P10 lxvp/stxvp intrinsic.
1356e8d8bef9SDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
1357e8d8bef9SDimitry Andric     if (II)
1358e8d8bef9SDimitry Andric       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1359e8d8bef9SDimitry Andric              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
1360e8d8bef9SDimitry Andric     // Check if it is a P9 vector load/store.
1361fe6060f1SDimitry Andric     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
1362480093f4SDimitry Andric   };
1363480093f4SDimitry Andric 
1364349cc55cSDimitry Andric   // Check if a load/store is candidate for chain commoning.
1365349cc55cSDimitry Andric   // If the SCEV is only with one ptr operand in its start, we can use that
1366349cc55cSDimitry Andric   // start as a chain separator. Mark this load/store as a candidate.
1367349cc55cSDimitry Andric   auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
1368349cc55cSDimitry Andric                                        const Type *PointerElementType) {
1369349cc55cSDimitry Andric     const SCEVAddRecExpr *ARSCEV =
1370349cc55cSDimitry Andric         cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
1371349cc55cSDimitry Andric     if (!ARSCEV)
1372349cc55cSDimitry Andric       return false;
1373349cc55cSDimitry Andric 
1374349cc55cSDimitry Andric     if (!ARSCEV->isAffine())
1375349cc55cSDimitry Andric       return false;
1376349cc55cSDimitry Andric 
1377349cc55cSDimitry Andric     const SCEV *Start = ARSCEV->getStart();
1378349cc55cSDimitry Andric 
1379349cc55cSDimitry Andric     // A single pointer. We can treat it as offset 0.
1380349cc55cSDimitry Andric     if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
1381349cc55cSDimitry Andric       return true;
1382349cc55cSDimitry Andric 
1383349cc55cSDimitry Andric     const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
1384349cc55cSDimitry Andric 
1385349cc55cSDimitry Andric     // We need a SCEVAddExpr to include both base and offset.
1386349cc55cSDimitry Andric     if (!ASCEV)
1387349cc55cSDimitry Andric       return false;
1388349cc55cSDimitry Andric 
1389349cc55cSDimitry Andric     // Make sure there is only one pointer operand(base) and all other operands
1390349cc55cSDimitry Andric     // are integer type.
1391349cc55cSDimitry Andric     bool SawPointer = false;
1392349cc55cSDimitry Andric     for (const SCEV *Op : ASCEV->operands()) {
1393349cc55cSDimitry Andric       if (Op->getType()->isPointerTy()) {
1394349cc55cSDimitry Andric         if (SawPointer)
1395349cc55cSDimitry Andric           return false;
1396349cc55cSDimitry Andric         SawPointer = true;
1397349cc55cSDimitry Andric       } else if (!Op->getType()->isIntegerTy())
1398349cc55cSDimitry Andric         return false;
1399349cc55cSDimitry Andric     }
1400349cc55cSDimitry Andric 
1401349cc55cSDimitry Andric     return SawPointer;
1402349cc55cSDimitry Andric   };
1403349cc55cSDimitry Andric 
1404349cc55cSDimitry Andric   // Check if the diff is a constant type. This is used for update/DS/DQ form
1405349cc55cSDimitry Andric   // preparation.
1406349cc55cSDimitry Andric   auto isValidConstantDiff = [](const SCEV *Diff) {
1407349cc55cSDimitry Andric     return dyn_cast<SCEVConstant>(Diff) != nullptr;
1408349cc55cSDimitry Andric   };
1409349cc55cSDimitry Andric 
1410349cc55cSDimitry Andric   // Make sure the diff between the base and new candidate is required type.
1411349cc55cSDimitry Andric   // This is used for chain commoning preparation.
1412349cc55cSDimitry Andric   auto isValidChainCommoningDiff = [](const SCEV *Diff) {
1413349cc55cSDimitry Andric     assert(Diff && "Invalid Diff!\n");
1414349cc55cSDimitry Andric 
1415349cc55cSDimitry Andric     // Don't mess up previous dform prepare.
1416349cc55cSDimitry Andric     if (isa<SCEVConstant>(Diff))
1417349cc55cSDimitry Andric       return false;
1418349cc55cSDimitry Andric 
1419349cc55cSDimitry Andric     // A single integer type offset.
1420349cc55cSDimitry Andric     if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
1421349cc55cSDimitry Andric       return true;
1422349cc55cSDimitry Andric 
1423349cc55cSDimitry Andric     const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
1424349cc55cSDimitry Andric     if (!ADiff)
1425349cc55cSDimitry Andric       return false;
1426349cc55cSDimitry Andric 
1427349cc55cSDimitry Andric     for (const SCEV *Op : ADiff->operands())
1428349cc55cSDimitry Andric       if (!Op->getType()->isIntegerTy())
1429349cc55cSDimitry Andric         return false;
1430349cc55cSDimitry Andric 
1431349cc55cSDimitry Andric     return true;
1432349cc55cSDimitry Andric   };
1433349cc55cSDimitry Andric 
1434349cc55cSDimitry Andric   HasCandidateForPrepare = false;
1435349cc55cSDimitry Andric 
1436349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
1437349cc55cSDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for update
1438349cc55cSDimitry Andric   // form.
1439349cc55cSDimitry Andric   SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
1440349cc55cSDimitry Andric       L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
1441480093f4SDimitry Andric 
1442480093f4SDimitry Andric   // Prepare for update form.
1443480093f4SDimitry Andric   if (!UpdateFormBuckets.empty())
1444480093f4SDimitry Andric     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
1445349cc55cSDimitry Andric   else if (!HasCandidateForPrepare) {
1446349cc55cSDimitry Andric     LLVM_DEBUG(
1447349cc55cSDimitry Andric         dbgs()
1448349cc55cSDimitry Andric         << "No prepare candidates found, stop praparation for current loop!\n");
1449349cc55cSDimitry Andric     // If no candidate for preparing, return early.
1450349cc55cSDimitry Andric     return MadeChange;
1451349cc55cSDimitry Andric   }
1452480093f4SDimitry Andric 
1453349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
1454480093f4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for DS
1455480093f4SDimitry Andric   // form.
1456349cc55cSDimitry Andric   SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
1457349cc55cSDimitry Andric       L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
1458480093f4SDimitry Andric 
1459480093f4SDimitry Andric   // Prepare for DS form.
1460480093f4SDimitry Andric   if (!DSFormBuckets.empty())
1461480093f4SDimitry Andric     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
1462480093f4SDimitry Andric 
1463349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
1464480093f4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for DQ
1465480093f4SDimitry Andric   // form.
1466349cc55cSDimitry Andric   SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
1467349cc55cSDimitry Andric       L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
1468480093f4SDimitry Andric 
1469480093f4SDimitry Andric   // Prepare for DQ form.
1470480093f4SDimitry Andric   if (!DQFormBuckets.empty())
1471480093f4SDimitry Andric     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
1472480093f4SDimitry Andric 
1473349cc55cSDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for chain
1474349cc55cSDimitry Andric   // commoning. With chain commoning, we reuse offsets between the chains, so
1475349cc55cSDimitry Andric   // the register pressure will be reduced.
1476349cc55cSDimitry Andric   if (!EnableChainCommoning) {
1477349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
1478349cc55cSDimitry Andric     return MadeChange;
1479349cc55cSDimitry Andric   }
1480349cc55cSDimitry Andric 
1481349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
1482349cc55cSDimitry Andric   SmallVector<Bucket, 16> Buckets =
1483349cc55cSDimitry Andric       collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
1484349cc55cSDimitry Andric                         MaxVarsChainCommon);
1485349cc55cSDimitry Andric 
1486349cc55cSDimitry Andric   // Prepare for chain commoning.
1487349cc55cSDimitry Andric   if (!Buckets.empty())
1488349cc55cSDimitry Andric     MadeChange |= chainCommoning(L, Buckets);
1489349cc55cSDimitry Andric 
1490480093f4SDimitry Andric   return MadeChange;
1491480093f4SDimitry Andric }
1492