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>
111bdd1243dSDimitry Andric #include <cmath>
112480093f4SDimitry Andric #include <iterator>
113480093f4SDimitry Andric #include <utility>
114480093f4SDimitry Andric 
115fe6060f1SDimitry Andric #define DEBUG_TYPE "ppc-loop-instr-form-prep"
116fe6060f1SDimitry Andric 
117480093f4SDimitry Andric using namespace llvm;
118480093f4SDimitry Andric 
119349cc55cSDimitry Andric static cl::opt<unsigned>
120349cc55cSDimitry Andric     MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
121349cc55cSDimitry Andric                 cl::desc("Potential common base number threshold per function "
122349cc55cSDimitry Andric                          "for PPC loop prep"));
123480093f4SDimitry Andric 
124480093f4SDimitry Andric static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
125480093f4SDimitry Andric                                  cl::init(true), cl::Hidden,
126480093f4SDimitry Andric   cl::desc("prefer update form when ds form is also a update form"));
127480093f4SDimitry Andric 
128349cc55cSDimitry Andric static cl::opt<bool> EnableUpdateFormForNonConstInc(
129349cc55cSDimitry Andric     "ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden,
130349cc55cSDimitry Andric     cl::desc("prepare update form when the load/store increment is a loop "
131349cc55cSDimitry Andric              "invariant non-const value."));
132349cc55cSDimitry Andric 
133349cc55cSDimitry Andric static cl::opt<bool> EnableChainCommoning(
134349cc55cSDimitry Andric     "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
135349cc55cSDimitry Andric     cl::desc("Enable chain commoning in PPC loop prepare pass."));
136349cc55cSDimitry Andric 
137480093f4SDimitry Andric // Sum of following 3 per loop thresholds for all loops can not be larger
138480093f4SDimitry Andric // than MaxVarsPrep.
139e8d8bef9SDimitry Andric // now the thresholds for each kind prep are exterimental values on Power9.
140480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
141480093f4SDimitry Andric                                  cl::Hidden, cl::init(3),
142480093f4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
143480093f4SDimitry Andric            "form"));
144480093f4SDimitry Andric 
145480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
146480093f4SDimitry Andric                                  cl::Hidden, cl::init(3),
147480093f4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
148480093f4SDimitry Andric 
149480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
150e8d8bef9SDimitry Andric                                  cl::Hidden, cl::init(8),
151480093f4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
152480093f4SDimitry Andric 
153349cc55cSDimitry Andric // Commoning chain will reduce the register pressure, so we don't consider about
154349cc55cSDimitry Andric // the PHI nodes number.
155349cc55cSDimitry Andric // But commoning chain will increase the addi/add number in the loop and also
156349cc55cSDimitry Andric // increase loop ILP. Maximum chain number should be same with hardware
157349cc55cSDimitry Andric // IssueWidth, because we won't benefit from ILP if the parallel chains number
158349cc55cSDimitry Andric // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so
159349cc55cSDimitry Andric // there would be 4 buckets at most on P9(IssueWidth is 8).
160349cc55cSDimitry Andric static cl::opt<unsigned> MaxVarsChainCommon(
161349cc55cSDimitry Andric     "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
162349cc55cSDimitry Andric     cl::desc("Bucket number per loop for PPC loop chain common"));
163480093f4SDimitry Andric 
164480093f4SDimitry Andric // If would not be profitable if the common base has only one load/store, ISEL
165480093f4SDimitry Andric // should already be able to choose best load/store form based on offset for
166480093f4SDimitry Andric // single load/store. Set minimal profitable value default to 2 and make it as
167480093f4SDimitry Andric // an option.
168480093f4SDimitry Andric static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
169480093f4SDimitry Andric                                     cl::Hidden, cl::init(2),
170480093f4SDimitry Andric   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
171480093f4SDimitry Andric            "preparation"));
172480093f4SDimitry Andric 
173349cc55cSDimitry Andric static cl::opt<unsigned> ChainCommonPrepMinThreshold(
174349cc55cSDimitry Andric     "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
175349cc55cSDimitry Andric     cl::desc("Minimal common base load/store instructions triggering chain "
176349cc55cSDimitry Andric              "commoning preparation. Must be not smaller than 4"));
177349cc55cSDimitry Andric 
178480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
179480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
180480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
181480093f4SDimitry Andric STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
182480093f4SDimitry Andric STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
183480093f4SDimitry Andric STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
184349cc55cSDimitry Andric STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
185480093f4SDimitry Andric 
186480093f4SDimitry Andric namespace {
187480093f4SDimitry Andric   struct BucketElement {
BucketElement__anon54712cd50111::BucketElement188349cc55cSDimitry Andric     BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
BucketElement__anon54712cd50111::BucketElement189480093f4SDimitry Andric     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
190480093f4SDimitry Andric 
191349cc55cSDimitry Andric     const SCEV *Offset;
192480093f4SDimitry Andric     Instruction *Instr;
193480093f4SDimitry Andric   };
194480093f4SDimitry Andric 
195480093f4SDimitry Andric   struct Bucket {
Bucket__anon54712cd50111::Bucket196349cc55cSDimitry Andric     Bucket(const SCEV *B, Instruction *I)
197349cc55cSDimitry Andric         : BaseSCEV(B), Elements(1, BucketElement(I)) {
198349cc55cSDimitry Andric       ChainSize = 0;
199349cc55cSDimitry Andric     }
200480093f4SDimitry Andric 
201349cc55cSDimitry Andric     // The base of the whole bucket.
202480093f4SDimitry Andric     const SCEV *BaseSCEV;
203349cc55cSDimitry Andric 
204349cc55cSDimitry Andric     // All elements in the bucket. In the bucket, the element with the BaseSCEV
205349cc55cSDimitry Andric     // has no offset and all other elements are stored as offsets to the
206349cc55cSDimitry Andric     // BaseSCEV.
207480093f4SDimitry Andric     SmallVector<BucketElement, 16> Elements;
208349cc55cSDimitry Andric 
209349cc55cSDimitry Andric     // The potential chains size. This is used for chain commoning only.
210349cc55cSDimitry Andric     unsigned ChainSize;
211349cc55cSDimitry Andric 
212349cc55cSDimitry Andric     // The base for each potential chain. This is used for chain commoning only.
213349cc55cSDimitry Andric     SmallVector<BucketElement, 16> ChainBases;
214480093f4SDimitry Andric   };
215480093f4SDimitry Andric 
216480093f4SDimitry Andric   // "UpdateForm" is not a real PPC instruction form, it stands for dform
217480093f4SDimitry Andric   // load/store with update like ldu/stdu, or Prefetch intrinsic.
218480093f4SDimitry Andric   // For DS form instructions, their displacements must be multiple of 4.
219480093f4SDimitry Andric   // For DQ form instructions, their displacements must be multiple of 16.
220349cc55cSDimitry Andric   enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
221480093f4SDimitry Andric 
222480093f4SDimitry Andric   class PPCLoopInstrFormPrep : public FunctionPass {
223480093f4SDimitry Andric   public:
224480093f4SDimitry Andric     static char ID; // Pass ID, replacement for typeid
225480093f4SDimitry Andric 
PPCLoopInstrFormPrep()226480093f4SDimitry Andric     PPCLoopInstrFormPrep() : FunctionPass(ID) {
227480093f4SDimitry Andric       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
228480093f4SDimitry Andric     }
229480093f4SDimitry Andric 
PPCLoopInstrFormPrep(PPCTargetMachine & TM)230480093f4SDimitry Andric     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
231480093f4SDimitry Andric       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
232480093f4SDimitry Andric     }
233480093f4SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const234480093f4SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
235480093f4SDimitry Andric       AU.addPreserved<DominatorTreeWrapperPass>();
236480093f4SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
237480093f4SDimitry Andric       AU.addPreserved<LoopInfoWrapperPass>();
238480093f4SDimitry Andric       AU.addRequired<ScalarEvolutionWrapperPass>();
239480093f4SDimitry Andric     }
240480093f4SDimitry Andric 
241480093f4SDimitry Andric     bool runOnFunction(Function &F) override;
242480093f4SDimitry Andric 
243480093f4SDimitry Andric   private:
244480093f4SDimitry Andric     PPCTargetMachine *TM = nullptr;
245480093f4SDimitry Andric     const PPCSubtarget *ST;
246480093f4SDimitry Andric     DominatorTree *DT;
247480093f4SDimitry Andric     LoopInfo *LI;
248480093f4SDimitry Andric     ScalarEvolution *SE;
249480093f4SDimitry Andric     bool PreserveLCSSA;
250349cc55cSDimitry Andric     bool HasCandidateForPrepare;
251480093f4SDimitry Andric 
252480093f4SDimitry Andric     /// Successful preparation number for Update/DS/DQ form in all inner most
253480093f4SDimitry Andric     /// loops. One successful preparation will put one common base out of loop,
254480093f4SDimitry Andric     /// this may leads to register presure like LICM does.
255480093f4SDimitry Andric     /// Make sure total preparation number can be controlled by option.
256480093f4SDimitry Andric     unsigned SuccPrepCount;
257480093f4SDimitry Andric 
258480093f4SDimitry Andric     bool runOnLoop(Loop *L);
259480093f4SDimitry Andric 
260480093f4SDimitry Andric     /// Check if required PHI node is already exist in Loop \p L.
261480093f4SDimitry Andric     bool alreadyPrepared(Loop *L, Instruction *MemI,
262480093f4SDimitry Andric                          const SCEV *BasePtrStartSCEV,
263349cc55cSDimitry Andric                          const SCEV *BasePtrIncSCEV, PrepForm Form);
264349cc55cSDimitry Andric 
265349cc55cSDimitry Andric     /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
266349cc55cSDimitry Andric     Value *getNodeForInc(Loop *L, Instruction *MemI,
267349cc55cSDimitry Andric                          const SCEV *BasePtrIncSCEV);
268349cc55cSDimitry Andric 
269349cc55cSDimitry Andric     /// Common chains to reuse offsets for a loop to reduce register pressure.
270349cc55cSDimitry Andric     bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
271349cc55cSDimitry Andric 
272349cc55cSDimitry Andric     /// Find out the potential commoning chains and their bases.
273349cc55cSDimitry Andric     bool prepareBasesForCommoningChains(Bucket &BucketChain);
274349cc55cSDimitry Andric 
275349cc55cSDimitry Andric     /// Rewrite load/store according to the common chains.
276349cc55cSDimitry Andric     bool
277349cc55cSDimitry Andric     rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
278349cc55cSDimitry Andric                                         SmallSet<BasicBlock *, 16> &BBChanged);
279480093f4SDimitry Andric 
280480093f4SDimitry Andric     /// Collect condition matched(\p isValidCandidate() returns true)
281480093f4SDimitry Andric     /// candidates in Loop \p L.
282fe6060f1SDimitry Andric     SmallVector<Bucket, 16> collectCandidates(
283fe6060f1SDimitry Andric         Loop *L,
284349cc55cSDimitry Andric         std::function<bool(const Instruction *, Value *, const Type *)>
285480093f4SDimitry Andric             isValidCandidate,
286349cc55cSDimitry Andric         std::function<bool(const SCEV *)> isValidDiff,
287480093f4SDimitry Andric         unsigned MaxCandidateNum);
288480093f4SDimitry Andric 
289349cc55cSDimitry Andric     /// Add a candidate to candidates \p Buckets if diff between candidate and
290349cc55cSDimitry Andric     /// one base in \p Buckets matches \p isValidDiff.
291480093f4SDimitry Andric     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
292480093f4SDimitry Andric                          SmallVector<Bucket, 16> &Buckets,
293349cc55cSDimitry Andric                          std::function<bool(const SCEV *)> isValidDiff,
294480093f4SDimitry Andric                          unsigned MaxCandidateNum);
295480093f4SDimitry Andric 
296480093f4SDimitry Andric     /// Prepare all candidates in \p Buckets for update form.
297480093f4SDimitry Andric     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
298480093f4SDimitry Andric 
299480093f4SDimitry Andric     /// Prepare all candidates in \p Buckets for displacement form, now for
300480093f4SDimitry Andric     /// ds/dq.
301349cc55cSDimitry Andric     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
302480093f4SDimitry Andric 
303480093f4SDimitry Andric     /// Prepare for one chain \p BucketChain, find the best base element and
304480093f4SDimitry Andric     /// update all other elements in \p BucketChain accordingly.
305480093f4SDimitry Andric     /// \p Form is used to find the best base element.
306480093f4SDimitry Andric     /// If success, best base element must be stored as the first element of
307480093f4SDimitry Andric     /// \p BucketChain.
308480093f4SDimitry Andric     /// Return false if no base element found, otherwise return true.
309349cc55cSDimitry Andric     bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
310480093f4SDimitry Andric 
311480093f4SDimitry Andric     /// Prepare for one chain \p BucketChain, find the best base element and
312480093f4SDimitry Andric     /// update all other elements in \p BucketChain accordingly.
313480093f4SDimitry Andric     /// If success, best base element must be stored as the first element of
314480093f4SDimitry Andric     /// \p BucketChain.
315480093f4SDimitry Andric     /// Return false if no base element found, otherwise return true.
316480093f4SDimitry Andric     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
317480093f4SDimitry Andric 
318480093f4SDimitry Andric     /// Rewrite load/store instructions in \p BucketChain according to
319480093f4SDimitry Andric     /// preparation.
320480093f4SDimitry Andric     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
321480093f4SDimitry Andric                            SmallSet<BasicBlock *, 16> &BBChanged,
322349cc55cSDimitry Andric                            PrepForm Form);
323349cc55cSDimitry Andric 
324349cc55cSDimitry Andric     /// Rewrite for the base load/store of a chain.
325349cc55cSDimitry Andric     std::pair<Instruction *, Instruction *>
326349cc55cSDimitry Andric     rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
327349cc55cSDimitry Andric                    Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
328349cc55cSDimitry Andric                    SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
329349cc55cSDimitry Andric 
330349cc55cSDimitry Andric     /// Rewrite for the other load/stores of a chain according to the new \p
331349cc55cSDimitry Andric     /// Base.
332349cc55cSDimitry Andric     Instruction *
333349cc55cSDimitry Andric     rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
334349cc55cSDimitry Andric                             const BucketElement &Element, Value *OffToBase,
335349cc55cSDimitry Andric                             SmallPtrSet<Value *, 16> &DeletedPtrs);
336480093f4SDimitry Andric   };
337480093f4SDimitry Andric 
338480093f4SDimitry Andric } // end anonymous namespace
339480093f4SDimitry Andric 
340480093f4SDimitry Andric char PPCLoopInstrFormPrep::ID = 0;
341480093f4SDimitry Andric static const char *name = "Prepare loop for ppc preferred instruction forms";
342480093f4SDimitry Andric INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
343480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
344480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
345480093f4SDimitry Andric INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
346480093f4SDimitry Andric 
3475ffd83dbSDimitry Andric static constexpr StringRef PHINodeNameSuffix    = ".phi";
3485ffd83dbSDimitry Andric static constexpr StringRef CastNodeNameSuffix   = ".cast";
3495ffd83dbSDimitry Andric static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
3505ffd83dbSDimitry Andric static constexpr StringRef GEPNodeOffNameSuffix = ".off";
351480093f4SDimitry Andric 
createPPCLoopInstrFormPrepPass(PPCTargetMachine & TM)352480093f4SDimitry Andric FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
353480093f4SDimitry Andric   return new PPCLoopInstrFormPrep(TM);
354480093f4SDimitry Andric }
355480093f4SDimitry Andric 
IsPtrInBounds(Value * BasePtr)356480093f4SDimitry Andric static bool IsPtrInBounds(Value *BasePtr) {
357480093f4SDimitry Andric   Value *StrippedBasePtr = BasePtr;
358480093f4SDimitry Andric   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
359480093f4SDimitry Andric     StrippedBasePtr = BC->getOperand(0);
360480093f4SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
361480093f4SDimitry Andric     return GEP->isInBounds();
362480093f4SDimitry Andric 
363480093f4SDimitry Andric   return false;
364480093f4SDimitry Andric }
365480093f4SDimitry Andric 
getInstrName(const Value * I,StringRef Suffix)3665ffd83dbSDimitry Andric static std::string getInstrName(const Value *I, StringRef Suffix) {
367480093f4SDimitry Andric   assert(I && "Invalid paramater!");
368480093f4SDimitry Andric   if (I->hasName())
369480093f4SDimitry Andric     return (I->getName() + Suffix).str();
370480093f4SDimitry Andric   else
371480093f4SDimitry Andric     return "";
372480093f4SDimitry Andric }
373480093f4SDimitry Andric 
getPointerOperandAndType(Value * MemI,Type ** PtrElementType=nullptr)374349cc55cSDimitry Andric static Value *getPointerOperandAndType(Value *MemI,
375349cc55cSDimitry Andric                                        Type **PtrElementType = nullptr) {
376480093f4SDimitry Andric 
377349cc55cSDimitry Andric   Value *PtrValue = nullptr;
378349cc55cSDimitry Andric   Type *PointerElementType = nullptr;
379349cc55cSDimitry Andric 
380349cc55cSDimitry Andric   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
381349cc55cSDimitry Andric     PtrValue = LMemI->getPointerOperand();
382349cc55cSDimitry Andric     PointerElementType = LMemI->getType();
383349cc55cSDimitry Andric   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
384349cc55cSDimitry Andric     PtrValue = SMemI->getPointerOperand();
385349cc55cSDimitry Andric     PointerElementType = SMemI->getValueOperand()->getType();
386349cc55cSDimitry Andric   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
387349cc55cSDimitry Andric     PointerElementType = Type::getInt8Ty(MemI->getContext());
388349cc55cSDimitry Andric     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
389349cc55cSDimitry Andric         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
390349cc55cSDimitry Andric       PtrValue = IMemI->getArgOperand(0);
391349cc55cSDimitry Andric     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
392349cc55cSDimitry Andric       PtrValue = IMemI->getArgOperand(1);
393349cc55cSDimitry Andric     }
394349cc55cSDimitry Andric   }
395349cc55cSDimitry Andric   /*Get ElementType if PtrElementType is not null.*/
396349cc55cSDimitry Andric   if (PtrElementType)
397349cc55cSDimitry Andric     *PtrElementType = PointerElementType;
398349cc55cSDimitry Andric 
399349cc55cSDimitry Andric   return PtrValue;
400480093f4SDimitry Andric }
401480093f4SDimitry Andric 
runOnFunction(Function & F)402480093f4SDimitry Andric bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
403480093f4SDimitry Andric   if (skipFunction(F))
404480093f4SDimitry Andric     return false;
405480093f4SDimitry Andric 
406480093f4SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
407480093f4SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
408480093f4SDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
409480093f4SDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
410480093f4SDimitry Andric   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
411480093f4SDimitry Andric   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
412480093f4SDimitry Andric   SuccPrepCount = 0;
413480093f4SDimitry Andric 
414480093f4SDimitry Andric   bool MadeChange = false;
415480093f4SDimitry Andric 
4160eae32dcSDimitry Andric   for (Loop *I : *LI)
4170eae32dcSDimitry Andric     for (Loop *L : depth_first(I))
4180eae32dcSDimitry Andric       MadeChange |= runOnLoop(L);
419480093f4SDimitry Andric 
420480093f4SDimitry Andric   return MadeChange;
421480093f4SDimitry Andric }
422480093f4SDimitry Andric 
423349cc55cSDimitry Andric // Finding the minimal(chain_number + reusable_offset_number) is a complicated
424349cc55cSDimitry Andric // algorithmic problem.
425349cc55cSDimitry Andric // For now, the algorithm used here is simply adjusted to handle the case for
426349cc55cSDimitry Andric // manually unrolling cases.
427349cc55cSDimitry Andric // FIXME: use a more powerful algorithm to find minimal sum of chain_number and
428349cc55cSDimitry Andric // reusable_offset_number for one base with multiple offsets.
prepareBasesForCommoningChains(Bucket & CBucket)429349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
430349cc55cSDimitry Andric   // The minimal size for profitable chain commoning:
431349cc55cSDimitry Andric   // A1 = base + offset1
432349cc55cSDimitry Andric   // A2 = base + offset2 (offset2 - offset1 = X)
433349cc55cSDimitry Andric   // A3 = base + offset3
434349cc55cSDimitry Andric   // A4 = base + offset4 (offset4 - offset3 = X)
435349cc55cSDimitry Andric   // ======>
436349cc55cSDimitry Andric   // base1 = base + offset1
437349cc55cSDimitry Andric   // base2 = base + offset3
438349cc55cSDimitry Andric   // A1 = base1
439349cc55cSDimitry Andric   // A2 = base1 + X
440349cc55cSDimitry Andric   // A3 = base2
441349cc55cSDimitry Andric   // A4 = base2 + X
442349cc55cSDimitry Andric   //
443349cc55cSDimitry Andric   // There is benefit because of reuse of offest 'X'.
444349cc55cSDimitry Andric 
445349cc55cSDimitry Andric   assert(ChainCommonPrepMinThreshold >= 4 &&
446349cc55cSDimitry Andric          "Thredhold can not be smaller than 4!\n");
447349cc55cSDimitry Andric   if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
448349cc55cSDimitry Andric     return false;
449349cc55cSDimitry Andric 
450349cc55cSDimitry Andric   // We simply select the FirstOffset as the first reusable offset between each
451349cc55cSDimitry Andric   // chain element 1 and element 0.
452349cc55cSDimitry Andric   const SCEV *FirstOffset = CBucket.Elements[1].Offset;
453349cc55cSDimitry Andric 
454349cc55cSDimitry Andric   // Figure out how many times above FirstOffset is used in the chain.
455349cc55cSDimitry Andric   // For a success commoning chain candidate, offset difference between each
456349cc55cSDimitry Andric   // chain element 1 and element 0 must be also FirstOffset.
457349cc55cSDimitry Andric   unsigned FirstOffsetReusedCount = 1;
458349cc55cSDimitry Andric 
459349cc55cSDimitry Andric   // Figure out how many times above FirstOffset is used in the first chain.
460349cc55cSDimitry Andric   // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
461349cc55cSDimitry Andric   unsigned FirstOffsetReusedCountInFirstChain = 1;
462349cc55cSDimitry Andric 
463349cc55cSDimitry Andric   unsigned EleNum = CBucket.Elements.size();
464349cc55cSDimitry Andric   bool SawChainSeparater = false;
465349cc55cSDimitry Andric   for (unsigned j = 2; j != EleNum; ++j) {
466349cc55cSDimitry Andric     if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
467349cc55cSDimitry Andric                          CBucket.Elements[j - 1].Offset) == FirstOffset) {
468349cc55cSDimitry Andric       if (!SawChainSeparater)
469349cc55cSDimitry Andric         FirstOffsetReusedCountInFirstChain++;
470349cc55cSDimitry Andric       FirstOffsetReusedCount++;
471349cc55cSDimitry Andric     } else
472349cc55cSDimitry Andric       // For now, if we meet any offset which is not FirstOffset, we assume we
473349cc55cSDimitry Andric       // find a new Chain.
474349cc55cSDimitry Andric       // This makes us miss some opportunities.
475349cc55cSDimitry Andric       // For example, we can common:
476349cc55cSDimitry Andric       //
477349cc55cSDimitry Andric       // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
478349cc55cSDimitry Andric       //
479349cc55cSDimitry Andric       // as two chains:
480349cc55cSDimitry Andric       // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
481349cc55cSDimitry Andric       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
482349cc55cSDimitry Andric       //
483349cc55cSDimitry Andric       // But we fail to common:
484349cc55cSDimitry Andric       //
485349cc55cSDimitry Andric       // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
486349cc55cSDimitry Andric       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
487349cc55cSDimitry Andric 
488349cc55cSDimitry Andric       SawChainSeparater = true;
489349cc55cSDimitry Andric   }
490349cc55cSDimitry Andric 
491349cc55cSDimitry Andric   // FirstOffset is not reused, skip this bucket.
492349cc55cSDimitry Andric   if (FirstOffsetReusedCount == 1)
493349cc55cSDimitry Andric     return false;
494349cc55cSDimitry Andric 
495349cc55cSDimitry Andric   unsigned ChainNum =
496349cc55cSDimitry Andric       FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
497349cc55cSDimitry Andric 
498349cc55cSDimitry Andric   // All elements are increased by FirstOffset.
499349cc55cSDimitry Andric   // The number of chains should be sqrt(EleNum).
500349cc55cSDimitry Andric   if (!SawChainSeparater)
501349cc55cSDimitry Andric     ChainNum = (unsigned)sqrt((double)EleNum);
502349cc55cSDimitry Andric 
503349cc55cSDimitry Andric   CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
504349cc55cSDimitry Andric 
505349cc55cSDimitry Andric   // If this is not a perfect chain(eg: not all elements can be put inside
506349cc55cSDimitry Andric   // commoning chains.), skip now.
507349cc55cSDimitry Andric   if (CBucket.ChainSize * ChainNum != EleNum)
508349cc55cSDimitry Andric     return false;
509349cc55cSDimitry Andric 
510349cc55cSDimitry Andric   if (SawChainSeparater) {
511349cc55cSDimitry Andric     // Check that the offset seqs are the same for all chains.
512349cc55cSDimitry Andric     for (unsigned i = 1; i < CBucket.ChainSize; i++)
513349cc55cSDimitry Andric       for (unsigned j = 1; j < ChainNum; j++)
514349cc55cSDimitry Andric         if (CBucket.Elements[i].Offset !=
515349cc55cSDimitry Andric             SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
516349cc55cSDimitry Andric                              CBucket.Elements[j * CBucket.ChainSize].Offset))
517349cc55cSDimitry Andric           return false;
518349cc55cSDimitry Andric   }
519349cc55cSDimitry Andric 
520349cc55cSDimitry Andric   for (unsigned i = 0; i < ChainNum; i++)
521349cc55cSDimitry Andric     CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
522349cc55cSDimitry Andric 
523349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
524349cc55cSDimitry Andric 
525349cc55cSDimitry Andric   return true;
526349cc55cSDimitry Andric }
527349cc55cSDimitry Andric 
chainCommoning(Loop * L,SmallVector<Bucket,16> & Buckets)528349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
529349cc55cSDimitry Andric                                           SmallVector<Bucket, 16> &Buckets) {
530349cc55cSDimitry Andric   bool MadeChange = false;
531349cc55cSDimitry Andric 
532349cc55cSDimitry Andric   if (Buckets.empty())
533349cc55cSDimitry Andric     return MadeChange;
534349cc55cSDimitry Andric 
535349cc55cSDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
536349cc55cSDimitry Andric 
537349cc55cSDimitry Andric   for (auto &Bucket : Buckets) {
538349cc55cSDimitry Andric     if (prepareBasesForCommoningChains(Bucket))
539349cc55cSDimitry Andric       MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
540349cc55cSDimitry Andric   }
541349cc55cSDimitry Andric 
542349cc55cSDimitry Andric   if (MadeChange)
543349cc55cSDimitry Andric     for (auto *BB : BBChanged)
544349cc55cSDimitry Andric       DeleteDeadPHIs(BB);
545349cc55cSDimitry Andric   return MadeChange;
546349cc55cSDimitry Andric }
547349cc55cSDimitry Andric 
rewriteLoadStoresForCommoningChains(Loop * L,Bucket & Bucket,SmallSet<BasicBlock *,16> & BBChanged)548349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
549349cc55cSDimitry Andric     Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
550349cc55cSDimitry Andric   bool MadeChange = false;
551349cc55cSDimitry Andric 
552349cc55cSDimitry Andric   assert(Bucket.Elements.size() ==
553349cc55cSDimitry Andric              Bucket.ChainBases.size() * Bucket.ChainSize &&
554349cc55cSDimitry Andric          "invalid bucket for chain commoning!\n");
555349cc55cSDimitry Andric   SmallPtrSet<Value *, 16> DeletedPtrs;
556349cc55cSDimitry Andric 
557349cc55cSDimitry Andric   BasicBlock *Header = L->getHeader();
558349cc55cSDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
559349cc55cSDimitry Andric 
560349cc55cSDimitry Andric   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
561349cc55cSDimitry Andric                      "loopprepare-chaincommon");
562349cc55cSDimitry Andric 
563349cc55cSDimitry Andric   for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
564349cc55cSDimitry Andric     unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
565349cc55cSDimitry Andric     const SCEV *BaseSCEV =
566349cc55cSDimitry Andric         ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
567349cc55cSDimitry Andric                                   Bucket.Elements[BaseElemIdx].Offset)
568349cc55cSDimitry Andric                  : Bucket.BaseSCEV;
569349cc55cSDimitry Andric     const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
570349cc55cSDimitry Andric 
571349cc55cSDimitry Andric     // Make sure the base is able to expand.
572fcaf7f86SDimitry Andric     if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
573349cc55cSDimitry Andric       return MadeChange;
574349cc55cSDimitry Andric 
575349cc55cSDimitry Andric     assert(BasePtrSCEV->isAffine() &&
576349cc55cSDimitry Andric            "Invalid SCEV type for the base ptr for a candidate chain!\n");
577349cc55cSDimitry Andric 
578349cc55cSDimitry Andric     std::pair<Instruction *, Instruction *> Base = rewriteForBase(
579349cc55cSDimitry Andric         L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
580349cc55cSDimitry Andric         false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs);
581349cc55cSDimitry Andric 
582349cc55cSDimitry Andric     if (!Base.first || !Base.second)
583349cc55cSDimitry Andric       return MadeChange;
584349cc55cSDimitry Andric 
585349cc55cSDimitry Andric     // Keep track of the replacement pointer values we've inserted so that we
586349cc55cSDimitry Andric     // don't generate more pointer values than necessary.
587349cc55cSDimitry Andric     SmallPtrSet<Value *, 16> NewPtrs;
588349cc55cSDimitry Andric     NewPtrs.insert(Base.first);
589349cc55cSDimitry Andric 
590349cc55cSDimitry Andric     for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
591349cc55cSDimitry Andric          ++Idx) {
592349cc55cSDimitry Andric       BucketElement &I = Bucket.Elements[Idx];
593349cc55cSDimitry Andric       Value *Ptr = getPointerOperandAndType(I.Instr);
594349cc55cSDimitry Andric       assert(Ptr && "No pointer operand");
595349cc55cSDimitry Andric       if (NewPtrs.count(Ptr))
596349cc55cSDimitry Andric         continue;
597349cc55cSDimitry Andric 
598349cc55cSDimitry Andric       const SCEV *OffsetSCEV =
599349cc55cSDimitry Andric           BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
600349cc55cSDimitry Andric                                          Bucket.Elements[BaseElemIdx].Offset)
601349cc55cSDimitry Andric                       : Bucket.Elements[Idx].Offset;
602349cc55cSDimitry Andric 
603349cc55cSDimitry Andric       // Make sure offset is able to expand. Only need to check one time as the
604349cc55cSDimitry Andric       // offsets are reused between different chains.
605349cc55cSDimitry Andric       if (!BaseElemIdx)
606fcaf7f86SDimitry Andric         if (!SCEVE.isSafeToExpand(OffsetSCEV))
607349cc55cSDimitry Andric           return false;
608349cc55cSDimitry Andric 
609349cc55cSDimitry Andric       Value *OffsetValue = SCEVE.expandCodeFor(
610349cc55cSDimitry Andric           OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
611349cc55cSDimitry Andric 
612349cc55cSDimitry Andric       Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
613349cc55cSDimitry Andric                                                     OffsetValue, DeletedPtrs);
614349cc55cSDimitry Andric 
615349cc55cSDimitry Andric       assert(NewPtr && "Wrong rewrite!\n");
616349cc55cSDimitry Andric       NewPtrs.insert(NewPtr);
617349cc55cSDimitry Andric     }
618349cc55cSDimitry Andric 
619349cc55cSDimitry Andric     ++ChainCommoningRewritten;
620349cc55cSDimitry Andric   }
621349cc55cSDimitry Andric 
622349cc55cSDimitry Andric   // Clear the rewriter cache, because values that are in the rewriter's cache
623349cc55cSDimitry Andric   // can be deleted below, causing the AssertingVH in the cache to trigger.
624349cc55cSDimitry Andric   SCEVE.clear();
625349cc55cSDimitry Andric 
626349cc55cSDimitry Andric   for (auto *Ptr : DeletedPtrs) {
627349cc55cSDimitry Andric     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
628349cc55cSDimitry Andric       BBChanged.insert(IDel->getParent());
629349cc55cSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
630349cc55cSDimitry Andric   }
631349cc55cSDimitry Andric 
632349cc55cSDimitry Andric   MadeChange = true;
633349cc55cSDimitry Andric   return MadeChange;
634349cc55cSDimitry Andric }
635349cc55cSDimitry Andric 
636349cc55cSDimitry Andric // Rewrite the new base according to BasePtrSCEV.
637349cc55cSDimitry Andric // bb.loop.preheader:
638349cc55cSDimitry Andric //   %newstart = ...
639349cc55cSDimitry Andric // bb.loop.body:
640349cc55cSDimitry Andric //   %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
641349cc55cSDimitry Andric //   ...
642349cc55cSDimitry Andric //   %add = getelementptr %phinode, %inc
643349cc55cSDimitry Andric //
644349cc55cSDimitry Andric // First returned instruciton is %phinode (or a type cast to %phinode), caller
645349cc55cSDimitry Andric // needs this value to rewrite other load/stores in the same chain.
646349cc55cSDimitry Andric // Second returned instruction is %add, caller needs this value to rewrite other
647349cc55cSDimitry Andric // load/stores in the same chain.
648349cc55cSDimitry Andric std::pair<Instruction *, Instruction *>
rewriteForBase(Loop * L,const SCEVAddRecExpr * BasePtrSCEV,Instruction * BaseMemI,bool CanPreInc,PrepForm Form,SCEVExpander & SCEVE,SmallPtrSet<Value *,16> & DeletedPtrs)649349cc55cSDimitry Andric PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
650349cc55cSDimitry Andric                                      Instruction *BaseMemI, bool CanPreInc,
651349cc55cSDimitry Andric                                      PrepForm Form, SCEVExpander &SCEVE,
652349cc55cSDimitry Andric                                      SmallPtrSet<Value *, 16> &DeletedPtrs) {
653349cc55cSDimitry Andric 
654349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
655349cc55cSDimitry Andric 
656349cc55cSDimitry Andric   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
657349cc55cSDimitry Andric 
658349cc55cSDimitry Andric   Value *BasePtr = getPointerOperandAndType(BaseMemI);
659349cc55cSDimitry Andric   assert(BasePtr && "No pointer operand");
660349cc55cSDimitry Andric 
661349cc55cSDimitry Andric   Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
662349cc55cSDimitry Andric   Type *I8PtrTy =
663*5f757f3fSDimitry Andric       PointerType::get(BaseMemI->getParent()->getContext(),
664349cc55cSDimitry Andric                        BasePtr->getType()->getPointerAddressSpace());
665349cc55cSDimitry Andric 
666349cc55cSDimitry Andric   bool IsConstantInc = false;
667349cc55cSDimitry Andric   const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
668349cc55cSDimitry Andric   Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
669349cc55cSDimitry Andric 
670349cc55cSDimitry Andric   const SCEVConstant *BasePtrIncConstantSCEV =
671349cc55cSDimitry Andric       dyn_cast<SCEVConstant>(BasePtrIncSCEV);
672349cc55cSDimitry Andric   if (BasePtrIncConstantSCEV)
673349cc55cSDimitry Andric     IsConstantInc = true;
674349cc55cSDimitry Andric 
675349cc55cSDimitry Andric   // No valid representation for the increment.
676349cc55cSDimitry Andric   if (!IncNode) {
677349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
678349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
679349cc55cSDimitry Andric   }
680349cc55cSDimitry Andric 
681349cc55cSDimitry Andric   if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) {
682349cc55cSDimitry Andric     LLVM_DEBUG(
683349cc55cSDimitry Andric         dbgs()
684349cc55cSDimitry Andric         << "Update form prepare for non-const increment is not enabled!\n");
685349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
686349cc55cSDimitry Andric   }
687349cc55cSDimitry Andric 
688349cc55cSDimitry Andric   const SCEV *BasePtrStartSCEV = nullptr;
689349cc55cSDimitry Andric   if (CanPreInc) {
690349cc55cSDimitry Andric     assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
691349cc55cSDimitry Andric            "Increment is not loop invariant!\n");
692349cc55cSDimitry Andric     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
693349cc55cSDimitry Andric                                         IsConstantInc ? BasePtrIncConstantSCEV
694349cc55cSDimitry Andric                                                       : BasePtrIncSCEV);
695349cc55cSDimitry Andric   } else
696349cc55cSDimitry Andric     BasePtrStartSCEV = BasePtrSCEV->getStart();
697349cc55cSDimitry Andric 
698349cc55cSDimitry Andric   if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
699349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
700349cc55cSDimitry Andric     return std::make_pair(nullptr, nullptr);
701349cc55cSDimitry Andric   }
702349cc55cSDimitry Andric 
703349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
704349cc55cSDimitry Andric 
705349cc55cSDimitry Andric   BasicBlock *Header = L->getHeader();
706349cc55cSDimitry Andric   unsigned HeaderLoopPredCount = pred_size(Header);
707349cc55cSDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
708349cc55cSDimitry Andric 
709349cc55cSDimitry Andric   PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
710*5f757f3fSDimitry Andric                                     getInstrName(BaseMemI, PHINodeNameSuffix));
711*5f757f3fSDimitry Andric   NewPHI->insertBefore(Header->getFirstNonPHIIt());
712349cc55cSDimitry Andric 
713349cc55cSDimitry Andric   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
714349cc55cSDimitry Andric                                             LoopPredecessor->getTerminator());
715349cc55cSDimitry Andric 
716349cc55cSDimitry Andric   // Note that LoopPredecessor might occur in the predecessor list multiple
717349cc55cSDimitry Andric   // times, and we need to add it the right number of times.
718bdd1243dSDimitry Andric   for (auto *PI : predecessors(Header)) {
719349cc55cSDimitry Andric     if (PI != LoopPredecessor)
720349cc55cSDimitry Andric       continue;
721349cc55cSDimitry Andric 
722349cc55cSDimitry Andric     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
723349cc55cSDimitry Andric   }
724349cc55cSDimitry Andric 
725349cc55cSDimitry Andric   Instruction *PtrInc = nullptr;
726349cc55cSDimitry Andric   Instruction *NewBasePtr = nullptr;
727349cc55cSDimitry Andric   if (CanPreInc) {
728349cc55cSDimitry Andric     Instruction *InsPoint = &*Header->getFirstInsertionPt();
729349cc55cSDimitry Andric     PtrInc = GetElementPtrInst::Create(
730349cc55cSDimitry Andric         I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
731349cc55cSDimitry Andric         InsPoint);
732349cc55cSDimitry Andric     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
733bdd1243dSDimitry Andric     for (auto *PI : predecessors(Header)) {
734349cc55cSDimitry Andric       if (PI == LoopPredecessor)
735349cc55cSDimitry Andric         continue;
736349cc55cSDimitry Andric 
737349cc55cSDimitry Andric       NewPHI->addIncoming(PtrInc, PI);
738349cc55cSDimitry Andric     }
739349cc55cSDimitry Andric     if (PtrInc->getType() != BasePtr->getType())
740349cc55cSDimitry Andric       NewBasePtr =
741349cc55cSDimitry Andric           new BitCastInst(PtrInc, BasePtr->getType(),
742349cc55cSDimitry Andric                           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
743349cc55cSDimitry Andric     else
744349cc55cSDimitry Andric       NewBasePtr = PtrInc;
745349cc55cSDimitry Andric   } else {
746349cc55cSDimitry Andric     // Note that LoopPredecessor might occur in the predecessor list multiple
747349cc55cSDimitry Andric     // times, and we need to make sure no more incoming value for them in PHI.
748bdd1243dSDimitry Andric     for (auto *PI : predecessors(Header)) {
749349cc55cSDimitry Andric       if (PI == LoopPredecessor)
750349cc55cSDimitry Andric         continue;
751349cc55cSDimitry Andric 
752349cc55cSDimitry Andric       // For the latch predecessor, we need to insert a GEP just before the
753349cc55cSDimitry Andric       // terminator to increase the address.
754349cc55cSDimitry Andric       BasicBlock *BB = PI;
755349cc55cSDimitry Andric       Instruction *InsPoint = BB->getTerminator();
756349cc55cSDimitry Andric       PtrInc = GetElementPtrInst::Create(
757349cc55cSDimitry Andric           I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
758349cc55cSDimitry Andric           InsPoint);
759349cc55cSDimitry Andric       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
760349cc55cSDimitry Andric 
761349cc55cSDimitry Andric       NewPHI->addIncoming(PtrInc, PI);
762349cc55cSDimitry Andric     }
763349cc55cSDimitry Andric     PtrInc = NewPHI;
764349cc55cSDimitry Andric     if (NewPHI->getType() != BasePtr->getType())
765349cc55cSDimitry Andric       NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
766349cc55cSDimitry Andric                                    getInstrName(NewPHI, CastNodeNameSuffix),
767349cc55cSDimitry Andric                                    &*Header->getFirstInsertionPt());
768349cc55cSDimitry Andric     else
769349cc55cSDimitry Andric       NewBasePtr = NewPHI;
770349cc55cSDimitry Andric   }
771349cc55cSDimitry Andric 
772349cc55cSDimitry Andric   BasePtr->replaceAllUsesWith(NewBasePtr);
773349cc55cSDimitry Andric 
774349cc55cSDimitry Andric   DeletedPtrs.insert(BasePtr);
775349cc55cSDimitry Andric 
776349cc55cSDimitry Andric   return std::make_pair(NewBasePtr, PtrInc);
777349cc55cSDimitry Andric }
778349cc55cSDimitry Andric 
rewriteForBucketElement(std::pair<Instruction *,Instruction * > Base,const BucketElement & Element,Value * OffToBase,SmallPtrSet<Value *,16> & DeletedPtrs)779349cc55cSDimitry Andric Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
780349cc55cSDimitry Andric     std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
781349cc55cSDimitry Andric     Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
782349cc55cSDimitry Andric   Instruction *NewBasePtr = Base.first;
783349cc55cSDimitry Andric   Instruction *PtrInc = Base.second;
784349cc55cSDimitry Andric   assert((NewBasePtr && PtrInc) && "base does not exist!\n");
785349cc55cSDimitry Andric 
786349cc55cSDimitry Andric   Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
787349cc55cSDimitry Andric 
788349cc55cSDimitry Andric   Value *Ptr = getPointerOperandAndType(Element.Instr);
789349cc55cSDimitry Andric   assert(Ptr && "No pointer operand");
790349cc55cSDimitry Andric 
791349cc55cSDimitry Andric   Instruction *RealNewPtr;
792349cc55cSDimitry Andric   if (!Element.Offset ||
793349cc55cSDimitry Andric       (isa<SCEVConstant>(Element.Offset) &&
794349cc55cSDimitry Andric        cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
795349cc55cSDimitry Andric     RealNewPtr = NewBasePtr;
796349cc55cSDimitry Andric   } else {
797349cc55cSDimitry Andric     Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
798349cc55cSDimitry Andric     if (PtrIP && isa<Instruction>(NewBasePtr) &&
799349cc55cSDimitry Andric         cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
800349cc55cSDimitry Andric       PtrIP = nullptr;
801349cc55cSDimitry Andric     else if (PtrIP && isa<PHINode>(PtrIP))
802349cc55cSDimitry Andric       PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
803349cc55cSDimitry Andric     else if (!PtrIP)
804349cc55cSDimitry Andric       PtrIP = Element.Instr;
805349cc55cSDimitry Andric 
806349cc55cSDimitry Andric     assert(OffToBase && "There should be an offset for non base element!\n");
807349cc55cSDimitry Andric     GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
808349cc55cSDimitry Andric         I8Ty, PtrInc, OffToBase,
809349cc55cSDimitry Andric         getInstrName(Element.Instr, GEPNodeOffNameSuffix), PtrIP);
810349cc55cSDimitry Andric     if (!PtrIP)
811349cc55cSDimitry Andric       NewPtr->insertAfter(cast<Instruction>(PtrInc));
812349cc55cSDimitry Andric     NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
813349cc55cSDimitry Andric     RealNewPtr = NewPtr;
814349cc55cSDimitry Andric   }
815349cc55cSDimitry Andric 
816349cc55cSDimitry Andric   Instruction *ReplNewPtr;
817349cc55cSDimitry Andric   if (Ptr->getType() != RealNewPtr->getType()) {
818349cc55cSDimitry Andric     ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
819349cc55cSDimitry Andric                                  getInstrName(Ptr, CastNodeNameSuffix));
820349cc55cSDimitry Andric     ReplNewPtr->insertAfter(RealNewPtr);
821349cc55cSDimitry Andric   } else
822349cc55cSDimitry Andric     ReplNewPtr = RealNewPtr;
823349cc55cSDimitry Andric 
824349cc55cSDimitry Andric   Ptr->replaceAllUsesWith(ReplNewPtr);
825349cc55cSDimitry Andric   DeletedPtrs.insert(Ptr);
826349cc55cSDimitry Andric 
827349cc55cSDimitry Andric   return ReplNewPtr;
828349cc55cSDimitry Andric }
829349cc55cSDimitry Andric 
addOneCandidate(Instruction * MemI,const SCEV * LSCEV,SmallVector<Bucket,16> & Buckets,std::function<bool (const SCEV *)> isValidDiff,unsigned MaxCandidateNum)830349cc55cSDimitry Andric void PPCLoopInstrFormPrep::addOneCandidate(
831349cc55cSDimitry Andric     Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
832349cc55cSDimitry Andric     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
833349cc55cSDimitry Andric   assert((MemI && getPointerOperandAndType(MemI)) &&
834480093f4SDimitry Andric          "Candidate should be a memory instruction.");
835480093f4SDimitry Andric   assert(LSCEV && "Invalid SCEV for Ptr value.");
836349cc55cSDimitry Andric 
837480093f4SDimitry Andric   bool FoundBucket = false;
838480093f4SDimitry Andric   for (auto &B : Buckets) {
839349cc55cSDimitry Andric     if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
840349cc55cSDimitry Andric         cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
841349cc55cSDimitry Andric       continue;
842480093f4SDimitry Andric     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
843349cc55cSDimitry Andric     if (isValidDiff(Diff)) {
844349cc55cSDimitry Andric       B.Elements.push_back(BucketElement(Diff, MemI));
845480093f4SDimitry Andric       FoundBucket = true;
846480093f4SDimitry Andric       break;
847480093f4SDimitry Andric     }
848480093f4SDimitry Andric   }
849480093f4SDimitry Andric 
850480093f4SDimitry Andric   if (!FoundBucket) {
851349cc55cSDimitry Andric     if (Buckets.size() == MaxCandidateNum) {
852349cc55cSDimitry Andric       LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
853349cc55cSDimitry Andric                         << MaxCandidateNum << "\n");
854480093f4SDimitry Andric       return;
855349cc55cSDimitry Andric     }
856480093f4SDimitry Andric     Buckets.push_back(Bucket(LSCEV, MemI));
857480093f4SDimitry Andric   }
858480093f4SDimitry Andric }
859480093f4SDimitry Andric 
collectCandidates(Loop * L,std::function<bool (const Instruction *,Value *,const Type *)> isValidCandidate,std::function<bool (const SCEV *)> isValidDiff,unsigned MaxCandidateNum)860480093f4SDimitry Andric SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
861480093f4SDimitry Andric     Loop *L,
862349cc55cSDimitry Andric     std::function<bool(const Instruction *, Value *, const Type *)>
863fe6060f1SDimitry Andric         isValidCandidate,
864349cc55cSDimitry Andric     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
865480093f4SDimitry Andric   SmallVector<Bucket, 16> Buckets;
866349cc55cSDimitry Andric 
867480093f4SDimitry Andric   for (const auto &BB : L->blocks())
868480093f4SDimitry Andric     for (auto &J : *BB) {
869349cc55cSDimitry Andric       Value *PtrValue = nullptr;
870349cc55cSDimitry Andric       Type *PointerElementType = nullptr;
871349cc55cSDimitry Andric       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
872480093f4SDimitry Andric 
873349cc55cSDimitry Andric       if (!PtrValue)
874349cc55cSDimitry Andric         continue;
875480093f4SDimitry Andric 
876349cc55cSDimitry Andric       if (PtrValue->getType()->getPointerAddressSpace())
877480093f4SDimitry Andric         continue;
878480093f4SDimitry Andric 
879480093f4SDimitry Andric       if (L->isLoopInvariant(PtrValue))
880480093f4SDimitry Andric         continue;
881480093f4SDimitry Andric 
882480093f4SDimitry Andric       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
883480093f4SDimitry Andric       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
884480093f4SDimitry Andric       if (!LARSCEV || LARSCEV->getLoop() != L)
885480093f4SDimitry Andric         continue;
886480093f4SDimitry Andric 
887349cc55cSDimitry Andric       // Mark that we have candidates for preparing.
888349cc55cSDimitry Andric       HasCandidateForPrepare = true;
889349cc55cSDimitry Andric 
890fe6060f1SDimitry Andric       if (isValidCandidate(&J, PtrValue, PointerElementType))
891349cc55cSDimitry Andric         addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
892480093f4SDimitry Andric     }
893480093f4SDimitry Andric   return Buckets;
894480093f4SDimitry Andric }
895480093f4SDimitry Andric 
prepareBaseForDispFormChain(Bucket & BucketChain,PrepForm Form)896480093f4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
897349cc55cSDimitry Andric                                                        PrepForm Form) {
898480093f4SDimitry Andric   // RemainderOffsetInfo details:
899480093f4SDimitry Andric   // key:            value of (Offset urem DispConstraint). For DSForm, it can
900480093f4SDimitry Andric   //                 be [0, 4).
901480093f4SDimitry Andric   // first of pair:  the index of first BucketElement whose remainder is equal
902480093f4SDimitry Andric   //                 to key. For key 0, this value must be 0.
903480093f4SDimitry Andric   // second of pair: number of load/stores with the same remainder.
904480093f4SDimitry Andric   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
905480093f4SDimitry Andric 
906480093f4SDimitry Andric   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
907480093f4SDimitry Andric     if (!BucketChain.Elements[j].Offset)
908480093f4SDimitry Andric       RemainderOffsetInfo[0] = std::make_pair(0, 1);
909480093f4SDimitry Andric     else {
910349cc55cSDimitry Andric       unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
911349cc55cSDimitry Andric                                ->getAPInt()
912349cc55cSDimitry Andric                                .urem(Form);
91306c3fb27SDimitry Andric       if (!RemainderOffsetInfo.contains(Remainder))
914480093f4SDimitry Andric         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
915480093f4SDimitry Andric       else
916480093f4SDimitry Andric         RemainderOffsetInfo[Remainder].second++;
917480093f4SDimitry Andric     }
918480093f4SDimitry Andric   }
919480093f4SDimitry Andric   // Currently we choose the most profitable base as the one which has the max
920480093f4SDimitry Andric   // number of load/store with same remainder.
921480093f4SDimitry Andric   // FIXME: adjust the base selection strategy according to load/store offset
922480093f4SDimitry Andric   // distribution.
923480093f4SDimitry Andric   // For example, if we have one candidate chain for DS form preparation, which
924480093f4SDimitry Andric   // contains following load/stores with different remainders:
925480093f4SDimitry Andric   // 1: 10 load/store whose remainder is 1;
926480093f4SDimitry Andric   // 2: 9 load/store whose remainder is 2;
927480093f4SDimitry Andric   // 3: 1 for remainder 3 and 0 for remainder 0;
928480093f4SDimitry Andric   // Now we will choose the first load/store whose remainder is 1 as base and
929480093f4SDimitry Andric   // adjust all other load/stores according to new base, so we will get 10 DS
930480093f4SDimitry Andric   // form and 10 X form.
931480093f4SDimitry Andric   // But we should be more clever, for this case we could use two bases, one for
932349cc55cSDimitry Andric   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
933349cc55cSDimitry Andric   // 1 X form.
934480093f4SDimitry Andric   unsigned MaxCountRemainder = 0;
935480093f4SDimitry Andric   for (unsigned j = 0; j < (unsigned)Form; j++)
93606c3fb27SDimitry Andric     if ((RemainderOffsetInfo.contains(j)) &&
937480093f4SDimitry Andric         RemainderOffsetInfo[j].second >
938480093f4SDimitry Andric             RemainderOffsetInfo[MaxCountRemainder].second)
939480093f4SDimitry Andric       MaxCountRemainder = j;
940480093f4SDimitry Andric 
941480093f4SDimitry Andric   // Abort when there are too few insts with common base.
942480093f4SDimitry Andric   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
943480093f4SDimitry Andric     return false;
944480093f4SDimitry Andric 
945480093f4SDimitry Andric   // If the first value is most profitable, no needed to adjust BucketChain
946480093f4SDimitry Andric   // elements as they are substracted the first value when collecting.
947480093f4SDimitry Andric   if (MaxCountRemainder == 0)
948480093f4SDimitry Andric     return true;
949480093f4SDimitry Andric 
950480093f4SDimitry Andric   // Adjust load/store to the new chosen base.
951480093f4SDimitry Andric   const SCEV *Offset =
952480093f4SDimitry Andric       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
953480093f4SDimitry Andric   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
954480093f4SDimitry Andric   for (auto &E : BucketChain.Elements) {
955480093f4SDimitry Andric     if (E.Offset)
956480093f4SDimitry Andric       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
957480093f4SDimitry Andric     else
958480093f4SDimitry Andric       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
959480093f4SDimitry Andric   }
960480093f4SDimitry Andric 
961480093f4SDimitry Andric   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
962480093f4SDimitry Andric             BucketChain.Elements[0]);
963480093f4SDimitry Andric   return true;
964480093f4SDimitry Andric }
965480093f4SDimitry Andric 
966480093f4SDimitry Andric // FIXME: implement a more clever base choosing policy.
967480093f4SDimitry Andric // Currently we always choose an exist load/store offset. This maybe lead to
968480093f4SDimitry Andric // suboptimal code sequences. For example, for one DS chain with offsets
969480093f4SDimitry Andric // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
970480093f4SDimitry Andric // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
971480093f4SDimitry Andric // multipler of 4, it cannot be represented by sint16.
prepareBaseForUpdateFormChain(Bucket & BucketChain)972480093f4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
973480093f4SDimitry Andric   // We have a choice now of which instruction's memory operand we use as the
974480093f4SDimitry Andric   // base for the generated PHI. Always picking the first instruction in each
975480093f4SDimitry Andric   // bucket does not work well, specifically because that instruction might
976480093f4SDimitry Andric   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
977480093f4SDimitry Andric   // the choice is somewhat arbitrary, because the backend will happily
978480093f4SDimitry Andric   // generate direct offsets from both the pre-incremented and
979480093f4SDimitry Andric   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
980480093f4SDimitry Andric   // instruction in each bucket, and adjust the recurrence and other offsets
981480093f4SDimitry Andric   // accordingly.
982480093f4SDimitry Andric   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
983480093f4SDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
984480093f4SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::prefetch)
985480093f4SDimitry Andric         continue;
986480093f4SDimitry Andric 
987480093f4SDimitry Andric     // If we'd otherwise pick the first element anyway, there's nothing to do.
988480093f4SDimitry Andric     if (j == 0)
989480093f4SDimitry Andric       break;
990480093f4SDimitry Andric 
991480093f4SDimitry Andric     // If our chosen element has no offset from the base pointer, there's
992480093f4SDimitry Andric     // nothing to do.
993480093f4SDimitry Andric     if (!BucketChain.Elements[j].Offset ||
994349cc55cSDimitry Andric         cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
995480093f4SDimitry Andric       break;
996480093f4SDimitry Andric 
997480093f4SDimitry Andric     const SCEV *Offset = BucketChain.Elements[j].Offset;
998480093f4SDimitry Andric     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
999480093f4SDimitry Andric     for (auto &E : BucketChain.Elements) {
1000480093f4SDimitry Andric       if (E.Offset)
1001480093f4SDimitry Andric         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
1002480093f4SDimitry Andric       else
1003480093f4SDimitry Andric         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
1004480093f4SDimitry Andric     }
1005480093f4SDimitry Andric 
1006480093f4SDimitry Andric     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
1007480093f4SDimitry Andric     break;
1008480093f4SDimitry Andric   }
1009480093f4SDimitry Andric   return true;
1010480093f4SDimitry Andric }
1011480093f4SDimitry Andric 
rewriteLoadStores(Loop * L,Bucket & BucketChain,SmallSet<BasicBlock *,16> & BBChanged,PrepForm Form)1012349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStores(
1013349cc55cSDimitry Andric     Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
1014349cc55cSDimitry Andric     PrepForm Form) {
1015480093f4SDimitry Andric   bool MadeChange = false;
1016349cc55cSDimitry Andric 
1017480093f4SDimitry Andric   const SCEVAddRecExpr *BasePtrSCEV =
1018480093f4SDimitry Andric       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
1019480093f4SDimitry Andric   if (!BasePtrSCEV->isAffine())
1020480093f4SDimitry Andric     return MadeChange;
1021480093f4SDimitry Andric 
1022480093f4SDimitry Andric   BasicBlock *Header = L->getHeader();
1023349cc55cSDimitry Andric   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
1024349cc55cSDimitry Andric                      "loopprepare-formrewrite");
1025fcaf7f86SDimitry Andric   if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
1026fcaf7f86SDimitry Andric     return MadeChange;
1027fcaf7f86SDimitry Andric 
1028fcaf7f86SDimitry Andric   SmallPtrSet<Value *, 16> DeletedPtrs;
1029480093f4SDimitry Andric 
1030349cc55cSDimitry Andric   // For some DS form load/store instructions, it can also be an update form,
1031349cc55cSDimitry Andric   // if the stride is constant and is a multipler of 4. Use update form if
1032349cc55cSDimitry Andric   // prefer it.
1033349cc55cSDimitry Andric   bool CanPreInc = (Form == UpdateForm ||
1034349cc55cSDimitry Andric                     ((Form == DSForm) &&
1035349cc55cSDimitry Andric                      isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
1036349cc55cSDimitry Andric                      !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
1037349cc55cSDimitry Andric                           ->getAPInt()
1038349cc55cSDimitry Andric                           .urem(4) &&
1039349cc55cSDimitry Andric                      PreferUpdateForm));
1040480093f4SDimitry Andric 
1041349cc55cSDimitry Andric   std::pair<Instruction *, Instruction *> Base =
1042349cc55cSDimitry Andric       rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
1043349cc55cSDimitry Andric                      CanPreInc, Form, SCEVE, DeletedPtrs);
1044480093f4SDimitry Andric 
1045349cc55cSDimitry Andric   if (!Base.first || !Base.second)
1046349cc55cSDimitry Andric     return MadeChange;
1047349cc55cSDimitry Andric 
1048349cc55cSDimitry Andric   // Keep track of the replacement pointer values we've inserted so that we
1049349cc55cSDimitry Andric   // don't generate more pointer values than necessary.
1050349cc55cSDimitry Andric   SmallPtrSet<Value *, 16> NewPtrs;
1051349cc55cSDimitry Andric   NewPtrs.insert(Base.first);
1052349cc55cSDimitry Andric 
1053bdd1243dSDimitry Andric   for (const BucketElement &BE : llvm::drop_begin(BucketChain.Elements)) {
1054bdd1243dSDimitry Andric     Value *Ptr = getPointerOperandAndType(BE.Instr);
1055349cc55cSDimitry Andric     assert(Ptr && "No pointer operand");
1056349cc55cSDimitry Andric     if (NewPtrs.count(Ptr))
1057480093f4SDimitry Andric       continue;
1058480093f4SDimitry Andric 
1059349cc55cSDimitry Andric     Instruction *NewPtr = rewriteForBucketElement(
1060bdd1243dSDimitry Andric         Base, BE,
1061bdd1243dSDimitry Andric         BE.Offset ? cast<SCEVConstant>(BE.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 
updateFormPrep(Loop * L,SmallVector<Bucket,16> & Buckets)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 
dispFormPrep(Loop * L,SmallVector<Bucket,16> & Buckets,PrepForm Form)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 //
getNodeForInc(Loop * L,Instruction * MemI,const SCEV * BasePtrIncSCEV)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.
118206c3fb27SDimitry Andric     if (CurrentPHINode->getBasicBlockIndex(LatchBB) < 0)
118306c3fb27SDimitry Andric       continue;
1184349cc55cSDimitry Andric     if (Instruction *I = dyn_cast<Instruction>(
1185349cc55cSDimitry Andric             CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1186349cc55cSDimitry Andric       Value *StrippedBaseI = I;
1187349cc55cSDimitry Andric       while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1188349cc55cSDimitry Andric         StrippedBaseI = BC->getOperand(0);
1189349cc55cSDimitry Andric 
1190349cc55cSDimitry Andric       Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1191349cc55cSDimitry Andric       if (!StrippedI)
1192349cc55cSDimitry Andric         continue;
1193349cc55cSDimitry Andric 
1194349cc55cSDimitry Andric       // LSR pass may add a getelementptr instruction to do the loop increment,
1195349cc55cSDimitry Andric       // also search in that getelementptr instruction.
1196349cc55cSDimitry Andric       if (StrippedI->getOpcode() == Instruction::Add ||
1197349cc55cSDimitry Andric           (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1198349cc55cSDimitry Andric            StrippedI->getNumOperands() == 2)) {
1199349cc55cSDimitry Andric         if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1200349cc55cSDimitry Andric           return StrippedI->getOperand(0);
1201349cc55cSDimitry Andric         if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1202349cc55cSDimitry Andric           return StrippedI->getOperand(1);
1203349cc55cSDimitry Andric       }
1204349cc55cSDimitry Andric     }
1205349cc55cSDimitry Andric   }
1206349cc55cSDimitry Andric   return nullptr;
1207349cc55cSDimitry Andric }
1208349cc55cSDimitry Andric 
1209480093f4SDimitry Andric // In order to prepare for the preferred instruction form, a PHI is added.
1210480093f4SDimitry Andric // This function will check to see if that PHI already exists and will return
1211480093f4SDimitry Andric // true if it found an existing PHI with the matched start and increment as the
1212480093f4SDimitry Andric // one we wanted to create.
alreadyPrepared(Loop * L,Instruction * MemI,const SCEV * BasePtrStartSCEV,const SCEV * BasePtrIncSCEV,PrepForm Form)1213480093f4SDimitry Andric bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
1214480093f4SDimitry Andric                                            const SCEV *BasePtrStartSCEV,
1215349cc55cSDimitry Andric                                            const SCEV *BasePtrIncSCEV,
1216349cc55cSDimitry Andric                                            PrepForm Form) {
1217480093f4SDimitry Andric   BasicBlock *BB = MemI->getParent();
1218480093f4SDimitry Andric   if (!BB)
1219480093f4SDimitry Andric     return false;
1220480093f4SDimitry Andric 
1221480093f4SDimitry Andric   BasicBlock *PredBB = L->getLoopPredecessor();
1222480093f4SDimitry Andric   BasicBlock *LatchBB = L->getLoopLatch();
1223480093f4SDimitry Andric 
1224480093f4SDimitry Andric   if (!PredBB || !LatchBB)
1225480093f4SDimitry Andric     return false;
1226480093f4SDimitry Andric 
1227480093f4SDimitry Andric   // Run through the PHIs and see if we have some that looks like a preparation
1228480093f4SDimitry Andric   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1229480093f4SDimitry Andric   for (auto & CurrentPHI : PHIIter) {
1230480093f4SDimitry Andric     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1231480093f4SDimitry Andric     if (!CurrentPHINode)
1232480093f4SDimitry Andric       continue;
1233480093f4SDimitry Andric 
1234480093f4SDimitry Andric     if (!SE->isSCEVable(CurrentPHINode->getType()))
1235480093f4SDimitry Andric       continue;
1236480093f4SDimitry Andric 
1237480093f4SDimitry Andric     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1238480093f4SDimitry Andric 
1239480093f4SDimitry Andric     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1240480093f4SDimitry Andric     if (!PHIBasePtrSCEV)
1241480093f4SDimitry Andric       continue;
1242480093f4SDimitry Andric 
1243480093f4SDimitry Andric     const SCEVConstant *PHIBasePtrIncSCEV =
1244480093f4SDimitry Andric       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
1245480093f4SDimitry Andric     if (!PHIBasePtrIncSCEV)
1246480093f4SDimitry Andric       continue;
1247480093f4SDimitry Andric 
1248480093f4SDimitry Andric     if (CurrentPHINode->getNumIncomingValues() == 2) {
1249480093f4SDimitry Andric       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
1250480093f4SDimitry Andric            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
1251480093f4SDimitry Andric           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
1252480093f4SDimitry Andric            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
1253480093f4SDimitry Andric         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
1254480093f4SDimitry Andric           // The existing PHI (CurrentPHINode) has the same start and increment
1255480093f4SDimitry Andric           // as the PHI that we wanted to create.
1256349cc55cSDimitry Andric           if ((Form == UpdateForm || Form == ChainCommoning ) &&
1257480093f4SDimitry Andric               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
1258480093f4SDimitry Andric             ++PHINodeAlreadyExistsUpdate;
1259480093f4SDimitry Andric             return true;
1260480093f4SDimitry Andric           }
1261480093f4SDimitry Andric           if (Form == DSForm || Form == DQForm) {
1262480093f4SDimitry Andric             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
1263480093f4SDimitry Andric                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
1264480093f4SDimitry Andric             if (Diff && !Diff->getAPInt().urem(Form)) {
1265480093f4SDimitry Andric               if (Form == DSForm)
1266480093f4SDimitry Andric                 ++PHINodeAlreadyExistsDS;
1267480093f4SDimitry Andric               else
1268480093f4SDimitry Andric                 ++PHINodeAlreadyExistsDQ;
1269480093f4SDimitry Andric               return true;
1270480093f4SDimitry Andric             }
1271480093f4SDimitry Andric           }
1272480093f4SDimitry Andric         }
1273480093f4SDimitry Andric       }
1274480093f4SDimitry Andric     }
1275480093f4SDimitry Andric   }
1276480093f4SDimitry Andric   return false;
1277480093f4SDimitry Andric }
1278480093f4SDimitry Andric 
runOnLoop(Loop * L)1279480093f4SDimitry Andric bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
1280480093f4SDimitry Andric   bool MadeChange = false;
1281480093f4SDimitry Andric 
1282480093f4SDimitry Andric   // Only prep. the inner-most loop
1283e8d8bef9SDimitry Andric   if (!L->isInnermost())
1284480093f4SDimitry Andric     return MadeChange;
1285480093f4SDimitry Andric 
1286480093f4SDimitry Andric   // Return if already done enough preparation.
1287480093f4SDimitry Andric   if (SuccPrepCount >= MaxVarsPrep)
1288480093f4SDimitry Andric     return MadeChange;
1289480093f4SDimitry Andric 
1290480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
1291480093f4SDimitry Andric 
1292480093f4SDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
1293480093f4SDimitry Andric   // If there is no loop predecessor, or the loop predecessor's terminator
1294480093f4SDimitry Andric   // returns a value (which might contribute to determining the loop's
1295480093f4SDimitry Andric   // iteration space), insert a new preheader for the loop.
1296480093f4SDimitry Andric   if (!LoopPredecessor ||
1297480093f4SDimitry Andric       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
1298480093f4SDimitry Andric     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
1299480093f4SDimitry Andric     if (LoopPredecessor)
1300480093f4SDimitry Andric       MadeChange = true;
1301480093f4SDimitry Andric   }
1302480093f4SDimitry Andric   if (!LoopPredecessor) {
1303480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
1304480093f4SDimitry Andric     return MadeChange;
1305480093f4SDimitry Andric   }
1306480093f4SDimitry Andric   // Check if a load/store has update form. This lambda is used by function
1307480093f4SDimitry Andric   // collectCandidates which can collect candidates for types defined by lambda.
1308349cc55cSDimitry Andric   auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1309fe6060f1SDimitry Andric                                    const Type *PointerElementType) {
1310480093f4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1311480093f4SDimitry Andric     // There are no update forms for Altivec vector load/stores.
1312fe6060f1SDimitry Andric     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
1313480093f4SDimitry Andric       return false;
1314e8d8bef9SDimitry Andric     // There are no update forms for P10 lxvp/stxvp intrinsic.
1315e8d8bef9SDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
1316e8d8bef9SDimitry Andric     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1317e8d8bef9SDimitry Andric                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
1318e8d8bef9SDimitry Andric       return false;
1319480093f4SDimitry Andric     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
1320480093f4SDimitry Andric     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
1321480093f4SDimitry Andric     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
1322480093f4SDimitry Andric     // useless and possible to break some original well-form addressing mode
1323480093f4SDimitry Andric     // to make this pre-inc prep for it.
1324fe6060f1SDimitry Andric     if (PointerElementType->isIntegerTy(64)) {
1325480093f4SDimitry Andric       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
1326480093f4SDimitry Andric       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
1327480093f4SDimitry Andric       if (!LARSCEV || LARSCEV->getLoop() != L)
1328480093f4SDimitry Andric         return false;
1329480093f4SDimitry Andric       if (const SCEVConstant *StepConst =
1330480093f4SDimitry Andric               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
1331480093f4SDimitry Andric         const APInt &ConstInt = StepConst->getValue()->getValue();
1332480093f4SDimitry Andric         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
1333480093f4SDimitry Andric           return false;
1334480093f4SDimitry Andric       }
1335480093f4SDimitry Andric     }
1336480093f4SDimitry Andric     return true;
1337480093f4SDimitry Andric   };
1338480093f4SDimitry Andric 
1339480093f4SDimitry Andric   // Check if a load/store has DS form.
1340349cc55cSDimitry Andric   auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1341fe6060f1SDimitry Andric                               const Type *PointerElementType) {
1342480093f4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1343480093f4SDimitry Andric     if (isa<IntrinsicInst>(I))
1344480093f4SDimitry Andric       return false;
1345480093f4SDimitry Andric     return (PointerElementType->isIntegerTy(64)) ||
1346480093f4SDimitry Andric            (PointerElementType->isFloatTy()) ||
1347480093f4SDimitry Andric            (PointerElementType->isDoubleTy()) ||
1348480093f4SDimitry Andric            (PointerElementType->isIntegerTy(32) &&
1349480093f4SDimitry Andric             llvm::any_of(I->users(),
1350480093f4SDimitry Andric                          [](const User *U) { return isa<SExtInst>(U); }));
1351480093f4SDimitry Andric   };
1352480093f4SDimitry Andric 
1353480093f4SDimitry Andric   // Check if a load/store has DQ form.
1354349cc55cSDimitry Andric   auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1355fe6060f1SDimitry Andric                                const Type *PointerElementType) {
1356480093f4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1357e8d8bef9SDimitry Andric     // Check if it is a P10 lxvp/stxvp intrinsic.
1358e8d8bef9SDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
1359e8d8bef9SDimitry Andric     if (II)
1360e8d8bef9SDimitry Andric       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1361e8d8bef9SDimitry Andric              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
1362e8d8bef9SDimitry Andric     // Check if it is a P9 vector load/store.
1363fe6060f1SDimitry Andric     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
1364480093f4SDimitry Andric   };
1365480093f4SDimitry Andric 
1366349cc55cSDimitry Andric   // Check if a load/store is candidate for chain commoning.
1367349cc55cSDimitry Andric   // If the SCEV is only with one ptr operand in its start, we can use that
1368349cc55cSDimitry Andric   // start as a chain separator. Mark this load/store as a candidate.
1369349cc55cSDimitry Andric   auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
1370349cc55cSDimitry Andric                                        const Type *PointerElementType) {
1371349cc55cSDimitry Andric     const SCEVAddRecExpr *ARSCEV =
1372349cc55cSDimitry Andric         cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
1373349cc55cSDimitry Andric     if (!ARSCEV)
1374349cc55cSDimitry Andric       return false;
1375349cc55cSDimitry Andric 
1376349cc55cSDimitry Andric     if (!ARSCEV->isAffine())
1377349cc55cSDimitry Andric       return false;
1378349cc55cSDimitry Andric 
1379349cc55cSDimitry Andric     const SCEV *Start = ARSCEV->getStart();
1380349cc55cSDimitry Andric 
1381349cc55cSDimitry Andric     // A single pointer. We can treat it as offset 0.
1382349cc55cSDimitry Andric     if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
1383349cc55cSDimitry Andric       return true;
1384349cc55cSDimitry Andric 
1385349cc55cSDimitry Andric     const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
1386349cc55cSDimitry Andric 
1387349cc55cSDimitry Andric     // We need a SCEVAddExpr to include both base and offset.
1388349cc55cSDimitry Andric     if (!ASCEV)
1389349cc55cSDimitry Andric       return false;
1390349cc55cSDimitry Andric 
1391349cc55cSDimitry Andric     // Make sure there is only one pointer operand(base) and all other operands
1392349cc55cSDimitry Andric     // are integer type.
1393349cc55cSDimitry Andric     bool SawPointer = false;
1394349cc55cSDimitry Andric     for (const SCEV *Op : ASCEV->operands()) {
1395349cc55cSDimitry Andric       if (Op->getType()->isPointerTy()) {
1396349cc55cSDimitry Andric         if (SawPointer)
1397349cc55cSDimitry Andric           return false;
1398349cc55cSDimitry Andric         SawPointer = true;
1399349cc55cSDimitry Andric       } else if (!Op->getType()->isIntegerTy())
1400349cc55cSDimitry Andric         return false;
1401349cc55cSDimitry Andric     }
1402349cc55cSDimitry Andric 
1403349cc55cSDimitry Andric     return SawPointer;
1404349cc55cSDimitry Andric   };
1405349cc55cSDimitry Andric 
1406349cc55cSDimitry Andric   // Check if the diff is a constant type. This is used for update/DS/DQ form
1407349cc55cSDimitry Andric   // preparation.
1408349cc55cSDimitry Andric   auto isValidConstantDiff = [](const SCEV *Diff) {
1409349cc55cSDimitry Andric     return dyn_cast<SCEVConstant>(Diff) != nullptr;
1410349cc55cSDimitry Andric   };
1411349cc55cSDimitry Andric 
1412349cc55cSDimitry Andric   // Make sure the diff between the base and new candidate is required type.
1413349cc55cSDimitry Andric   // This is used for chain commoning preparation.
1414349cc55cSDimitry Andric   auto isValidChainCommoningDiff = [](const SCEV *Diff) {
1415349cc55cSDimitry Andric     assert(Diff && "Invalid Diff!\n");
1416349cc55cSDimitry Andric 
1417349cc55cSDimitry Andric     // Don't mess up previous dform prepare.
1418349cc55cSDimitry Andric     if (isa<SCEVConstant>(Diff))
1419349cc55cSDimitry Andric       return false;
1420349cc55cSDimitry Andric 
1421349cc55cSDimitry Andric     // A single integer type offset.
1422349cc55cSDimitry Andric     if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
1423349cc55cSDimitry Andric       return true;
1424349cc55cSDimitry Andric 
1425349cc55cSDimitry Andric     const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
1426349cc55cSDimitry Andric     if (!ADiff)
1427349cc55cSDimitry Andric       return false;
1428349cc55cSDimitry Andric 
1429349cc55cSDimitry Andric     for (const SCEV *Op : ADiff->operands())
1430349cc55cSDimitry Andric       if (!Op->getType()->isIntegerTy())
1431349cc55cSDimitry Andric         return false;
1432349cc55cSDimitry Andric 
1433349cc55cSDimitry Andric     return true;
1434349cc55cSDimitry Andric   };
1435349cc55cSDimitry Andric 
1436349cc55cSDimitry Andric   HasCandidateForPrepare = false;
1437349cc55cSDimitry Andric 
1438349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
1439349cc55cSDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for update
1440349cc55cSDimitry Andric   // form.
1441349cc55cSDimitry Andric   SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
1442349cc55cSDimitry Andric       L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
1443480093f4SDimitry Andric 
1444480093f4SDimitry Andric   // Prepare for update form.
1445480093f4SDimitry Andric   if (!UpdateFormBuckets.empty())
1446480093f4SDimitry Andric     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
1447349cc55cSDimitry Andric   else if (!HasCandidateForPrepare) {
1448349cc55cSDimitry Andric     LLVM_DEBUG(
1449349cc55cSDimitry Andric         dbgs()
1450349cc55cSDimitry Andric         << "No prepare candidates found, stop praparation for current loop!\n");
1451349cc55cSDimitry Andric     // If no candidate for preparing, return early.
1452349cc55cSDimitry Andric     return MadeChange;
1453349cc55cSDimitry Andric   }
1454480093f4SDimitry Andric 
1455349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
1456480093f4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for DS
1457480093f4SDimitry Andric   // form.
1458349cc55cSDimitry Andric   SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
1459349cc55cSDimitry Andric       L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
1460480093f4SDimitry Andric 
1461480093f4SDimitry Andric   // Prepare for DS form.
1462480093f4SDimitry Andric   if (!DSFormBuckets.empty())
1463480093f4SDimitry Andric     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
1464480093f4SDimitry Andric 
1465349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
1466480093f4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for DQ
1467480093f4SDimitry Andric   // form.
1468349cc55cSDimitry Andric   SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
1469349cc55cSDimitry Andric       L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
1470480093f4SDimitry Andric 
1471480093f4SDimitry Andric   // Prepare for DQ form.
1472480093f4SDimitry Andric   if (!DQFormBuckets.empty())
1473480093f4SDimitry Andric     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
1474480093f4SDimitry Andric 
1475349cc55cSDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for chain
1476349cc55cSDimitry Andric   // commoning. With chain commoning, we reuse offsets between the chains, so
1477349cc55cSDimitry Andric   // the register pressure will be reduced.
1478349cc55cSDimitry Andric   if (!EnableChainCommoning) {
1479349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
1480349cc55cSDimitry Andric     return MadeChange;
1481349cc55cSDimitry Andric   }
1482349cc55cSDimitry Andric 
1483349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
1484349cc55cSDimitry Andric   SmallVector<Bucket, 16> Buckets =
1485349cc55cSDimitry Andric       collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
1486349cc55cSDimitry Andric                         MaxVarsChainCommon);
1487349cc55cSDimitry Andric 
1488349cc55cSDimitry Andric   // Prepare for chain commoning.
1489349cc55cSDimitry Andric   if (!Buckets.empty())
1490349cc55cSDimitry Andric     MadeChange |= chainCommoning(L, Buckets);
1491349cc55cSDimitry Andric 
1492480093f4SDimitry Andric   return MadeChange;
1493480093f4SDimitry Andric }
1494