198189755Sczhengsz //===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===//
21260ea74SJinsong Ji //
31260ea74SJinsong Ji // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
41260ea74SJinsong Ji // See https://llvm.org/LICENSE.txt for license information.
51260ea74SJinsong Ji // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61260ea74SJinsong Ji //
71260ea74SJinsong Ji //===----------------------------------------------------------------------===//
81260ea74SJinsong Ji //
91260ea74SJinsong Ji // This file implements a pass to prepare loops for ppc preferred addressing
101260ea74SJinsong Ji // modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with
111260ea74SJinsong Ji // update)
121260ea74SJinsong Ji // Additional PHIs are created for loop induction variables used by load/store
131260ea74SJinsong Ji // instructions so that preferred addressing modes can be used.
141260ea74SJinsong Ji //
151260ea74SJinsong Ji // 1: DS/DQ form preparation, prepare the load/store instructions so that they
161260ea74SJinsong Ji //    can satisfy the DS/DQ form displacement requirements.
171260ea74SJinsong Ji //    Generically, this means transforming loops like this:
181260ea74SJinsong Ji //    for (int i = 0; i < n; ++i) {
191260ea74SJinsong Ji //      unsigned long x1 = *(unsigned long *)(p + i + 5);
201260ea74SJinsong Ji //      unsigned long x2 = *(unsigned long *)(p + i + 9);
211260ea74SJinsong Ji //    }
221260ea74SJinsong Ji //
231260ea74SJinsong Ji //    to look like this:
241260ea74SJinsong Ji //
251260ea74SJinsong Ji //    unsigned NewP = p + 5;
261260ea74SJinsong Ji //    for (int i = 0; i < n; ++i) {
271260ea74SJinsong Ji //      unsigned long x1 = *(unsigned long *)(i + NewP);
281260ea74SJinsong Ji //      unsigned long x2 = *(unsigned long *)(i + NewP + 4);
291260ea74SJinsong Ji //    }
301260ea74SJinsong Ji //
311260ea74SJinsong Ji // 2: D/DS form with update preparation, prepare the load/store instructions so
321260ea74SJinsong Ji //    that we can use update form to do pre-increment.
331260ea74SJinsong Ji //    Generically, this means transforming loops like this:
341260ea74SJinsong Ji //    for (int i = 0; i < n; ++i)
351260ea74SJinsong Ji //      array[i] = c;
361260ea74SJinsong Ji //
371260ea74SJinsong Ji //    to look like this:
381260ea74SJinsong Ji //
391260ea74SJinsong Ji //    T *p = array[-1];
401260ea74SJinsong Ji //    for (int i = 0; i < n; ++i)
411260ea74SJinsong Ji //      *++p = c;
4280e6aff6SChen Zheng //
4380e6aff6SChen Zheng // 3: common multiple chains for the load/stores with same offsets in the loop,
4480e6aff6SChen Zheng //    so that we can reuse the offsets and reduce the register pressure in the
4580e6aff6SChen Zheng //    loop. This transformation can also increase the loop ILP as now each chain
4680e6aff6SChen Zheng //    uses its own loop induction add/addi. But this will increase the number of
4780e6aff6SChen Zheng //    add/addi in the loop.
4880e6aff6SChen Zheng //
4980e6aff6SChen Zheng //    Generically, this means transforming loops like this:
5080e6aff6SChen Zheng //
5180e6aff6SChen Zheng //    char *p;
5280e6aff6SChen Zheng //    A1 = p + base1
5380e6aff6SChen Zheng //    A2 = p + base1 + offset
5480e6aff6SChen Zheng //    B1 = p + base2
5580e6aff6SChen Zheng //    B2 = p + base2 + offset
5680e6aff6SChen Zheng //
5780e6aff6SChen Zheng //    for (int i = 0; i < n; i++)
5880e6aff6SChen Zheng //      unsigned long x1 = *(unsigned long *)(A1 + i);
5980e6aff6SChen Zheng //      unsigned long x2 = *(unsigned long *)(A2 + i)
6080e6aff6SChen Zheng //      unsigned long x3 = *(unsigned long *)(B1 + i);
6180e6aff6SChen Zheng //      unsigned long x4 = *(unsigned long *)(B2 + i);
6280e6aff6SChen Zheng //    }
6380e6aff6SChen Zheng //
6480e6aff6SChen Zheng //    to look like this:
6580e6aff6SChen Zheng //
6680e6aff6SChen Zheng //    A1_new = p + base1 // chain 1
6780e6aff6SChen Zheng //    B1_new = p + base2 // chain 2, now inside the loop, common offset is
6880e6aff6SChen Zheng //                       // reused.
6980e6aff6SChen Zheng //
7080e6aff6SChen Zheng //    for (long long i = 0; i < n; i+=count) {
7180e6aff6SChen Zheng //      unsigned long x1 = *(unsigned long *)(A1_new + i);
7280e6aff6SChen Zheng //      unsigned long x2 = *(unsigned long *)((A1_new + i) + offset);
7380e6aff6SChen Zheng //      unsigned long x3 = *(unsigned long *)(B1_new + i);
7480e6aff6SChen Zheng //      unsigned long x4 = *(unsigned long *)((B1_new + i) + offset);
7580e6aff6SChen Zheng //    }
761260ea74SJinsong Ji //===----------------------------------------------------------------------===//
771260ea74SJinsong Ji 
781260ea74SJinsong Ji #include "PPC.h"
791260ea74SJinsong Ji #include "PPCSubtarget.h"
801260ea74SJinsong Ji #include "PPCTargetMachine.h"
811260ea74SJinsong Ji #include "llvm/ADT/DepthFirstIterator.h"
821260ea74SJinsong Ji #include "llvm/ADT/SmallPtrSet.h"
831260ea74SJinsong Ji #include "llvm/ADT/SmallSet.h"
841260ea74SJinsong Ji #include "llvm/ADT/SmallVector.h"
851260ea74SJinsong Ji #include "llvm/ADT/Statistic.h"
861260ea74SJinsong Ji #include "llvm/Analysis/LoopInfo.h"
871260ea74SJinsong Ji #include "llvm/Analysis/ScalarEvolution.h"
881260ea74SJinsong Ji #include "llvm/Analysis/ScalarEvolutionExpressions.h"
891260ea74SJinsong Ji #include "llvm/IR/BasicBlock.h"
901260ea74SJinsong Ji #include "llvm/IR/CFG.h"
911260ea74SJinsong Ji #include "llvm/IR/Dominators.h"
921260ea74SJinsong Ji #include "llvm/IR/Instruction.h"
931260ea74SJinsong Ji #include "llvm/IR/Instructions.h"
941260ea74SJinsong Ji #include "llvm/IR/IntrinsicInst.h"
953f78605aSBaptiste Saleil #include "llvm/IR/IntrinsicsPowerPC.h"
961260ea74SJinsong Ji #include "llvm/IR/Module.h"
971260ea74SJinsong Ji #include "llvm/IR/Type.h"
981260ea74SJinsong Ji #include "llvm/IR/Value.h"
991260ea74SJinsong Ji #include "llvm/InitializePasses.h"
1001260ea74SJinsong Ji #include "llvm/Pass.h"
1011260ea74SJinsong Ji #include "llvm/Support/Casting.h"
1021260ea74SJinsong Ji #include "llvm/Support/CommandLine.h"
1031260ea74SJinsong Ji #include "llvm/Support/Debug.h"
1041260ea74SJinsong Ji #include "llvm/Transforms/Scalar.h"
1051260ea74SJinsong Ji #include "llvm/Transforms/Utils.h"
1061260ea74SJinsong Ji #include "llvm/Transforms/Utils/BasicBlockUtils.h"
1071260ea74SJinsong Ji #include "llvm/Transforms/Utils/Local.h"
1081260ea74SJinsong Ji #include "llvm/Transforms/Utils/LoopUtils.h"
109bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
1101260ea74SJinsong Ji #include <cassert>
1111260ea74SJinsong Ji #include <iterator>
1121260ea74SJinsong Ji #include <utility>
1131260ea74SJinsong Ji 
11471acce68SMindong Chen #define DEBUG_TYPE "ppc-loop-instr-form-prep"
11571acce68SMindong Chen 
1161260ea74SJinsong Ji using namespace llvm;
1171260ea74SJinsong Ji 
118f6db18fdSChen Zheng static cl::opt<unsigned>
119f6db18fdSChen Zheng     MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
120f6db18fdSChen Zheng                 cl::desc("Potential common base number threshold per function "
121f6db18fdSChen Zheng                          "for PPC loop prep"));
1221260ea74SJinsong Ji 
1231260ea74SJinsong Ji static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
1241260ea74SJinsong Ji                                  cl::init(true), cl::Hidden,
1251260ea74SJinsong Ji   cl::desc("prefer update form when ds form is also a update form"));
1261260ea74SJinsong Ji 
127eec9ca62SChen Zheng static cl::opt<bool> EnableUpdateFormForNonConstInc(
128eec9ca62SChen Zheng     "ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden,
129eec9ca62SChen Zheng     cl::desc("prepare update form when the load/store increment is a loop "
130eec9ca62SChen Zheng              "invariant non-const value."));
131eec9ca62SChen Zheng 
13280e6aff6SChen Zheng static cl::opt<bool> EnableChainCommoning(
133eeed1545SChen Zheng     "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
13480e6aff6SChen Zheng     cl::desc("Enable chain commoning in PPC loop prepare pass."));
13580e6aff6SChen Zheng 
1361260ea74SJinsong Ji // Sum of following 3 per loop thresholds for all loops can not be larger
1371260ea74SJinsong Ji // than MaxVarsPrep.
13866a03d10SChen Zheng // now the thresholds for each kind prep are exterimental values on Power9.
1391260ea74SJinsong Ji static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
1401260ea74SJinsong Ji                                  cl::Hidden, cl::init(3),
1411260ea74SJinsong Ji   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
1421260ea74SJinsong Ji            "form"));
1431260ea74SJinsong Ji 
1441260ea74SJinsong Ji static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
1451260ea74SJinsong Ji                                  cl::Hidden, cl::init(3),
1461260ea74SJinsong Ji   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
1471260ea74SJinsong Ji 
1481260ea74SJinsong Ji static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
14966a03d10SChen Zheng                                  cl::Hidden, cl::init(8),
1501260ea74SJinsong Ji   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
1511260ea74SJinsong Ji 
15280e6aff6SChen Zheng // Commoning chain will reduce the register pressure, so we don't consider about
15380e6aff6SChen Zheng // the PHI nodes number.
15480e6aff6SChen Zheng // But commoning chain will increase the addi/add number in the loop and also
15580e6aff6SChen Zheng // increase loop ILP. Maximum chain number should be same with hardware
15680e6aff6SChen Zheng // IssueWidth, because we won't benefit from ILP if the parallel chains number
15780e6aff6SChen Zheng // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so
15880e6aff6SChen Zheng // there would be 4 buckets at most on P9(IssueWidth is 8).
15980e6aff6SChen Zheng static cl::opt<unsigned> MaxVarsChainCommon(
16080e6aff6SChen Zheng     "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
16180e6aff6SChen Zheng     cl::desc("Bucket number per loop for PPC loop chain common"));
1621260ea74SJinsong Ji 
1631260ea74SJinsong Ji // If would not be profitable if the common base has only one load/store, ISEL
1641260ea74SJinsong Ji // should already be able to choose best load/store form based on offset for
1651260ea74SJinsong Ji // single load/store. Set minimal profitable value default to 2 and make it as
1661260ea74SJinsong Ji // an option.
1671260ea74SJinsong Ji static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
1681260ea74SJinsong Ji                                     cl::Hidden, cl::init(2),
1691260ea74SJinsong Ji   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
1701260ea74SJinsong Ji            "preparation"));
1711260ea74SJinsong Ji 
17280e6aff6SChen Zheng static cl::opt<unsigned> ChainCommonPrepMinThreshold(
17380e6aff6SChen Zheng     "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
17480e6aff6SChen Zheng     cl::desc("Minimal common base load/store instructions triggering chain "
17580e6aff6SChen Zheng              "commoning preparation. Must be not smaller than 4"));
17680e6aff6SChen Zheng 
1771260ea74SJinsong Ji STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
1781260ea74SJinsong Ji STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
1791260ea74SJinsong Ji STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
1801260ea74SJinsong Ji STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
1811260ea74SJinsong Ji STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
1821260ea74SJinsong Ji STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
18380e6aff6SChen Zheng STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
1841260ea74SJinsong Ji 
1851260ea74SJinsong Ji namespace {
1861260ea74SJinsong Ji   struct BucketElement {
BucketElement__anonfe56763d0111::BucketElement1871bf05fbcSChen Zheng     BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
BucketElement__anonfe56763d0111::BucketElement1881260ea74SJinsong Ji     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
1891260ea74SJinsong Ji 
1901bf05fbcSChen Zheng     const SCEV *Offset;
1911260ea74SJinsong Ji     Instruction *Instr;
1921260ea74SJinsong Ji   };
1931260ea74SJinsong Ji 
1941260ea74SJinsong Ji   struct Bucket {
Bucket__anonfe56763d0111::Bucket19580e6aff6SChen Zheng     Bucket(const SCEV *B, Instruction *I)
19680e6aff6SChen Zheng         : BaseSCEV(B), Elements(1, BucketElement(I)) {
19780e6aff6SChen Zheng       ChainSize = 0;
19880e6aff6SChen Zheng     }
1991260ea74SJinsong Ji 
20080e6aff6SChen Zheng     // The base of the whole bucket.
2011260ea74SJinsong Ji     const SCEV *BaseSCEV;
20280e6aff6SChen Zheng 
20380e6aff6SChen Zheng     // All elements in the bucket. In the bucket, the element with the BaseSCEV
20480e6aff6SChen Zheng     // has no offset and all other elements are stored as offsets to the
20580e6aff6SChen Zheng     // BaseSCEV.
2061260ea74SJinsong Ji     SmallVector<BucketElement, 16> Elements;
20780e6aff6SChen Zheng 
20880e6aff6SChen Zheng     // The potential chains size. This is used for chain commoning only.
20980e6aff6SChen Zheng     unsigned ChainSize;
21080e6aff6SChen Zheng 
21180e6aff6SChen Zheng     // The base for each potential chain. This is used for chain commoning only.
21280e6aff6SChen Zheng     SmallVector<BucketElement, 16> ChainBases;
2131260ea74SJinsong Ji   };
2141260ea74SJinsong Ji 
2151260ea74SJinsong Ji   // "UpdateForm" is not a real PPC instruction form, it stands for dform
2161260ea74SJinsong Ji   // load/store with update like ldu/stdu, or Prefetch intrinsic.
2171260ea74SJinsong Ji   // For DS form instructions, their displacements must be multiple of 4.
2181260ea74SJinsong Ji   // For DQ form instructions, their displacements must be multiple of 16.
219eec9ca62SChen Zheng   enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
2201260ea74SJinsong Ji 
22198189755Sczhengsz   class PPCLoopInstrFormPrep : public FunctionPass {
2221260ea74SJinsong Ji   public:
2231260ea74SJinsong Ji     static char ID; // Pass ID, replacement for typeid
2241260ea74SJinsong Ji 
PPCLoopInstrFormPrep()22598189755Sczhengsz     PPCLoopInstrFormPrep() : FunctionPass(ID) {
22698189755Sczhengsz       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
2271260ea74SJinsong Ji     }
2281260ea74SJinsong Ji 
PPCLoopInstrFormPrep(PPCTargetMachine & TM)22998189755Sczhengsz     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
23098189755Sczhengsz       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
2311260ea74SJinsong Ji     }
2321260ea74SJinsong Ji 
getAnalysisUsage(AnalysisUsage & AU) const2331260ea74SJinsong Ji     void getAnalysisUsage(AnalysisUsage &AU) const override {
2341260ea74SJinsong Ji       AU.addPreserved<DominatorTreeWrapperPass>();
2351260ea74SJinsong Ji       AU.addRequired<LoopInfoWrapperPass>();
2361260ea74SJinsong Ji       AU.addPreserved<LoopInfoWrapperPass>();
2371260ea74SJinsong Ji       AU.addRequired<ScalarEvolutionWrapperPass>();
2381260ea74SJinsong Ji     }
2391260ea74SJinsong Ji 
2401260ea74SJinsong Ji     bool runOnFunction(Function &F) override;
2411260ea74SJinsong Ji 
2421260ea74SJinsong Ji   private:
2431260ea74SJinsong Ji     PPCTargetMachine *TM = nullptr;
2441260ea74SJinsong Ji     const PPCSubtarget *ST;
2451260ea74SJinsong Ji     DominatorTree *DT;
2461260ea74SJinsong Ji     LoopInfo *LI;
2471260ea74SJinsong Ji     ScalarEvolution *SE;
2481260ea74SJinsong Ji     bool PreserveLCSSA;
24913755436SChen Zheng     bool HasCandidateForPrepare;
2501260ea74SJinsong Ji 
2511260ea74SJinsong Ji     /// Successful preparation number for Update/DS/DQ form in all inner most
2521260ea74SJinsong Ji     /// loops. One successful preparation will put one common base out of loop,
2531260ea74SJinsong Ji     /// this may leads to register presure like LICM does.
2541260ea74SJinsong Ji     /// Make sure total preparation number can be controlled by option.
2551260ea74SJinsong Ji     unsigned SuccPrepCount;
2561260ea74SJinsong Ji 
2571260ea74SJinsong Ji     bool runOnLoop(Loop *L);
2581260ea74SJinsong Ji 
2591260ea74SJinsong Ji     /// Check if required PHI node is already exist in Loop \p L.
2601260ea74SJinsong Ji     bool alreadyPrepared(Loop *L, Instruction *MemI,
2611260ea74SJinsong Ji                          const SCEV *BasePtrStartSCEV,
262eec9ca62SChen Zheng                          const SCEV *BasePtrIncSCEV, PrepForm Form);
263946e69d2SChen Zheng 
264946e69d2SChen Zheng     /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
265946e69d2SChen Zheng     Value *getNodeForInc(Loop *L, Instruction *MemI,
266946e69d2SChen Zheng                          const SCEV *BasePtrIncSCEV);
2671260ea74SJinsong Ji 
26880e6aff6SChen Zheng     /// Common chains to reuse offsets for a loop to reduce register pressure.
26980e6aff6SChen Zheng     bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
27080e6aff6SChen Zheng 
27180e6aff6SChen Zheng     /// Find out the potential commoning chains and their bases.
27280e6aff6SChen Zheng     bool prepareBasesForCommoningChains(Bucket &BucketChain);
27380e6aff6SChen Zheng 
27480e6aff6SChen Zheng     /// Rewrite load/store according to the common chains.
27580e6aff6SChen Zheng     bool
27680e6aff6SChen Zheng     rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
27780e6aff6SChen Zheng                                         SmallSet<BasicBlock *, 16> &BBChanged);
27880e6aff6SChen Zheng 
2791260ea74SJinsong Ji     /// Collect condition matched(\p isValidCandidate() returns true)
2801260ea74SJinsong Ji     /// candidates in Loop \p L.
281be5d454fSArthur Eubanks     SmallVector<Bucket, 16> collectCandidates(
282be5d454fSArthur Eubanks         Loop *L,
28380e6aff6SChen Zheng         std::function<bool(const Instruction *, Value *, const Type *)>
2841260ea74SJinsong Ji             isValidCandidate,
28580e6aff6SChen Zheng         std::function<bool(const SCEV *)> isValidDiff,
2861260ea74SJinsong Ji         unsigned MaxCandidateNum);
2871260ea74SJinsong Ji 
28880e6aff6SChen Zheng     /// Add a candidate to candidates \p Buckets if diff between candidate and
28980e6aff6SChen Zheng     /// one base in \p Buckets matches \p isValidDiff.
2901260ea74SJinsong Ji     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
2911260ea74SJinsong Ji                          SmallVector<Bucket, 16> &Buckets,
29280e6aff6SChen Zheng                          std::function<bool(const SCEV *)> isValidDiff,
2931260ea74SJinsong Ji                          unsigned MaxCandidateNum);
2941260ea74SJinsong Ji 
2951260ea74SJinsong Ji     /// Prepare all candidates in \p Buckets for update form.
2961260ea74SJinsong Ji     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
2971260ea74SJinsong Ji 
2981260ea74SJinsong Ji     /// Prepare all candidates in \p Buckets for displacement form, now for
2991260ea74SJinsong Ji     /// ds/dq.
300eec9ca62SChen Zheng     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
3011260ea74SJinsong Ji 
3021260ea74SJinsong Ji     /// Prepare for one chain \p BucketChain, find the best base element and
3031260ea74SJinsong Ji     /// update all other elements in \p BucketChain accordingly.
3041260ea74SJinsong Ji     /// \p Form is used to find the best base element.
3051260ea74SJinsong Ji     /// If success, best base element must be stored as the first element of
3061260ea74SJinsong Ji     /// \p BucketChain.
3071260ea74SJinsong Ji     /// Return false if no base element found, otherwise return true.
308eec9ca62SChen Zheng     bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
3091260ea74SJinsong Ji 
3101260ea74SJinsong Ji     /// Prepare for one chain \p BucketChain, find the best base element and
3111260ea74SJinsong Ji     /// update all other elements in \p BucketChain accordingly.
3121260ea74SJinsong Ji     /// If success, best base element must be stored as the first element of
3131260ea74SJinsong Ji     /// \p BucketChain.
3141260ea74SJinsong Ji     /// Return false if no base element found, otherwise return true.
3151260ea74SJinsong Ji     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
3161260ea74SJinsong Ji 
3171260ea74SJinsong Ji     /// Rewrite load/store instructions in \p BucketChain according to
3181260ea74SJinsong Ji     /// preparation.
3191260ea74SJinsong Ji     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
3201260ea74SJinsong Ji                            SmallSet<BasicBlock *, 16> &BBChanged,
321eec9ca62SChen Zheng                            PrepForm Form);
3221bf05fbcSChen Zheng 
3231bf05fbcSChen Zheng     /// Rewrite for the base load/store of a chain.
3241bf05fbcSChen Zheng     std::pair<Instruction *, Instruction *>
3251bf05fbcSChen Zheng     rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
326eec9ca62SChen Zheng                    Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
3271bf05fbcSChen Zheng                    SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
3281bf05fbcSChen Zheng 
3291bf05fbcSChen Zheng     /// Rewrite for the other load/stores of a chain according to the new \p
3301bf05fbcSChen Zheng     /// Base.
3311bf05fbcSChen Zheng     Instruction *
3321bf05fbcSChen Zheng     rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
3331bf05fbcSChen Zheng                             const BucketElement &Element, Value *OffToBase,
3341bf05fbcSChen Zheng                             SmallPtrSet<Value *, 16> &DeletedPtrs);
3351260ea74SJinsong Ji   };
3361260ea74SJinsong Ji 
3371260ea74SJinsong Ji } // end anonymous namespace
3381260ea74SJinsong Ji 
33998189755Sczhengsz char PPCLoopInstrFormPrep::ID = 0;
34098189755Sczhengsz static const char *name = "Prepare loop for ppc preferred instruction forms";
34198189755Sczhengsz INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
3421260ea74SJinsong Ji INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3431260ea74SJinsong Ji INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
34498189755Sczhengsz INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
3451260ea74SJinsong Ji 
346df9a51daSBenjamin Kramer static constexpr StringRef PHINodeNameSuffix    = ".phi";
347df9a51daSBenjamin Kramer static constexpr StringRef CastNodeNameSuffix   = ".cast";
348df9a51daSBenjamin Kramer static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
349df9a51daSBenjamin Kramer static constexpr StringRef GEPNodeOffNameSuffix = ".off";
3501260ea74SJinsong Ji 
createPPCLoopInstrFormPrepPass(PPCTargetMachine & TM)35198189755Sczhengsz FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
35298189755Sczhengsz   return new PPCLoopInstrFormPrep(TM);
3531260ea74SJinsong Ji }
3541260ea74SJinsong Ji 
IsPtrInBounds(Value * BasePtr)3551260ea74SJinsong Ji static bool IsPtrInBounds(Value *BasePtr) {
3561260ea74SJinsong Ji   Value *StrippedBasePtr = BasePtr;
3571260ea74SJinsong Ji   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
3581260ea74SJinsong Ji     StrippedBasePtr = BC->getOperand(0);
3591260ea74SJinsong Ji   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
3601260ea74SJinsong Ji     return GEP->isInBounds();
3611260ea74SJinsong Ji 
3621260ea74SJinsong Ji   return false;
3631260ea74SJinsong Ji }
3641260ea74SJinsong Ji 
getInstrName(const Value * I,StringRef Suffix)365df9a51daSBenjamin Kramer static std::string getInstrName(const Value *I, StringRef Suffix) {
3661260ea74SJinsong Ji   assert(I && "Invalid paramater!");
3671260ea74SJinsong Ji   if (I->hasName())
3681260ea74SJinsong Ji     return (I->getName() + Suffix).str();
3691260ea74SJinsong Ji   else
3701260ea74SJinsong Ji     return "";
3711260ea74SJinsong Ji }
3721260ea74SJinsong Ji 
getPointerOperandAndType(Value * MemI,Type ** PtrElementType=nullptr)3738671191dSJinsong Ji static Value *getPointerOperandAndType(Value *MemI,
3748671191dSJinsong Ji                                        Type **PtrElementType = nullptr) {
3751260ea74SJinsong Ji 
3768671191dSJinsong Ji   Value *PtrValue = nullptr;
3778671191dSJinsong Ji   Type *PointerElementType = nullptr;
3788671191dSJinsong Ji 
3798671191dSJinsong Ji   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
3808671191dSJinsong Ji     PtrValue = LMemI->getPointerOperand();
3818671191dSJinsong Ji     PointerElementType = LMemI->getType();
3828671191dSJinsong Ji   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
3838671191dSJinsong Ji     PtrValue = SMemI->getPointerOperand();
3848671191dSJinsong Ji     PointerElementType = SMemI->getValueOperand()->getType();
3858671191dSJinsong Ji   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
3868671191dSJinsong Ji     PointerElementType = Type::getInt8Ty(MemI->getContext());
3878671191dSJinsong Ji     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
3888671191dSJinsong Ji         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
3898671191dSJinsong Ji       PtrValue = IMemI->getArgOperand(0);
3908671191dSJinsong Ji     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
3918671191dSJinsong Ji       PtrValue = IMemI->getArgOperand(1);
3928671191dSJinsong Ji     }
3938671191dSJinsong Ji   }
3948671191dSJinsong Ji   /*Get ElementType if PtrElementType is not null.*/
3958671191dSJinsong Ji   if (PtrElementType)
3968671191dSJinsong Ji     *PtrElementType = PointerElementType;
3978671191dSJinsong Ji 
3988671191dSJinsong Ji   return PtrValue;
3991260ea74SJinsong Ji }
4001260ea74SJinsong Ji 
runOnFunction(Function & F)40198189755Sczhengsz bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
4021260ea74SJinsong Ji   if (skipFunction(F))
4031260ea74SJinsong Ji     return false;
4041260ea74SJinsong Ji 
4051260ea74SJinsong Ji   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4061260ea74SJinsong Ji   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4071260ea74SJinsong Ji   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
4081260ea74SJinsong Ji   DT = DTWP ? &DTWP->getDomTree() : nullptr;
4091260ea74SJinsong Ji   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
4101260ea74SJinsong Ji   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
4111260ea74SJinsong Ji   SuccPrepCount = 0;
4121260ea74SJinsong Ji 
4131260ea74SJinsong Ji   bool MadeChange = false;
4141260ea74SJinsong Ji 
4159db0e216SKazu Hirata   for (Loop *I : *LI)
4169db0e216SKazu Hirata     for (Loop *L : depth_first(I))
4179db0e216SKazu Hirata       MadeChange |= runOnLoop(L);
4181260ea74SJinsong Ji 
4191260ea74SJinsong Ji   return MadeChange;
4201260ea74SJinsong Ji }
4211260ea74SJinsong Ji 
42280e6aff6SChen Zheng // Finding the minimal(chain_number + reusable_offset_number) is a complicated
42380e6aff6SChen Zheng // algorithmic problem.
42480e6aff6SChen Zheng // For now, the algorithm used here is simply adjusted to handle the case for
42580e6aff6SChen Zheng // manually unrolling cases.
42680e6aff6SChen Zheng // FIXME: use a more powerful algorithm to find minimal sum of chain_number and
42780e6aff6SChen Zheng // reusable_offset_number for one base with multiple offsets.
prepareBasesForCommoningChains(Bucket & CBucket)42880e6aff6SChen Zheng bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
42980e6aff6SChen Zheng   // The minimal size for profitable chain commoning:
43080e6aff6SChen Zheng   // A1 = base + offset1
43180e6aff6SChen Zheng   // A2 = base + offset2 (offset2 - offset1 = X)
43280e6aff6SChen Zheng   // A3 = base + offset3
43380e6aff6SChen Zheng   // A4 = base + offset4 (offset4 - offset3 = X)
43480e6aff6SChen Zheng   // ======>
43580e6aff6SChen Zheng   // base1 = base + offset1
43680e6aff6SChen Zheng   // base2 = base + offset3
43780e6aff6SChen Zheng   // A1 = base1
43880e6aff6SChen Zheng   // A2 = base1 + X
43980e6aff6SChen Zheng   // A3 = base2
44080e6aff6SChen Zheng   // A4 = base2 + X
44180e6aff6SChen Zheng   //
44280e6aff6SChen Zheng   // There is benefit because of reuse of offest 'X'.
44380e6aff6SChen Zheng 
44480e6aff6SChen Zheng   assert(ChainCommonPrepMinThreshold >= 4 &&
44580e6aff6SChen Zheng          "Thredhold can not be smaller than 4!\n");
44680e6aff6SChen Zheng   if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
44780e6aff6SChen Zheng     return false;
44880e6aff6SChen Zheng 
44980e6aff6SChen Zheng   // We simply select the FirstOffset as the first reusable offset between each
45080e6aff6SChen Zheng   // chain element 1 and element 0.
45180e6aff6SChen Zheng   const SCEV *FirstOffset = CBucket.Elements[1].Offset;
45280e6aff6SChen Zheng 
45380e6aff6SChen Zheng   // Figure out how many times above FirstOffset is used in the chain.
45480e6aff6SChen Zheng   // For a success commoning chain candidate, offset difference between each
45580e6aff6SChen Zheng   // chain element 1 and element 0 must be also FirstOffset.
45680e6aff6SChen Zheng   unsigned FirstOffsetReusedCount = 1;
45780e6aff6SChen Zheng 
45880e6aff6SChen Zheng   // Figure out how many times above FirstOffset is used in the first chain.
45980e6aff6SChen Zheng   // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
46080e6aff6SChen Zheng   unsigned FirstOffsetReusedCountInFirstChain = 1;
46180e6aff6SChen Zheng 
46280e6aff6SChen Zheng   unsigned EleNum = CBucket.Elements.size();
46380e6aff6SChen Zheng   bool SawChainSeparater = false;
46480e6aff6SChen Zheng   for (unsigned j = 2; j != EleNum; ++j) {
46580e6aff6SChen Zheng     if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
46680e6aff6SChen Zheng                          CBucket.Elements[j - 1].Offset) == FirstOffset) {
46780e6aff6SChen Zheng       if (!SawChainSeparater)
46880e6aff6SChen Zheng         FirstOffsetReusedCountInFirstChain++;
46980e6aff6SChen Zheng       FirstOffsetReusedCount++;
47080e6aff6SChen Zheng     } else
47180e6aff6SChen Zheng       // For now, if we meet any offset which is not FirstOffset, we assume we
47280e6aff6SChen Zheng       // find a new Chain.
47380e6aff6SChen Zheng       // This makes us miss some opportunities.
47480e6aff6SChen Zheng       // For example, we can common:
47580e6aff6SChen Zheng       //
47680e6aff6SChen Zheng       // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
47780e6aff6SChen Zheng       //
47880e6aff6SChen Zheng       // as two chains:
47980e6aff6SChen Zheng       // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
48080e6aff6SChen Zheng       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
48180e6aff6SChen Zheng       //
48280e6aff6SChen Zheng       // But we fail to common:
48380e6aff6SChen Zheng       //
48480e6aff6SChen Zheng       // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
48580e6aff6SChen Zheng       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
48680e6aff6SChen Zheng 
48780e6aff6SChen Zheng       SawChainSeparater = true;
48880e6aff6SChen Zheng   }
48980e6aff6SChen Zheng 
49080e6aff6SChen Zheng   // FirstOffset is not reused, skip this bucket.
49180e6aff6SChen Zheng   if (FirstOffsetReusedCount == 1)
49280e6aff6SChen Zheng     return false;
49380e6aff6SChen Zheng 
49480e6aff6SChen Zheng   unsigned ChainNum =
49580e6aff6SChen Zheng       FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
49680e6aff6SChen Zheng 
49780e6aff6SChen Zheng   // All elements are increased by FirstOffset.
49880e6aff6SChen Zheng   // The number of chains should be sqrt(EleNum).
49980e6aff6SChen Zheng   if (!SawChainSeparater)
5007591d210SChen Zheng     ChainNum = (unsigned)sqrt((double)EleNum);
50180e6aff6SChen Zheng 
50280e6aff6SChen Zheng   CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
50380e6aff6SChen Zheng 
50480e6aff6SChen Zheng   // If this is not a perfect chain(eg: not all elements can be put inside
50580e6aff6SChen Zheng   // commoning chains.), skip now.
50680e6aff6SChen Zheng   if (CBucket.ChainSize * ChainNum != EleNum)
50780e6aff6SChen Zheng     return false;
50880e6aff6SChen Zheng 
50980e6aff6SChen Zheng   if (SawChainSeparater) {
51080e6aff6SChen Zheng     // Check that the offset seqs are the same for all chains.
51180e6aff6SChen Zheng     for (unsigned i = 1; i < CBucket.ChainSize; i++)
51280e6aff6SChen Zheng       for (unsigned j = 1; j < ChainNum; j++)
51380e6aff6SChen Zheng         if (CBucket.Elements[i].Offset !=
51480e6aff6SChen Zheng             SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
51580e6aff6SChen Zheng                              CBucket.Elements[j * CBucket.ChainSize].Offset))
51680e6aff6SChen Zheng           return false;
51780e6aff6SChen Zheng   }
51880e6aff6SChen Zheng 
51980e6aff6SChen Zheng   for (unsigned i = 0; i < ChainNum; i++)
52080e6aff6SChen Zheng     CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
52180e6aff6SChen Zheng 
52280e6aff6SChen Zheng   LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
52380e6aff6SChen Zheng 
52480e6aff6SChen Zheng   return true;
52580e6aff6SChen Zheng }
52680e6aff6SChen Zheng 
chainCommoning(Loop * L,SmallVector<Bucket,16> & Buckets)52780e6aff6SChen Zheng bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
52880e6aff6SChen Zheng                                           SmallVector<Bucket, 16> &Buckets) {
52980e6aff6SChen Zheng   bool MadeChange = false;
53080e6aff6SChen Zheng 
53180e6aff6SChen Zheng   if (Buckets.empty())
53280e6aff6SChen Zheng     return MadeChange;
53380e6aff6SChen Zheng 
53480e6aff6SChen Zheng   SmallSet<BasicBlock *, 16> BBChanged;
53580e6aff6SChen Zheng 
53680e6aff6SChen Zheng   for (auto &Bucket : Buckets) {
53780e6aff6SChen Zheng     if (prepareBasesForCommoningChains(Bucket))
53880e6aff6SChen Zheng       MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
53980e6aff6SChen Zheng   }
54080e6aff6SChen Zheng 
54180e6aff6SChen Zheng   if (MadeChange)
54280e6aff6SChen Zheng     for (auto *BB : BBChanged)
54380e6aff6SChen Zheng       DeleteDeadPHIs(BB);
54480e6aff6SChen Zheng   return MadeChange;
54580e6aff6SChen Zheng }
54680e6aff6SChen Zheng 
rewriteLoadStoresForCommoningChains(Loop * L,Bucket & Bucket,SmallSet<BasicBlock *,16> & BBChanged)54780e6aff6SChen Zheng bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
54880e6aff6SChen Zheng     Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
54980e6aff6SChen Zheng   bool MadeChange = false;
55080e6aff6SChen Zheng 
55180e6aff6SChen Zheng   assert(Bucket.Elements.size() ==
55280e6aff6SChen Zheng              Bucket.ChainBases.size() * Bucket.ChainSize &&
55380e6aff6SChen Zheng          "invalid bucket for chain commoning!\n");
55480e6aff6SChen Zheng   SmallPtrSet<Value *, 16> DeletedPtrs;
55580e6aff6SChen Zheng 
55680e6aff6SChen Zheng   BasicBlock *Header = L->getHeader();
55780e6aff6SChen Zheng   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
55880e6aff6SChen Zheng 
55980e6aff6SChen Zheng   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
56080e6aff6SChen Zheng                      "loopprepare-chaincommon");
56180e6aff6SChen Zheng 
56280e6aff6SChen Zheng   for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
56380e6aff6SChen Zheng     unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
56480e6aff6SChen Zheng     const SCEV *BaseSCEV =
56580e6aff6SChen Zheng         ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
56680e6aff6SChen Zheng                                   Bucket.Elements[BaseElemIdx].Offset)
56780e6aff6SChen Zheng                  : Bucket.BaseSCEV;
56880e6aff6SChen Zheng     const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
56980e6aff6SChen Zheng 
57080e6aff6SChen Zheng     // Make sure the base is able to expand.
571*dcf4b733SNikita Popov     if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
57280e6aff6SChen Zheng       return MadeChange;
57380e6aff6SChen Zheng 
57480e6aff6SChen Zheng     assert(BasePtrSCEV->isAffine() &&
57580e6aff6SChen Zheng            "Invalid SCEV type for the base ptr for a candidate chain!\n");
57680e6aff6SChen Zheng 
577eec9ca62SChen Zheng     std::pair<Instruction *, Instruction *> Base = rewriteForBase(
578eec9ca62SChen Zheng         L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
579eec9ca62SChen Zheng         false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs);
58080e6aff6SChen Zheng 
58180e6aff6SChen Zheng     if (!Base.first || !Base.second)
58280e6aff6SChen Zheng       return MadeChange;
58380e6aff6SChen Zheng 
58480e6aff6SChen Zheng     // Keep track of the replacement pointer values we've inserted so that we
58580e6aff6SChen Zheng     // don't generate more pointer values than necessary.
58680e6aff6SChen Zheng     SmallPtrSet<Value *, 16> NewPtrs;
58780e6aff6SChen Zheng     NewPtrs.insert(Base.first);
58880e6aff6SChen Zheng 
58980e6aff6SChen Zheng     for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
59080e6aff6SChen Zheng          ++Idx) {
59180e6aff6SChen Zheng       BucketElement &I = Bucket.Elements[Idx];
59280e6aff6SChen Zheng       Value *Ptr = getPointerOperandAndType(I.Instr);
59380e6aff6SChen Zheng       assert(Ptr && "No pointer operand");
59480e6aff6SChen Zheng       if (NewPtrs.count(Ptr))
59580e6aff6SChen Zheng         continue;
59680e6aff6SChen Zheng 
59780e6aff6SChen Zheng       const SCEV *OffsetSCEV =
59880e6aff6SChen Zheng           BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
59980e6aff6SChen Zheng                                          Bucket.Elements[BaseElemIdx].Offset)
60080e6aff6SChen Zheng                       : Bucket.Elements[Idx].Offset;
60180e6aff6SChen Zheng 
60280e6aff6SChen Zheng       // Make sure offset is able to expand. Only need to check one time as the
60380e6aff6SChen Zheng       // offsets are reused between different chains.
60480e6aff6SChen Zheng       if (!BaseElemIdx)
605*dcf4b733SNikita Popov         if (!SCEVE.isSafeToExpand(OffsetSCEV))
60680e6aff6SChen Zheng           return false;
60780e6aff6SChen Zheng 
60880e6aff6SChen Zheng       Value *OffsetValue = SCEVE.expandCodeFor(
609631f44f3SChen Zheng           OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
61080e6aff6SChen Zheng 
61180e6aff6SChen Zheng       Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
61280e6aff6SChen Zheng                                                     OffsetValue, DeletedPtrs);
61380e6aff6SChen Zheng 
61480e6aff6SChen Zheng       assert(NewPtr && "Wrong rewrite!\n");
61580e6aff6SChen Zheng       NewPtrs.insert(NewPtr);
61680e6aff6SChen Zheng     }
61780e6aff6SChen Zheng 
61880e6aff6SChen Zheng     ++ChainCommoningRewritten;
61980e6aff6SChen Zheng   }
62080e6aff6SChen Zheng 
62180e6aff6SChen Zheng   // Clear the rewriter cache, because values that are in the rewriter's cache
62280e6aff6SChen Zheng   // can be deleted below, causing the AssertingVH in the cache to trigger.
62380e6aff6SChen Zheng   SCEVE.clear();
62480e6aff6SChen Zheng 
62580e6aff6SChen Zheng   for (auto *Ptr : DeletedPtrs) {
62680e6aff6SChen Zheng     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
62780e6aff6SChen Zheng       BBChanged.insert(IDel->getParent());
62880e6aff6SChen Zheng     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
62980e6aff6SChen Zheng   }
63080e6aff6SChen Zheng 
63180e6aff6SChen Zheng   MadeChange = true;
63280e6aff6SChen Zheng   return MadeChange;
63380e6aff6SChen Zheng }
63480e6aff6SChen Zheng 
6351bf05fbcSChen Zheng // Rewrite the new base according to BasePtrSCEV.
6361bf05fbcSChen Zheng // bb.loop.preheader:
6371bf05fbcSChen Zheng //   %newstart = ...
6381bf05fbcSChen Zheng // bb.loop.body:
6391bf05fbcSChen Zheng //   %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
6401bf05fbcSChen Zheng //   ...
6411bf05fbcSChen Zheng //   %add = getelementptr %phinode, %inc
6421bf05fbcSChen Zheng //
6431bf05fbcSChen Zheng // First returned instruciton is %phinode (or a type cast to %phinode), caller
6441bf05fbcSChen Zheng // needs this value to rewrite other load/stores in the same chain.
6451bf05fbcSChen Zheng // Second returned instruction is %add, caller needs this value to rewrite other
6461bf05fbcSChen Zheng // load/stores in the same chain.
6471bf05fbcSChen Zheng std::pair<Instruction *, Instruction *>
rewriteForBase(Loop * L,const SCEVAddRecExpr * BasePtrSCEV,Instruction * BaseMemI,bool CanPreInc,PrepForm Form,SCEVExpander & SCEVE,SmallPtrSet<Value *,16> & DeletedPtrs)6481bf05fbcSChen Zheng PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
6491bf05fbcSChen Zheng                                      Instruction *BaseMemI, bool CanPreInc,
650eec9ca62SChen Zheng                                      PrepForm Form, SCEVExpander &SCEVE,
6511bf05fbcSChen Zheng                                      SmallPtrSet<Value *, 16> &DeletedPtrs) {
6521bf05fbcSChen Zheng 
6531bf05fbcSChen Zheng   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
6541bf05fbcSChen Zheng 
6551bf05fbcSChen Zheng   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
6561bf05fbcSChen Zheng 
6571bf05fbcSChen Zheng   Value *BasePtr = getPointerOperandAndType(BaseMemI);
6581bf05fbcSChen Zheng   assert(BasePtr && "No pointer operand");
6591bf05fbcSChen Zheng 
6601bf05fbcSChen Zheng   Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
6611bf05fbcSChen Zheng   Type *I8PtrTy =
6621bf05fbcSChen Zheng       Type::getInt8PtrTy(BaseMemI->getParent()->getContext(),
6631bf05fbcSChen Zheng                          BasePtr->getType()->getPointerAddressSpace());
6641bf05fbcSChen Zheng 
6651bf05fbcSChen Zheng   bool IsConstantInc = false;
6661bf05fbcSChen Zheng   const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
6671bf05fbcSChen Zheng   Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
6681bf05fbcSChen Zheng 
6691bf05fbcSChen Zheng   const SCEVConstant *BasePtrIncConstantSCEV =
6701bf05fbcSChen Zheng       dyn_cast<SCEVConstant>(BasePtrIncSCEV);
6711bf05fbcSChen Zheng   if (BasePtrIncConstantSCEV)
6721bf05fbcSChen Zheng     IsConstantInc = true;
6731bf05fbcSChen Zheng 
6741bf05fbcSChen Zheng   // No valid representation for the increment.
6751bf05fbcSChen Zheng   if (!IncNode) {
6761bf05fbcSChen Zheng     LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
6771bf05fbcSChen Zheng     return std::make_pair(nullptr, nullptr);
6781bf05fbcSChen Zheng   }
6791bf05fbcSChen Zheng 
680eec9ca62SChen Zheng   if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) {
681eec9ca62SChen Zheng     LLVM_DEBUG(
682eec9ca62SChen Zheng         dbgs()
683eec9ca62SChen Zheng         << "Update form prepare for non-const increment is not enabled!\n");
684eec9ca62SChen Zheng     return std::make_pair(nullptr, nullptr);
685eec9ca62SChen Zheng   }
686eec9ca62SChen Zheng 
6871bf05fbcSChen Zheng   const SCEV *BasePtrStartSCEV = nullptr;
6881bf05fbcSChen Zheng   if (CanPreInc) {
6891bf05fbcSChen Zheng     assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
6901bf05fbcSChen Zheng            "Increment is not loop invariant!\n");
6911bf05fbcSChen Zheng     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
6921bf05fbcSChen Zheng                                         IsConstantInc ? BasePtrIncConstantSCEV
6931bf05fbcSChen Zheng                                                       : BasePtrIncSCEV);
6941bf05fbcSChen Zheng   } else
6951bf05fbcSChen Zheng     BasePtrStartSCEV = BasePtrSCEV->getStart();
6961bf05fbcSChen Zheng 
6971bf05fbcSChen Zheng   if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
6981bf05fbcSChen Zheng     LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
6991bf05fbcSChen Zheng     return std::make_pair(nullptr, nullptr);
7001bf05fbcSChen Zheng   }
7011bf05fbcSChen Zheng 
7021bf05fbcSChen Zheng   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
7031bf05fbcSChen Zheng 
7041bf05fbcSChen Zheng   BasicBlock *Header = L->getHeader();
7051bf05fbcSChen Zheng   unsigned HeaderLoopPredCount = pred_size(Header);
7061bf05fbcSChen Zheng   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
7071bf05fbcSChen Zheng 
7081bf05fbcSChen Zheng   PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
7091bf05fbcSChen Zheng                                     getInstrName(BaseMemI, PHINodeNameSuffix),
7101bf05fbcSChen Zheng                                     Header->getFirstNonPHI());
7111bf05fbcSChen Zheng 
7121bf05fbcSChen Zheng   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
7131bf05fbcSChen Zheng                                             LoopPredecessor->getTerminator());
7141bf05fbcSChen Zheng 
7151bf05fbcSChen Zheng   // Note that LoopPredecessor might occur in the predecessor list multiple
7161bf05fbcSChen Zheng   // times, and we need to add it the right number of times.
7171bf05fbcSChen Zheng   for (auto PI : predecessors(Header)) {
7181bf05fbcSChen Zheng     if (PI != LoopPredecessor)
7191bf05fbcSChen Zheng       continue;
7201bf05fbcSChen Zheng 
7211bf05fbcSChen Zheng     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
7221bf05fbcSChen Zheng   }
7231bf05fbcSChen Zheng 
7241bf05fbcSChen Zheng   Instruction *PtrInc = nullptr;
7251bf05fbcSChen Zheng   Instruction *NewBasePtr = nullptr;
7261bf05fbcSChen Zheng   if (CanPreInc) {
7271bf05fbcSChen Zheng     Instruction *InsPoint = &*Header->getFirstInsertionPt();
7281bf05fbcSChen Zheng     PtrInc = GetElementPtrInst::Create(
7291bf05fbcSChen Zheng         I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
7301bf05fbcSChen Zheng         InsPoint);
7311bf05fbcSChen Zheng     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
7321bf05fbcSChen Zheng     for (auto PI : predecessors(Header)) {
7331bf05fbcSChen Zheng       if (PI == LoopPredecessor)
7341bf05fbcSChen Zheng         continue;
7351bf05fbcSChen Zheng 
7361bf05fbcSChen Zheng       NewPHI->addIncoming(PtrInc, PI);
7371bf05fbcSChen Zheng     }
7381bf05fbcSChen Zheng     if (PtrInc->getType() != BasePtr->getType())
7391bf05fbcSChen Zheng       NewBasePtr =
7401bf05fbcSChen Zheng           new BitCastInst(PtrInc, BasePtr->getType(),
7411bf05fbcSChen Zheng                           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
7421bf05fbcSChen Zheng     else
7431bf05fbcSChen Zheng       NewBasePtr = PtrInc;
7441bf05fbcSChen Zheng   } else {
7451bf05fbcSChen Zheng     // Note that LoopPredecessor might occur in the predecessor list multiple
7461bf05fbcSChen Zheng     // times, and we need to make sure no more incoming value for them in PHI.
7471bf05fbcSChen Zheng     for (auto PI : predecessors(Header)) {
7481bf05fbcSChen Zheng       if (PI == LoopPredecessor)
7491bf05fbcSChen Zheng         continue;
7501bf05fbcSChen Zheng 
7511bf05fbcSChen Zheng       // For the latch predecessor, we need to insert a GEP just before the
7521bf05fbcSChen Zheng       // terminator to increase the address.
7531bf05fbcSChen Zheng       BasicBlock *BB = PI;
7541bf05fbcSChen Zheng       Instruction *InsPoint = BB->getTerminator();
7551bf05fbcSChen Zheng       PtrInc = GetElementPtrInst::Create(
7561bf05fbcSChen Zheng           I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
7571bf05fbcSChen Zheng           InsPoint);
7581bf05fbcSChen Zheng       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
7591bf05fbcSChen Zheng 
7601bf05fbcSChen Zheng       NewPHI->addIncoming(PtrInc, PI);
7611bf05fbcSChen Zheng     }
7621bf05fbcSChen Zheng     PtrInc = NewPHI;
7631bf05fbcSChen Zheng     if (NewPHI->getType() != BasePtr->getType())
7641bf05fbcSChen Zheng       NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
7651bf05fbcSChen Zheng                                    getInstrName(NewPHI, CastNodeNameSuffix),
7661bf05fbcSChen Zheng                                    &*Header->getFirstInsertionPt());
7671bf05fbcSChen Zheng     else
7681bf05fbcSChen Zheng       NewBasePtr = NewPHI;
7691bf05fbcSChen Zheng   }
7701bf05fbcSChen Zheng 
7711bf05fbcSChen Zheng   BasePtr->replaceAllUsesWith(NewBasePtr);
7721bf05fbcSChen Zheng 
7731bf05fbcSChen Zheng   DeletedPtrs.insert(BasePtr);
7741bf05fbcSChen Zheng 
7751bf05fbcSChen Zheng   return std::make_pair(NewBasePtr, PtrInc);
7761bf05fbcSChen Zheng }
7771bf05fbcSChen Zheng 
rewriteForBucketElement(std::pair<Instruction *,Instruction * > Base,const BucketElement & Element,Value * OffToBase,SmallPtrSet<Value *,16> & DeletedPtrs)7781bf05fbcSChen Zheng Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
7791bf05fbcSChen Zheng     std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
7801bf05fbcSChen Zheng     Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
7811bf05fbcSChen Zheng   Instruction *NewBasePtr = Base.first;
7821bf05fbcSChen Zheng   Instruction *PtrInc = Base.second;
7831bf05fbcSChen Zheng   assert((NewBasePtr && PtrInc) && "base does not exist!\n");
7841bf05fbcSChen Zheng 
7851bf05fbcSChen Zheng   Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
7861bf05fbcSChen Zheng 
7871bf05fbcSChen Zheng   Value *Ptr = getPointerOperandAndType(Element.Instr);
7881bf05fbcSChen Zheng   assert(Ptr && "No pointer operand");
7891bf05fbcSChen Zheng 
7901bf05fbcSChen Zheng   Instruction *RealNewPtr;
7911bf05fbcSChen Zheng   if (!Element.Offset ||
7921bf05fbcSChen Zheng       (isa<SCEVConstant>(Element.Offset) &&
7931bf05fbcSChen Zheng        cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
7941bf05fbcSChen Zheng     RealNewPtr = NewBasePtr;
7951bf05fbcSChen Zheng   } else {
7961bf05fbcSChen Zheng     Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
7971bf05fbcSChen Zheng     if (PtrIP && isa<Instruction>(NewBasePtr) &&
7981bf05fbcSChen Zheng         cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
7991bf05fbcSChen Zheng       PtrIP = nullptr;
8001bf05fbcSChen Zheng     else if (PtrIP && isa<PHINode>(PtrIP))
8011bf05fbcSChen Zheng       PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
8021bf05fbcSChen Zheng     else if (!PtrIP)
8031bf05fbcSChen Zheng       PtrIP = Element.Instr;
8041bf05fbcSChen Zheng 
8051bf05fbcSChen Zheng     assert(OffToBase && "There should be an offset for non base element!\n");
8061bf05fbcSChen Zheng     GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
8071bf05fbcSChen Zheng         I8Ty, PtrInc, OffToBase,
8081bf05fbcSChen Zheng         getInstrName(Element.Instr, GEPNodeOffNameSuffix), PtrIP);
8091bf05fbcSChen Zheng     if (!PtrIP)
8101bf05fbcSChen Zheng       NewPtr->insertAfter(cast<Instruction>(PtrInc));
8111bf05fbcSChen Zheng     NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
8121bf05fbcSChen Zheng     RealNewPtr = NewPtr;
8131bf05fbcSChen Zheng   }
8141bf05fbcSChen Zheng 
8151bf05fbcSChen Zheng   Instruction *ReplNewPtr;
8161bf05fbcSChen Zheng   if (Ptr->getType() != RealNewPtr->getType()) {
8171bf05fbcSChen Zheng     ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
8181bf05fbcSChen Zheng                                  getInstrName(Ptr, CastNodeNameSuffix));
8191bf05fbcSChen Zheng     ReplNewPtr->insertAfter(RealNewPtr);
8201bf05fbcSChen Zheng   } else
8211bf05fbcSChen Zheng     ReplNewPtr = RealNewPtr;
8221bf05fbcSChen Zheng 
8231bf05fbcSChen Zheng   Ptr->replaceAllUsesWith(ReplNewPtr);
8241bf05fbcSChen Zheng   DeletedPtrs.insert(Ptr);
8251bf05fbcSChen Zheng 
8261bf05fbcSChen Zheng   return ReplNewPtr;
8271bf05fbcSChen Zheng }
8281bf05fbcSChen Zheng 
addOneCandidate(Instruction * MemI,const SCEV * LSCEV,SmallVector<Bucket,16> & Buckets,std::function<bool (const SCEV *)> isValidDiff,unsigned MaxCandidateNum)82980e6aff6SChen Zheng void PPCLoopInstrFormPrep::addOneCandidate(
83080e6aff6SChen Zheng     Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
83180e6aff6SChen Zheng     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
8328671191dSJinsong Ji   assert((MemI && getPointerOperandAndType(MemI)) &&
8331260ea74SJinsong Ji          "Candidate should be a memory instruction.");
8341260ea74SJinsong Ji   assert(LSCEV && "Invalid SCEV for Ptr value.");
83580e6aff6SChen Zheng 
8361260ea74SJinsong Ji   bool FoundBucket = false;
8371260ea74SJinsong Ji   for (auto &B : Buckets) {
83880e6aff6SChen Zheng     if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
83980e6aff6SChen Zheng         cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
84080e6aff6SChen Zheng       continue;
8411260ea74SJinsong Ji     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
84280e6aff6SChen Zheng     if (isValidDiff(Diff)) {
84380e6aff6SChen Zheng       B.Elements.push_back(BucketElement(Diff, MemI));
8441260ea74SJinsong Ji       FoundBucket = true;
8451260ea74SJinsong Ji       break;
8461260ea74SJinsong Ji     }
8471260ea74SJinsong Ji   }
8481260ea74SJinsong Ji 
8491260ea74SJinsong Ji   if (!FoundBucket) {
85080e6aff6SChen Zheng     if (Buckets.size() == MaxCandidateNum) {
85180e6aff6SChen Zheng       LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
85280e6aff6SChen Zheng                         << MaxCandidateNum << "\n");
8531260ea74SJinsong Ji       return;
85480e6aff6SChen Zheng     }
8551260ea74SJinsong Ji     Buckets.push_back(Bucket(LSCEV, MemI));
8561260ea74SJinsong Ji   }
8571260ea74SJinsong Ji }
8581260ea74SJinsong Ji 
collectCandidates(Loop * L,std::function<bool (const Instruction *,Value *,const Type *)> isValidCandidate,std::function<bool (const SCEV *)> isValidDiff,unsigned MaxCandidateNum)85998189755Sczhengsz SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
8601260ea74SJinsong Ji     Loop *L,
86180e6aff6SChen Zheng     std::function<bool(const Instruction *, Value *, const Type *)>
862be5d454fSArthur Eubanks         isValidCandidate,
86380e6aff6SChen Zheng     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
8641260ea74SJinsong Ji   SmallVector<Bucket, 16> Buckets;
86580e6aff6SChen Zheng 
8661260ea74SJinsong Ji   for (const auto &BB : L->blocks())
8671260ea74SJinsong Ji     for (auto &J : *BB) {
8688671191dSJinsong Ji       Value *PtrValue = nullptr;
8698671191dSJinsong Ji       Type *PointerElementType = nullptr;
8708671191dSJinsong Ji       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
8711260ea74SJinsong Ji 
8728671191dSJinsong Ji       if (!PtrValue)
8738671191dSJinsong Ji         continue;
8741260ea74SJinsong Ji 
8758671191dSJinsong Ji       if (PtrValue->getType()->getPointerAddressSpace())
8761260ea74SJinsong Ji         continue;
8771260ea74SJinsong Ji 
8781260ea74SJinsong Ji       if (L->isLoopInvariant(PtrValue))
8791260ea74SJinsong Ji         continue;
8801260ea74SJinsong Ji 
8811260ea74SJinsong Ji       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
8821260ea74SJinsong Ji       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
8831260ea74SJinsong Ji       if (!LARSCEV || LARSCEV->getLoop() != L)
8841260ea74SJinsong Ji         continue;
8851260ea74SJinsong Ji 
88613755436SChen Zheng       // Mark that we have candidates for preparing.
88713755436SChen Zheng       HasCandidateForPrepare = true;
88813755436SChen Zheng 
889be5d454fSArthur Eubanks       if (isValidCandidate(&J, PtrValue, PointerElementType))
89080e6aff6SChen Zheng         addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
8911260ea74SJinsong Ji     }
8921260ea74SJinsong Ji   return Buckets;
8931260ea74SJinsong Ji }
8941260ea74SJinsong Ji 
prepareBaseForDispFormChain(Bucket & BucketChain,PrepForm Form)89598189755Sczhengsz bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
896eec9ca62SChen Zheng                                                        PrepForm Form) {
8971260ea74SJinsong Ji   // RemainderOffsetInfo details:
8981260ea74SJinsong Ji   // key:            value of (Offset urem DispConstraint). For DSForm, it can
8991260ea74SJinsong Ji   //                 be [0, 4).
9001260ea74SJinsong Ji   // first of pair:  the index of first BucketElement whose remainder is equal
9011260ea74SJinsong Ji   //                 to key. For key 0, this value must be 0.
9021260ea74SJinsong Ji   // second of pair: number of load/stores with the same remainder.
9031260ea74SJinsong Ji   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
9041260ea74SJinsong Ji 
9051260ea74SJinsong Ji   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
9061260ea74SJinsong Ji     if (!BucketChain.Elements[j].Offset)
9071260ea74SJinsong Ji       RemainderOffsetInfo[0] = std::make_pair(0, 1);
9081260ea74SJinsong Ji     else {
9091bf05fbcSChen Zheng       unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
9101bf05fbcSChen Zheng                                ->getAPInt()
9111bf05fbcSChen Zheng                                .urem(Form);
9121260ea74SJinsong Ji       if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
9131260ea74SJinsong Ji         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
9141260ea74SJinsong Ji       else
9151260ea74SJinsong Ji         RemainderOffsetInfo[Remainder].second++;
9161260ea74SJinsong Ji     }
9171260ea74SJinsong Ji   }
9181260ea74SJinsong Ji   // Currently we choose the most profitable base as the one which has the max
9191260ea74SJinsong Ji   // number of load/store with same remainder.
9201260ea74SJinsong Ji   // FIXME: adjust the base selection strategy according to load/store offset
9211260ea74SJinsong Ji   // distribution.
9221260ea74SJinsong Ji   // For example, if we have one candidate chain for DS form preparation, which
9231260ea74SJinsong Ji   // contains following load/stores with different remainders:
9241260ea74SJinsong Ji   // 1: 10 load/store whose remainder is 1;
9251260ea74SJinsong Ji   // 2: 9 load/store whose remainder is 2;
9261260ea74SJinsong Ji   // 3: 1 for remainder 3 and 0 for remainder 0;
9271260ea74SJinsong Ji   // Now we will choose the first load/store whose remainder is 1 as base and
9281260ea74SJinsong Ji   // adjust all other load/stores according to new base, so we will get 10 DS
9291260ea74SJinsong Ji   // form and 10 X form.
9301260ea74SJinsong Ji   // But we should be more clever, for this case we could use two bases, one for
93125961201SChen Zheng   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
93225961201SChen Zheng   // 1 X form.
9331260ea74SJinsong Ji   unsigned MaxCountRemainder = 0;
9341260ea74SJinsong Ji   for (unsigned j = 0; j < (unsigned)Form; j++)
9351260ea74SJinsong Ji     if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
9361260ea74SJinsong Ji         RemainderOffsetInfo[j].second >
9371260ea74SJinsong Ji             RemainderOffsetInfo[MaxCountRemainder].second)
9381260ea74SJinsong Ji       MaxCountRemainder = j;
9391260ea74SJinsong Ji 
9401260ea74SJinsong Ji   // Abort when there are too few insts with common base.
9411260ea74SJinsong Ji   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
9421260ea74SJinsong Ji     return false;
9431260ea74SJinsong Ji 
9441260ea74SJinsong Ji   // If the first value is most profitable, no needed to adjust BucketChain
9451260ea74SJinsong Ji   // elements as they are substracted the first value when collecting.
9461260ea74SJinsong Ji   if (MaxCountRemainder == 0)
9471260ea74SJinsong Ji     return true;
9481260ea74SJinsong Ji 
9491260ea74SJinsong Ji   // Adjust load/store to the new chosen base.
9501260ea74SJinsong Ji   const SCEV *Offset =
9511260ea74SJinsong Ji       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
9521260ea74SJinsong Ji   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
9531260ea74SJinsong Ji   for (auto &E : BucketChain.Elements) {
9541260ea74SJinsong Ji     if (E.Offset)
9551260ea74SJinsong Ji       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
9561260ea74SJinsong Ji     else
9571260ea74SJinsong Ji       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
9581260ea74SJinsong Ji   }
9591260ea74SJinsong Ji 
9601260ea74SJinsong Ji   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
9611260ea74SJinsong Ji             BucketChain.Elements[0]);
9621260ea74SJinsong Ji   return true;
9631260ea74SJinsong Ji }
9641260ea74SJinsong Ji 
9651260ea74SJinsong Ji // FIXME: implement a more clever base choosing policy.
9661260ea74SJinsong Ji // Currently we always choose an exist load/store offset. This maybe lead to
9671260ea74SJinsong Ji // suboptimal code sequences. For example, for one DS chain with offsets
9681260ea74SJinsong Ji // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
9691260ea74SJinsong Ji // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
9701260ea74SJinsong Ji // multipler of 4, it cannot be represented by sint16.
prepareBaseForUpdateFormChain(Bucket & BucketChain)97198189755Sczhengsz bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
9721260ea74SJinsong Ji   // We have a choice now of which instruction's memory operand we use as the
9731260ea74SJinsong Ji   // base for the generated PHI. Always picking the first instruction in each
9741260ea74SJinsong Ji   // bucket does not work well, specifically because that instruction might
9751260ea74SJinsong Ji   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
9761260ea74SJinsong Ji   // the choice is somewhat arbitrary, because the backend will happily
9771260ea74SJinsong Ji   // generate direct offsets from both the pre-incremented and
9781260ea74SJinsong Ji   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
9791260ea74SJinsong Ji   // instruction in each bucket, and adjust the recurrence and other offsets
9801260ea74SJinsong Ji   // accordingly.
9811260ea74SJinsong Ji   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
9821260ea74SJinsong Ji     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
9831260ea74SJinsong Ji       if (II->getIntrinsicID() == Intrinsic::prefetch)
9841260ea74SJinsong Ji         continue;
9851260ea74SJinsong Ji 
9861260ea74SJinsong Ji     // If we'd otherwise pick the first element anyway, there's nothing to do.
9871260ea74SJinsong Ji     if (j == 0)
9881260ea74SJinsong Ji       break;
9891260ea74SJinsong Ji 
9901260ea74SJinsong Ji     // If our chosen element has no offset from the base pointer, there's
9911260ea74SJinsong Ji     // nothing to do.
9921260ea74SJinsong Ji     if (!BucketChain.Elements[j].Offset ||
9931bf05fbcSChen Zheng         cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
9941260ea74SJinsong Ji       break;
9951260ea74SJinsong Ji 
9961260ea74SJinsong Ji     const SCEV *Offset = BucketChain.Elements[j].Offset;
9971260ea74SJinsong Ji     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
9981260ea74SJinsong Ji     for (auto &E : BucketChain.Elements) {
9991260ea74SJinsong Ji       if (E.Offset)
10001260ea74SJinsong Ji         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
10011260ea74SJinsong Ji       else
10021260ea74SJinsong Ji         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
10031260ea74SJinsong Ji     }
10041260ea74SJinsong Ji 
10051260ea74SJinsong Ji     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
10061260ea74SJinsong Ji     break;
10071260ea74SJinsong Ji   }
10081260ea74SJinsong Ji   return true;
10091260ea74SJinsong Ji }
10101260ea74SJinsong Ji 
rewriteLoadStores(Loop * L,Bucket & BucketChain,SmallSet<BasicBlock *,16> & BBChanged,PrepForm Form)10111bf05fbcSChen Zheng bool PPCLoopInstrFormPrep::rewriteLoadStores(
10121bf05fbcSChen Zheng     Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
1013eec9ca62SChen Zheng     PrepForm Form) {
10141260ea74SJinsong Ji   bool MadeChange = false;
10151bf05fbcSChen Zheng 
10161260ea74SJinsong Ji   const SCEVAddRecExpr *BasePtrSCEV =
10171260ea74SJinsong Ji       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
10181260ea74SJinsong Ji   if (!BasePtrSCEV->isAffine())
10191260ea74SJinsong Ji     return MadeChange;
10201260ea74SJinsong Ji 
10211bf05fbcSChen Zheng   BasicBlock *Header = L->getHeader();
102280e6aff6SChen Zheng   SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
102380e6aff6SChen Zheng                      "loopprepare-formrewrite");
1024*dcf4b733SNikita Popov   if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
1025*dcf4b733SNikita Popov     return MadeChange;
1026*dcf4b733SNikita Popov 
1027*dcf4b733SNikita Popov   SmallPtrSet<Value *, 16> DeletedPtrs;
1028946e69d2SChen Zheng 
10291260ea74SJinsong Ji   // For some DS form load/store instructions, it can also be an update form,
1030946e69d2SChen Zheng   // if the stride is constant and is a multipler of 4. Use update form if
1031946e69d2SChen Zheng   // prefer it.
10321bf05fbcSChen Zheng   bool CanPreInc = (Form == UpdateForm ||
10331bf05fbcSChen Zheng                     ((Form == DSForm) &&
10341bf05fbcSChen Zheng                      isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
10351bf05fbcSChen Zheng                      !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
10361bf05fbcSChen Zheng                           ->getAPInt()
10371bf05fbcSChen Zheng                           .urem(4) &&
10381bf05fbcSChen Zheng                      PreferUpdateForm));
10391260ea74SJinsong Ji 
10401bf05fbcSChen Zheng   std::pair<Instruction *, Instruction *> Base =
10411bf05fbcSChen Zheng       rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
10421bf05fbcSChen Zheng                      CanPreInc, Form, SCEVE, DeletedPtrs);
10431bf05fbcSChen Zheng 
10441bf05fbcSChen Zheng   if (!Base.first || !Base.second)
10451260ea74SJinsong Ji     return MadeChange;
10461260ea74SJinsong Ji 
10471260ea74SJinsong Ji   // Keep track of the replacement pointer values we've inserted so that we
10481260ea74SJinsong Ji   // don't generate more pointer values than necessary.
10491260ea74SJinsong Ji   SmallPtrSet<Value *, 16> NewPtrs;
10501bf05fbcSChen Zheng   NewPtrs.insert(Base.first);
10511260ea74SJinsong Ji 
10521260ea74SJinsong Ji   for (auto I = std::next(BucketChain.Elements.begin()),
10531260ea74SJinsong Ji        IE = BucketChain.Elements.end(); I != IE; ++I) {
10548671191dSJinsong Ji     Value *Ptr = getPointerOperandAndType(I->Instr);
10551260ea74SJinsong Ji     assert(Ptr && "No pointer operand");
10561260ea74SJinsong Ji     if (NewPtrs.count(Ptr))
10571260ea74SJinsong Ji       continue;
10581260ea74SJinsong Ji 
10591bf05fbcSChen Zheng     Instruction *NewPtr = rewriteForBucketElement(
10601bf05fbcSChen Zheng         Base, *I,
10611bf05fbcSChen Zheng         I->Offset ? cast<SCEVConstant>(I->Offset)->getValue() : nullptr,
10621bf05fbcSChen Zheng         DeletedPtrs);
10631bf05fbcSChen Zheng     assert(NewPtr && "wrong rewrite!\n");
10641bf05fbcSChen Zheng     NewPtrs.insert(NewPtr);
10651260ea74SJinsong Ji   }
10661260ea74SJinsong Ji 
10671bf05fbcSChen Zheng   // Clear the rewriter cache, because values that are in the rewriter's cache
10681bf05fbcSChen Zheng   // can be deleted below, causing the AssertingVH in the cache to trigger.
10691bf05fbcSChen Zheng   SCEVE.clear();
10701bf05fbcSChen Zheng 
10711bf05fbcSChen Zheng   for (auto *Ptr : DeletedPtrs) {
10721260ea74SJinsong Ji     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
10731260ea74SJinsong Ji       BBChanged.insert(IDel->getParent());
10741260ea74SJinsong Ji     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
10751260ea74SJinsong Ji   }
10761260ea74SJinsong Ji 
10771260ea74SJinsong Ji   MadeChange = true;
10781260ea74SJinsong Ji 
10791260ea74SJinsong Ji   SuccPrepCount++;
10801260ea74SJinsong Ji 
10811260ea74SJinsong Ji   if (Form == DSForm && !CanPreInc)
10821260ea74SJinsong Ji     DSFormChainRewritten++;
10831260ea74SJinsong Ji   else if (Form == DQForm)
10841260ea74SJinsong Ji     DQFormChainRewritten++;
10851260ea74SJinsong Ji   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
10861260ea74SJinsong Ji     UpdFormChainRewritten++;
10871260ea74SJinsong Ji 
10881260ea74SJinsong Ji   return MadeChange;
10891260ea74SJinsong Ji }
10901260ea74SJinsong Ji 
updateFormPrep(Loop * L,SmallVector<Bucket,16> & Buckets)109198189755Sczhengsz bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
10921260ea74SJinsong Ji                                        SmallVector<Bucket, 16> &Buckets) {
10931260ea74SJinsong Ji   bool MadeChange = false;
10941260ea74SJinsong Ji   if (Buckets.empty())
10951260ea74SJinsong Ji     return MadeChange;
10961260ea74SJinsong Ji   SmallSet<BasicBlock *, 16> BBChanged;
10971260ea74SJinsong Ji   for (auto &Bucket : Buckets)
10981260ea74SJinsong Ji     // The base address of each bucket is transformed into a phi and the others
10991260ea74SJinsong Ji     // are rewritten based on new base.
11001260ea74SJinsong Ji     if (prepareBaseForUpdateFormChain(Bucket))
11011260ea74SJinsong Ji       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
11021260ea74SJinsong Ji 
11031260ea74SJinsong Ji   if (MadeChange)
110486a5c326SChen Zheng     for (auto *BB : BBChanged)
11051260ea74SJinsong Ji       DeleteDeadPHIs(BB);
11061260ea74SJinsong Ji   return MadeChange;
11071260ea74SJinsong Ji }
11081260ea74SJinsong Ji 
dispFormPrep(Loop * L,SmallVector<Bucket,16> & Buckets,PrepForm Form)1109eec9ca62SChen Zheng bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L,
1110eec9ca62SChen Zheng                                         SmallVector<Bucket, 16> &Buckets,
1111eec9ca62SChen Zheng                                         PrepForm Form) {
11121260ea74SJinsong Ji   bool MadeChange = false;
11131260ea74SJinsong Ji 
11141260ea74SJinsong Ji   if (Buckets.empty())
11151260ea74SJinsong Ji     return MadeChange;
11161260ea74SJinsong Ji 
11171260ea74SJinsong Ji   SmallSet<BasicBlock *, 16> BBChanged;
11181260ea74SJinsong Ji   for (auto &Bucket : Buckets) {
11191260ea74SJinsong Ji     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
11201260ea74SJinsong Ji       continue;
11211260ea74SJinsong Ji     if (prepareBaseForDispFormChain(Bucket, Form))
11221260ea74SJinsong Ji       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
11231260ea74SJinsong Ji   }
11241260ea74SJinsong Ji 
11251260ea74SJinsong Ji   if (MadeChange)
112686a5c326SChen Zheng     for (auto *BB : BBChanged)
11271260ea74SJinsong Ji       DeleteDeadPHIs(BB);
11281260ea74SJinsong Ji   return MadeChange;
11291260ea74SJinsong Ji }
11301260ea74SJinsong Ji 
1131946e69d2SChen Zheng // Find the loop invariant increment node for SCEV BasePtrIncSCEV.
1132946e69d2SChen Zheng // bb.loop.preheader:
1133946e69d2SChen Zheng //   %start = ...
1134946e69d2SChen Zheng // bb.loop.body:
1135946e69d2SChen Zheng //   %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ]
1136946e69d2SChen Zheng //   ...
1137946e69d2SChen Zheng //   %add = add %phinode, %inc  ; %inc is what we want to get.
1138946e69d2SChen Zheng //
getNodeForInc(Loop * L,Instruction * MemI,const SCEV * BasePtrIncSCEV)1139946e69d2SChen Zheng Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
1140946e69d2SChen Zheng                                            const SCEV *BasePtrIncSCEV) {
1141946e69d2SChen Zheng   // If the increment is a constant, no definition is needed.
1142946e69d2SChen Zheng   // Return the value directly.
1143946e69d2SChen Zheng   if (isa<SCEVConstant>(BasePtrIncSCEV))
1144946e69d2SChen Zheng     return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
1145946e69d2SChen Zheng 
1146946e69d2SChen Zheng   if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
1147946e69d2SChen Zheng     return nullptr;
1148946e69d2SChen Zheng 
1149946e69d2SChen Zheng   BasicBlock *BB = MemI->getParent();
1150946e69d2SChen Zheng   if (!BB)
1151946e69d2SChen Zheng     return nullptr;
1152946e69d2SChen Zheng 
1153946e69d2SChen Zheng   BasicBlock *LatchBB = L->getLoopLatch();
1154946e69d2SChen Zheng 
1155946e69d2SChen Zheng   if (!LatchBB)
1156946e69d2SChen Zheng     return nullptr;
1157946e69d2SChen Zheng 
1158946e69d2SChen Zheng   // Run through the PHIs and check their operands to find valid representation
1159946e69d2SChen Zheng   // for the increment SCEV.
1160946e69d2SChen Zheng   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1161946e69d2SChen Zheng   for (auto &CurrentPHI : PHIIter) {
1162946e69d2SChen Zheng     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1163946e69d2SChen Zheng     if (!CurrentPHINode)
1164946e69d2SChen Zheng       continue;
1165946e69d2SChen Zheng 
1166946e69d2SChen Zheng     if (!SE->isSCEVable(CurrentPHINode->getType()))
1167946e69d2SChen Zheng       continue;
1168946e69d2SChen Zheng 
1169946e69d2SChen Zheng     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1170946e69d2SChen Zheng 
1171946e69d2SChen Zheng     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1172946e69d2SChen Zheng     if (!PHIBasePtrSCEV)
1173946e69d2SChen Zheng       continue;
1174946e69d2SChen Zheng 
1175946e69d2SChen Zheng     const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
1176946e69d2SChen Zheng 
1177946e69d2SChen Zheng     if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
1178946e69d2SChen Zheng       continue;
1179946e69d2SChen Zheng 
1180946e69d2SChen Zheng     // Get the incoming value from the loop latch and check if the value has
1181946e69d2SChen Zheng     // the add form with the required increment.
1182946e69d2SChen Zheng     if (Instruction *I = dyn_cast<Instruction>(
1183946e69d2SChen Zheng             CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1184946e69d2SChen Zheng       Value *StrippedBaseI = I;
1185946e69d2SChen Zheng       while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1186946e69d2SChen Zheng         StrippedBaseI = BC->getOperand(0);
1187946e69d2SChen Zheng 
1188946e69d2SChen Zheng       Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1189946e69d2SChen Zheng       if (!StrippedI)
1190946e69d2SChen Zheng         continue;
1191946e69d2SChen Zheng 
1192946e69d2SChen Zheng       // LSR pass may add a getelementptr instruction to do the loop increment,
1193946e69d2SChen Zheng       // also search in that getelementptr instruction.
1194946e69d2SChen Zheng       if (StrippedI->getOpcode() == Instruction::Add ||
1195946e69d2SChen Zheng           (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1196946e69d2SChen Zheng            StrippedI->getNumOperands() == 2)) {
1197946e69d2SChen Zheng         if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1198946e69d2SChen Zheng           return StrippedI->getOperand(0);
1199946e69d2SChen Zheng         if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1200946e69d2SChen Zheng           return StrippedI->getOperand(1);
1201946e69d2SChen Zheng       }
1202946e69d2SChen Zheng     }
1203946e69d2SChen Zheng   }
1204946e69d2SChen Zheng   return nullptr;
1205946e69d2SChen Zheng }
1206946e69d2SChen Zheng 
12071260ea74SJinsong Ji // In order to prepare for the preferred instruction form, a PHI is added.
12081260ea74SJinsong Ji // This function will check to see if that PHI already exists and will return
12091260ea74SJinsong Ji // true if it found an existing PHI with the matched start and increment as the
12101260ea74SJinsong Ji // one we wanted to create.
alreadyPrepared(Loop * L,Instruction * MemI,const SCEV * BasePtrStartSCEV,const SCEV * BasePtrIncSCEV,PrepForm Form)121198189755Sczhengsz bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
12121260ea74SJinsong Ji                                            const SCEV *BasePtrStartSCEV,
1213946e69d2SChen Zheng                                            const SCEV *BasePtrIncSCEV,
1214eec9ca62SChen Zheng                                            PrepForm Form) {
12151260ea74SJinsong Ji   BasicBlock *BB = MemI->getParent();
12161260ea74SJinsong Ji   if (!BB)
12171260ea74SJinsong Ji     return false;
12181260ea74SJinsong Ji 
12191260ea74SJinsong Ji   BasicBlock *PredBB = L->getLoopPredecessor();
12201260ea74SJinsong Ji   BasicBlock *LatchBB = L->getLoopLatch();
12211260ea74SJinsong Ji 
12221260ea74SJinsong Ji   if (!PredBB || !LatchBB)
12231260ea74SJinsong Ji     return false;
12241260ea74SJinsong Ji 
12251260ea74SJinsong Ji   // Run through the PHIs and see if we have some that looks like a preparation
12261260ea74SJinsong Ji   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
12271260ea74SJinsong Ji   for (auto & CurrentPHI : PHIIter) {
12281260ea74SJinsong Ji     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
12291260ea74SJinsong Ji     if (!CurrentPHINode)
12301260ea74SJinsong Ji       continue;
12311260ea74SJinsong Ji 
12321260ea74SJinsong Ji     if (!SE->isSCEVable(CurrentPHINode->getType()))
12331260ea74SJinsong Ji       continue;
12341260ea74SJinsong Ji 
12351260ea74SJinsong Ji     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
12361260ea74SJinsong Ji 
12371260ea74SJinsong Ji     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
12381260ea74SJinsong Ji     if (!PHIBasePtrSCEV)
12391260ea74SJinsong Ji       continue;
12401260ea74SJinsong Ji 
12411260ea74SJinsong Ji     const SCEVConstant *PHIBasePtrIncSCEV =
12421260ea74SJinsong Ji       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
12431260ea74SJinsong Ji     if (!PHIBasePtrIncSCEV)
12441260ea74SJinsong Ji       continue;
12451260ea74SJinsong Ji 
12461260ea74SJinsong Ji     if (CurrentPHINode->getNumIncomingValues() == 2) {
12471260ea74SJinsong Ji       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
12481260ea74SJinsong Ji            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
12491260ea74SJinsong Ji           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
12501260ea74SJinsong Ji            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
12511260ea74SJinsong Ji         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
12521260ea74SJinsong Ji           // The existing PHI (CurrentPHINode) has the same start and increment
12531260ea74SJinsong Ji           // as the PHI that we wanted to create.
1254eec9ca62SChen Zheng           if ((Form == UpdateForm || Form == ChainCommoning ) &&
12551260ea74SJinsong Ji               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
12561260ea74SJinsong Ji             ++PHINodeAlreadyExistsUpdate;
12571260ea74SJinsong Ji             return true;
12581260ea74SJinsong Ji           }
12591260ea74SJinsong Ji           if (Form == DSForm || Form == DQForm) {
12601260ea74SJinsong Ji             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
12611260ea74SJinsong Ji                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
12621260ea74SJinsong Ji             if (Diff && !Diff->getAPInt().urem(Form)) {
12631260ea74SJinsong Ji               if (Form == DSForm)
12641260ea74SJinsong Ji                 ++PHINodeAlreadyExistsDS;
12651260ea74SJinsong Ji               else
12661260ea74SJinsong Ji                 ++PHINodeAlreadyExistsDQ;
12671260ea74SJinsong Ji               return true;
12681260ea74SJinsong Ji             }
12691260ea74SJinsong Ji           }
12701260ea74SJinsong Ji         }
12711260ea74SJinsong Ji       }
12721260ea74SJinsong Ji     }
12731260ea74SJinsong Ji   }
12741260ea74SJinsong Ji   return false;
12751260ea74SJinsong Ji }
12761260ea74SJinsong Ji 
runOnLoop(Loop * L)127798189755Sczhengsz bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
12781260ea74SJinsong Ji   bool MadeChange = false;
12791260ea74SJinsong Ji 
12801260ea74SJinsong Ji   // Only prep. the inner-most loop
1281a7873e5aSStefanos Baziotis   if (!L->isInnermost())
12821260ea74SJinsong Ji     return MadeChange;
12831260ea74SJinsong Ji 
12841260ea74SJinsong Ji   // Return if already done enough preparation.
12851260ea74SJinsong Ji   if (SuccPrepCount >= MaxVarsPrep)
12861260ea74SJinsong Ji     return MadeChange;
12871260ea74SJinsong Ji 
12881260ea74SJinsong Ji   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
12891260ea74SJinsong Ji 
12901260ea74SJinsong Ji   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
12911260ea74SJinsong Ji   // If there is no loop predecessor, or the loop predecessor's terminator
12921260ea74SJinsong Ji   // returns a value (which might contribute to determining the loop's
12931260ea74SJinsong Ji   // iteration space), insert a new preheader for the loop.
12941260ea74SJinsong Ji   if (!LoopPredecessor ||
12951260ea74SJinsong Ji       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
12961260ea74SJinsong Ji     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
12971260ea74SJinsong Ji     if (LoopPredecessor)
12981260ea74SJinsong Ji       MadeChange = true;
12991260ea74SJinsong Ji   }
13001260ea74SJinsong Ji   if (!LoopPredecessor) {
13011260ea74SJinsong Ji     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
13021260ea74SJinsong Ji     return MadeChange;
13031260ea74SJinsong Ji   }
13041260ea74SJinsong Ji   // Check if a load/store has update form. This lambda is used by function
13051260ea74SJinsong Ji   // collectCandidates which can collect candidates for types defined by lambda.
130680e6aff6SChen Zheng   auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1307be5d454fSArthur Eubanks                                    const Type *PointerElementType) {
13081260ea74SJinsong Ji     assert((PtrValue && I) && "Invalid parameter!");
13091260ea74SJinsong Ji     // There are no update forms for Altivec vector load/stores.
1310be5d454fSArthur Eubanks     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
13111260ea74SJinsong Ji       return false;
13123f78605aSBaptiste Saleil     // There are no update forms for P10 lxvp/stxvp intrinsic.
13133f78605aSBaptiste Saleil     auto *II = dyn_cast<IntrinsicInst>(I);
1314c2892978SBaptiste Saleil     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1315c2892978SBaptiste Saleil                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
13163f78605aSBaptiste Saleil       return false;
13171260ea74SJinsong Ji     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
13181260ea74SJinsong Ji     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
13191260ea74SJinsong Ji     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
13201260ea74SJinsong Ji     // useless and possible to break some original well-form addressing mode
13211260ea74SJinsong Ji     // to make this pre-inc prep for it.
1322be5d454fSArthur Eubanks     if (PointerElementType->isIntegerTy(64)) {
13231260ea74SJinsong Ji       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
13241260ea74SJinsong Ji       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
13251260ea74SJinsong Ji       if (!LARSCEV || LARSCEV->getLoop() != L)
13261260ea74SJinsong Ji         return false;
13271260ea74SJinsong Ji       if (const SCEVConstant *StepConst =
13281260ea74SJinsong Ji               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
13291260ea74SJinsong Ji         const APInt &ConstInt = StepConst->getValue()->getValue();
13301260ea74SJinsong Ji         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
13311260ea74SJinsong Ji           return false;
13321260ea74SJinsong Ji       }
13331260ea74SJinsong Ji     }
13341260ea74SJinsong Ji     return true;
13351260ea74SJinsong Ji   };
13361260ea74SJinsong Ji 
13371260ea74SJinsong Ji   // Check if a load/store has DS form.
133880e6aff6SChen Zheng   auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1339be5d454fSArthur Eubanks                               const Type *PointerElementType) {
13401260ea74SJinsong Ji     assert((PtrValue && I) && "Invalid parameter!");
1341f5440ec4Sczhengsz     if (isa<IntrinsicInst>(I))
1342f5440ec4Sczhengsz       return false;
1343f5440ec4Sczhengsz     return (PointerElementType->isIntegerTy(64)) ||
1344f5440ec4Sczhengsz            (PointerElementType->isFloatTy()) ||
1345f5440ec4Sczhengsz            (PointerElementType->isDoubleTy()) ||
1346f5440ec4Sczhengsz            (PointerElementType->isIntegerTy(32) &&
1347f5440ec4Sczhengsz             llvm::any_of(I->users(),
1348f5440ec4Sczhengsz                          [](const User *U) { return isa<SExtInst>(U); }));
13491260ea74SJinsong Ji   };
13501260ea74SJinsong Ji 
13511260ea74SJinsong Ji   // Check if a load/store has DQ form.
135280e6aff6SChen Zheng   auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1353be5d454fSArthur Eubanks                                const Type *PointerElementType) {
13541260ea74SJinsong Ji     assert((PtrValue && I) && "Invalid parameter!");
13553f78605aSBaptiste Saleil     // Check if it is a P10 lxvp/stxvp intrinsic.
13563f78605aSBaptiste Saleil     auto *II = dyn_cast<IntrinsicInst>(I);
13573f78605aSBaptiste Saleil     if (II)
1358c2892978SBaptiste Saleil       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1359c2892978SBaptiste Saleil              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
13603f78605aSBaptiste Saleil     // Check if it is a P9 vector load/store.
1361be5d454fSArthur Eubanks     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
13621260ea74SJinsong Ji   };
13631260ea74SJinsong Ji 
136480e6aff6SChen Zheng   // Check if a load/store is candidate for chain commoning.
136580e6aff6SChen Zheng   // If the SCEV is only with one ptr operand in its start, we can use that
136680e6aff6SChen Zheng   // start as a chain separator. Mark this load/store as a candidate.
136780e6aff6SChen Zheng   auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
136880e6aff6SChen Zheng                                        const Type *PointerElementType) {
136980e6aff6SChen Zheng     const SCEVAddRecExpr *ARSCEV =
137080e6aff6SChen Zheng         cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
137180e6aff6SChen Zheng     if (!ARSCEV)
137280e6aff6SChen Zheng       return false;
137380e6aff6SChen Zheng 
137480e6aff6SChen Zheng     if (!ARSCEV->isAffine())
137580e6aff6SChen Zheng       return false;
137680e6aff6SChen Zheng 
137780e6aff6SChen Zheng     const SCEV *Start = ARSCEV->getStart();
137880e6aff6SChen Zheng 
137980e6aff6SChen Zheng     // A single pointer. We can treat it as offset 0.
138080e6aff6SChen Zheng     if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
138180e6aff6SChen Zheng       return true;
138280e6aff6SChen Zheng 
138380e6aff6SChen Zheng     const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
138480e6aff6SChen Zheng 
138580e6aff6SChen Zheng     // We need a SCEVAddExpr to include both base and offset.
138680e6aff6SChen Zheng     if (!ASCEV)
138780e6aff6SChen Zheng       return false;
138880e6aff6SChen Zheng 
138980e6aff6SChen Zheng     // Make sure there is only one pointer operand(base) and all other operands
139080e6aff6SChen Zheng     // are integer type.
139180e6aff6SChen Zheng     bool SawPointer = false;
139280e6aff6SChen Zheng     for (const SCEV *Op : ASCEV->operands()) {
139380e6aff6SChen Zheng       if (Op->getType()->isPointerTy()) {
139480e6aff6SChen Zheng         if (SawPointer)
139580e6aff6SChen Zheng           return false;
139680e6aff6SChen Zheng         SawPointer = true;
139780e6aff6SChen Zheng       } else if (!Op->getType()->isIntegerTy())
139880e6aff6SChen Zheng         return false;
139980e6aff6SChen Zheng     }
140080e6aff6SChen Zheng 
140180e6aff6SChen Zheng     return SawPointer;
140280e6aff6SChen Zheng   };
140380e6aff6SChen Zheng 
140480e6aff6SChen Zheng   // Check if the diff is a constant type. This is used for update/DS/DQ form
140580e6aff6SChen Zheng   // preparation.
140680e6aff6SChen Zheng   auto isValidConstantDiff = [](const SCEV *Diff) {
140780e6aff6SChen Zheng     return dyn_cast<SCEVConstant>(Diff) != nullptr;
140880e6aff6SChen Zheng   };
140980e6aff6SChen Zheng 
141080e6aff6SChen Zheng   // Make sure the diff between the base and new candidate is required type.
141180e6aff6SChen Zheng   // This is used for chain commoning preparation.
141280e6aff6SChen Zheng   auto isValidChainCommoningDiff = [](const SCEV *Diff) {
141380e6aff6SChen Zheng     assert(Diff && "Invalid Diff!\n");
141480e6aff6SChen Zheng 
141580e6aff6SChen Zheng     // Don't mess up previous dform prepare.
141680e6aff6SChen Zheng     if (isa<SCEVConstant>(Diff))
141780e6aff6SChen Zheng       return false;
141880e6aff6SChen Zheng 
141980e6aff6SChen Zheng     // A single integer type offset.
142080e6aff6SChen Zheng     if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
142180e6aff6SChen Zheng       return true;
142280e6aff6SChen Zheng 
142380e6aff6SChen Zheng     const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
142480e6aff6SChen Zheng     if (!ADiff)
142580e6aff6SChen Zheng       return false;
142680e6aff6SChen Zheng 
142780e6aff6SChen Zheng     for (const SCEV *Op : ADiff->operands())
142880e6aff6SChen Zheng       if (!Op->getType()->isIntegerTy())
142980e6aff6SChen Zheng         return false;
143080e6aff6SChen Zheng 
143180e6aff6SChen Zheng     return true;
143280e6aff6SChen Zheng   };
143380e6aff6SChen Zheng 
143413755436SChen Zheng   HasCandidateForPrepare = false;
143513755436SChen Zheng 
143680e6aff6SChen Zheng   LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
143725961201SChen Zheng   // Collect buckets of comparable addresses used by loads and stores for update
143825961201SChen Zheng   // form.
143980e6aff6SChen Zheng   SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
144080e6aff6SChen Zheng       L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
14411260ea74SJinsong Ji 
14421260ea74SJinsong Ji   // Prepare for update form.
14431260ea74SJinsong Ji   if (!UpdateFormBuckets.empty())
14441260ea74SJinsong Ji     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
144580e6aff6SChen Zheng   else if (!HasCandidateForPrepare) {
144680e6aff6SChen Zheng     LLVM_DEBUG(
144780e6aff6SChen Zheng         dbgs()
144880e6aff6SChen Zheng         << "No prepare candidates found, stop praparation for current loop!\n");
144913755436SChen Zheng     // If no candidate for preparing, return early.
145013755436SChen Zheng     return MadeChange;
145180e6aff6SChen Zheng   }
14521260ea74SJinsong Ji 
145380e6aff6SChen Zheng   LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
14541260ea74SJinsong Ji   // Collect buckets of comparable addresses used by loads and stores for DS
14551260ea74SJinsong Ji   // form.
145680e6aff6SChen Zheng   SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
145780e6aff6SChen Zheng       L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
14581260ea74SJinsong Ji 
14591260ea74SJinsong Ji   // Prepare for DS form.
14601260ea74SJinsong Ji   if (!DSFormBuckets.empty())
14611260ea74SJinsong Ji     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
14621260ea74SJinsong Ji 
146380e6aff6SChen Zheng   LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
14641260ea74SJinsong Ji   // Collect buckets of comparable addresses used by loads and stores for DQ
14651260ea74SJinsong Ji   // form.
146680e6aff6SChen Zheng   SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
146780e6aff6SChen Zheng       L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
14681260ea74SJinsong Ji 
14691260ea74SJinsong Ji   // Prepare for DQ form.
14701260ea74SJinsong Ji   if (!DQFormBuckets.empty())
14711260ea74SJinsong Ji     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
14721260ea74SJinsong Ji 
147380e6aff6SChen Zheng   // Collect buckets of comparable addresses used by loads and stores for chain
147480e6aff6SChen Zheng   // commoning. With chain commoning, we reuse offsets between the chains, so
147580e6aff6SChen Zheng   // the register pressure will be reduced.
147680e6aff6SChen Zheng   if (!EnableChainCommoning) {
147780e6aff6SChen Zheng     LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
147880e6aff6SChen Zheng     return MadeChange;
147980e6aff6SChen Zheng   }
148080e6aff6SChen Zheng 
148180e6aff6SChen Zheng   LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
148280e6aff6SChen Zheng   SmallVector<Bucket, 16> Buckets =
148380e6aff6SChen Zheng       collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
148480e6aff6SChen Zheng                         MaxVarsChainCommon);
148580e6aff6SChen Zheng 
148680e6aff6SChen Zheng   // Prepare for chain commoning.
148780e6aff6SChen Zheng   if (!Buckets.empty())
148880e6aff6SChen Zheng     MadeChange |= chainCommoning(L, Buckets);
148980e6aff6SChen Zheng 
14901260ea74SJinsong Ji   return MadeChange;
14911260ea74SJinsong Ji }
1492