1480093f4SDimitry Andric //===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===// 2480093f4SDimitry Andric // 3480093f4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4480093f4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5480093f4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6480093f4SDimitry Andric // 7480093f4SDimitry Andric //===----------------------------------------------------------------------===// 8480093f4SDimitry Andric // 9480093f4SDimitry Andric // This file implements a pass to prepare loops for ppc preferred addressing 10480093f4SDimitry Andric // modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with 11480093f4SDimitry Andric // update) 12480093f4SDimitry Andric // Additional PHIs are created for loop induction variables used by load/store 13480093f4SDimitry Andric // instructions so that preferred addressing modes can be used. 14480093f4SDimitry Andric // 15480093f4SDimitry Andric // 1: DS/DQ form preparation, prepare the load/store instructions so that they 16480093f4SDimitry Andric // can satisfy the DS/DQ form displacement requirements. 17480093f4SDimitry Andric // Generically, this means transforming loops like this: 18480093f4SDimitry Andric // for (int i = 0; i < n; ++i) { 19480093f4SDimitry Andric // unsigned long x1 = *(unsigned long *)(p + i + 5); 20480093f4SDimitry Andric // unsigned long x2 = *(unsigned long *)(p + i + 9); 21480093f4SDimitry Andric // } 22480093f4SDimitry Andric // 23480093f4SDimitry Andric // to look like this: 24480093f4SDimitry Andric // 25480093f4SDimitry Andric // unsigned NewP = p + 5; 26480093f4SDimitry Andric // for (int i = 0; i < n; ++i) { 27480093f4SDimitry Andric // unsigned long x1 = *(unsigned long *)(i + NewP); 28480093f4SDimitry Andric // unsigned long x2 = *(unsigned long *)(i + NewP + 4); 29480093f4SDimitry Andric // } 30480093f4SDimitry Andric // 31480093f4SDimitry Andric // 2: D/DS form with update preparation, prepare the load/store instructions so 32480093f4SDimitry Andric // that we can use update form to do pre-increment. 33480093f4SDimitry Andric // Generically, this means transforming loops like this: 34480093f4SDimitry Andric // for (int i = 0; i < n; ++i) 35480093f4SDimitry Andric // array[i] = c; 36480093f4SDimitry Andric // 37480093f4SDimitry Andric // to look like this: 38480093f4SDimitry Andric // 39480093f4SDimitry Andric // T *p = array[-1]; 40480093f4SDimitry Andric // for (int i = 0; i < n; ++i) 41480093f4SDimitry Andric // *++p = c; 42349cc55cSDimitry Andric // 43349cc55cSDimitry Andric // 3: common multiple chains for the load/stores with same offsets in the loop, 44349cc55cSDimitry Andric // so that we can reuse the offsets and reduce the register pressure in the 45349cc55cSDimitry Andric // loop. This transformation can also increase the loop ILP as now each chain 46349cc55cSDimitry Andric // uses its own loop induction add/addi. But this will increase the number of 47349cc55cSDimitry Andric // add/addi in the loop. 48349cc55cSDimitry Andric // 49349cc55cSDimitry Andric // Generically, this means transforming loops like this: 50349cc55cSDimitry Andric // 51349cc55cSDimitry Andric // char *p; 52349cc55cSDimitry Andric // A1 = p + base1 53349cc55cSDimitry Andric // A2 = p + base1 + offset 54349cc55cSDimitry Andric // B1 = p + base2 55349cc55cSDimitry Andric // B2 = p + base2 + offset 56349cc55cSDimitry Andric // 57349cc55cSDimitry Andric // for (int i = 0; i < n; i++) 58349cc55cSDimitry Andric // unsigned long x1 = *(unsigned long *)(A1 + i); 59349cc55cSDimitry Andric // unsigned long x2 = *(unsigned long *)(A2 + i) 60349cc55cSDimitry Andric // unsigned long x3 = *(unsigned long *)(B1 + i); 61349cc55cSDimitry Andric // unsigned long x4 = *(unsigned long *)(B2 + i); 62349cc55cSDimitry Andric // } 63349cc55cSDimitry Andric // 64349cc55cSDimitry Andric // to look like this: 65349cc55cSDimitry Andric // 66349cc55cSDimitry Andric // A1_new = p + base1 // chain 1 67349cc55cSDimitry Andric // B1_new = p + base2 // chain 2, now inside the loop, common offset is 68349cc55cSDimitry Andric // // reused. 69349cc55cSDimitry Andric // 70349cc55cSDimitry Andric // for (long long i = 0; i < n; i+=count) { 71349cc55cSDimitry Andric // unsigned long x1 = *(unsigned long *)(A1_new + i); 72349cc55cSDimitry Andric // unsigned long x2 = *(unsigned long *)((A1_new + i) + offset); 73349cc55cSDimitry Andric // unsigned long x3 = *(unsigned long *)(B1_new + i); 74349cc55cSDimitry Andric // unsigned long x4 = *(unsigned long *)((B1_new + i) + offset); 75349cc55cSDimitry Andric // } 76480093f4SDimitry Andric //===----------------------------------------------------------------------===// 77480093f4SDimitry Andric 78480093f4SDimitry Andric #include "PPC.h" 79480093f4SDimitry Andric #include "PPCSubtarget.h" 80480093f4SDimitry Andric #include "PPCTargetMachine.h" 81480093f4SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h" 82480093f4SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 83480093f4SDimitry Andric #include "llvm/ADT/SmallSet.h" 84480093f4SDimitry Andric #include "llvm/ADT/SmallVector.h" 85480093f4SDimitry Andric #include "llvm/ADT/Statistic.h" 86480093f4SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 87480093f4SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 88480093f4SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 89480093f4SDimitry Andric #include "llvm/IR/BasicBlock.h" 90480093f4SDimitry Andric #include "llvm/IR/CFG.h" 91480093f4SDimitry Andric #include "llvm/IR/Dominators.h" 92480093f4SDimitry Andric #include "llvm/IR/Instruction.h" 93480093f4SDimitry Andric #include "llvm/IR/Instructions.h" 94480093f4SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 95e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsPowerPC.h" 96480093f4SDimitry Andric #include "llvm/IR/Module.h" 97480093f4SDimitry Andric #include "llvm/IR/Type.h" 98480093f4SDimitry Andric #include "llvm/IR/Value.h" 99480093f4SDimitry Andric #include "llvm/InitializePasses.h" 100480093f4SDimitry Andric #include "llvm/Pass.h" 101480093f4SDimitry Andric #include "llvm/Support/Casting.h" 102480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 103480093f4SDimitry Andric #include "llvm/Support/Debug.h" 104480093f4SDimitry Andric #include "llvm/Transforms/Scalar.h" 105480093f4SDimitry Andric #include "llvm/Transforms/Utils.h" 106480093f4SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 107480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 108480093f4SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 1095ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 110480093f4SDimitry Andric #include <cassert> 111bdd1243dSDimitry Andric #include <cmath> 112480093f4SDimitry Andric #include <iterator> 113480093f4SDimitry Andric #include <utility> 114480093f4SDimitry Andric 115fe6060f1SDimitry Andric #define DEBUG_TYPE "ppc-loop-instr-form-prep" 116fe6060f1SDimitry Andric 117480093f4SDimitry Andric using namespace llvm; 118480093f4SDimitry Andric 119349cc55cSDimitry Andric static cl::opt<unsigned> 120349cc55cSDimitry Andric MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24), 121349cc55cSDimitry Andric cl::desc("Potential common base number threshold per function " 122349cc55cSDimitry Andric "for PPC loop prep")); 123480093f4SDimitry Andric 124480093f4SDimitry Andric static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update", 125480093f4SDimitry Andric cl::init(true), cl::Hidden, 126480093f4SDimitry Andric cl::desc("prefer update form when ds form is also a update form")); 127480093f4SDimitry Andric 128349cc55cSDimitry Andric static cl::opt<bool> EnableUpdateFormForNonConstInc( 129349cc55cSDimitry Andric "ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden, 130349cc55cSDimitry Andric cl::desc("prepare update form when the load/store increment is a loop " 131349cc55cSDimitry Andric "invariant non-const value.")); 132349cc55cSDimitry Andric 133349cc55cSDimitry Andric static cl::opt<bool> EnableChainCommoning( 134349cc55cSDimitry Andric "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden, 135349cc55cSDimitry Andric cl::desc("Enable chain commoning in PPC loop prepare pass.")); 136349cc55cSDimitry Andric 137480093f4SDimitry Andric // Sum of following 3 per loop thresholds for all loops can not be larger 138480093f4SDimitry Andric // than MaxVarsPrep. 139e8d8bef9SDimitry Andric // now the thresholds for each kind prep are exterimental values on Power9. 140480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars", 141480093f4SDimitry Andric cl::Hidden, cl::init(3), 142480093f4SDimitry Andric cl::desc("Potential PHI threshold per loop for PPC loop prep of update " 143480093f4SDimitry Andric "form")); 144480093f4SDimitry Andric 145480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars", 146480093f4SDimitry Andric cl::Hidden, cl::init(3), 147480093f4SDimitry Andric cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form")); 148480093f4SDimitry Andric 149480093f4SDimitry Andric static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars", 150e8d8bef9SDimitry Andric cl::Hidden, cl::init(8), 151480093f4SDimitry Andric cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form")); 152480093f4SDimitry Andric 153349cc55cSDimitry Andric // Commoning chain will reduce the register pressure, so we don't consider about 154349cc55cSDimitry Andric // the PHI nodes number. 155349cc55cSDimitry Andric // But commoning chain will increase the addi/add number in the loop and also 156349cc55cSDimitry Andric // increase loop ILP. Maximum chain number should be same with hardware 157349cc55cSDimitry Andric // IssueWidth, because we won't benefit from ILP if the parallel chains number 158349cc55cSDimitry Andric // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so 159349cc55cSDimitry Andric // there would be 4 buckets at most on P9(IssueWidth is 8). 160349cc55cSDimitry Andric static cl::opt<unsigned> MaxVarsChainCommon( 161349cc55cSDimitry Andric "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4), 162349cc55cSDimitry Andric cl::desc("Bucket number per loop for PPC loop chain common")); 163480093f4SDimitry Andric 164480093f4SDimitry Andric // If would not be profitable if the common base has only one load/store, ISEL 165480093f4SDimitry Andric // should already be able to choose best load/store form based on offset for 166480093f4SDimitry Andric // single load/store. Set minimal profitable value default to 2 and make it as 167480093f4SDimitry Andric // an option. 168480093f4SDimitry Andric static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold", 169480093f4SDimitry Andric cl::Hidden, cl::init(2), 170480093f4SDimitry Andric cl::desc("Minimal common base load/store instructions triggering DS/DQ form " 171480093f4SDimitry Andric "preparation")); 172480093f4SDimitry Andric 173349cc55cSDimitry Andric static cl::opt<unsigned> ChainCommonPrepMinThreshold( 174349cc55cSDimitry Andric "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4), 175349cc55cSDimitry Andric cl::desc("Minimal common base load/store instructions triggering chain " 176349cc55cSDimitry Andric "commoning preparation. Must be not smaller than 4")); 177349cc55cSDimitry Andric 178480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form"); 179480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form"); 180480093f4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form"); 181480093f4SDimitry Andric STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten"); 182480093f4SDimitry Andric STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten"); 183480093f4SDimitry Andric STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten"); 184349cc55cSDimitry Andric STATISTIC(ChainCommoningRewritten, "Num of commoning chains"); 185480093f4SDimitry Andric 186480093f4SDimitry Andric namespace { 187480093f4SDimitry Andric struct BucketElement { 188349cc55cSDimitry Andric BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {} 189480093f4SDimitry Andric BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {} 190480093f4SDimitry Andric 191349cc55cSDimitry Andric const SCEV *Offset; 192480093f4SDimitry Andric Instruction *Instr; 193480093f4SDimitry Andric }; 194480093f4SDimitry Andric 195480093f4SDimitry Andric struct Bucket { 196349cc55cSDimitry Andric Bucket(const SCEV *B, Instruction *I) 197349cc55cSDimitry Andric : BaseSCEV(B), Elements(1, BucketElement(I)) { 198349cc55cSDimitry Andric ChainSize = 0; 199349cc55cSDimitry Andric } 200480093f4SDimitry Andric 201349cc55cSDimitry Andric // The base of the whole bucket. 202480093f4SDimitry Andric const SCEV *BaseSCEV; 203349cc55cSDimitry Andric 204349cc55cSDimitry Andric // All elements in the bucket. In the bucket, the element with the BaseSCEV 205349cc55cSDimitry Andric // has no offset and all other elements are stored as offsets to the 206349cc55cSDimitry Andric // BaseSCEV. 207480093f4SDimitry Andric SmallVector<BucketElement, 16> Elements; 208349cc55cSDimitry Andric 209349cc55cSDimitry Andric // The potential chains size. This is used for chain commoning only. 210349cc55cSDimitry Andric unsigned ChainSize; 211349cc55cSDimitry Andric 212349cc55cSDimitry Andric // The base for each potential chain. This is used for chain commoning only. 213349cc55cSDimitry Andric SmallVector<BucketElement, 16> ChainBases; 214480093f4SDimitry Andric }; 215480093f4SDimitry Andric 216480093f4SDimitry Andric // "UpdateForm" is not a real PPC instruction form, it stands for dform 217480093f4SDimitry Andric // load/store with update like ldu/stdu, or Prefetch intrinsic. 218480093f4SDimitry Andric // For DS form instructions, their displacements must be multiple of 4. 219480093f4SDimitry Andric // For DQ form instructions, their displacements must be multiple of 16. 220349cc55cSDimitry Andric enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning }; 221480093f4SDimitry Andric 222480093f4SDimitry Andric class PPCLoopInstrFormPrep : public FunctionPass { 223480093f4SDimitry Andric public: 224480093f4SDimitry Andric static char ID; // Pass ID, replacement for typeid 225480093f4SDimitry Andric 226480093f4SDimitry Andric PPCLoopInstrFormPrep() : FunctionPass(ID) { 227480093f4SDimitry Andric initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry()); 228480093f4SDimitry Andric } 229480093f4SDimitry Andric 230480093f4SDimitry Andric PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) { 231480093f4SDimitry Andric initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry()); 232480093f4SDimitry Andric } 233480093f4SDimitry Andric 234480093f4SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 235480093f4SDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 236480093f4SDimitry Andric AU.addRequired<LoopInfoWrapperPass>(); 237480093f4SDimitry Andric AU.addPreserved<LoopInfoWrapperPass>(); 238480093f4SDimitry Andric AU.addRequired<ScalarEvolutionWrapperPass>(); 239480093f4SDimitry Andric } 240480093f4SDimitry Andric 241480093f4SDimitry Andric bool runOnFunction(Function &F) override; 242480093f4SDimitry Andric 243480093f4SDimitry Andric private: 244480093f4SDimitry Andric PPCTargetMachine *TM = nullptr; 245480093f4SDimitry Andric const PPCSubtarget *ST; 246480093f4SDimitry Andric DominatorTree *DT; 247480093f4SDimitry Andric LoopInfo *LI; 248480093f4SDimitry Andric ScalarEvolution *SE; 249480093f4SDimitry Andric bool PreserveLCSSA; 250349cc55cSDimitry Andric bool HasCandidateForPrepare; 251480093f4SDimitry Andric 252480093f4SDimitry Andric /// Successful preparation number for Update/DS/DQ form in all inner most 253480093f4SDimitry Andric /// loops. One successful preparation will put one common base out of loop, 254480093f4SDimitry Andric /// this may leads to register presure like LICM does. 255480093f4SDimitry Andric /// Make sure total preparation number can be controlled by option. 256480093f4SDimitry Andric unsigned SuccPrepCount; 257480093f4SDimitry Andric 258480093f4SDimitry Andric bool runOnLoop(Loop *L); 259480093f4SDimitry Andric 260480093f4SDimitry Andric /// Check if required PHI node is already exist in Loop \p L. 261480093f4SDimitry Andric bool alreadyPrepared(Loop *L, Instruction *MemI, 262480093f4SDimitry Andric const SCEV *BasePtrStartSCEV, 263349cc55cSDimitry Andric const SCEV *BasePtrIncSCEV, PrepForm Form); 264349cc55cSDimitry Andric 265349cc55cSDimitry Andric /// Get the value which defines the increment SCEV \p BasePtrIncSCEV. 266349cc55cSDimitry Andric Value *getNodeForInc(Loop *L, Instruction *MemI, 267349cc55cSDimitry Andric const SCEV *BasePtrIncSCEV); 268349cc55cSDimitry Andric 269349cc55cSDimitry Andric /// Common chains to reuse offsets for a loop to reduce register pressure. 270349cc55cSDimitry Andric bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets); 271349cc55cSDimitry Andric 272349cc55cSDimitry Andric /// Find out the potential commoning chains and their bases. 273349cc55cSDimitry Andric bool prepareBasesForCommoningChains(Bucket &BucketChain); 274349cc55cSDimitry Andric 275349cc55cSDimitry Andric /// Rewrite load/store according to the common chains. 276349cc55cSDimitry Andric bool 277349cc55cSDimitry Andric rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket, 278349cc55cSDimitry Andric SmallSet<BasicBlock *, 16> &BBChanged); 279480093f4SDimitry Andric 280480093f4SDimitry Andric /// Collect condition matched(\p isValidCandidate() returns true) 281480093f4SDimitry Andric /// candidates in Loop \p L. 282fe6060f1SDimitry Andric SmallVector<Bucket, 16> collectCandidates( 283fe6060f1SDimitry Andric Loop *L, 284349cc55cSDimitry Andric std::function<bool(const Instruction *, Value *, const Type *)> 285480093f4SDimitry Andric isValidCandidate, 286349cc55cSDimitry Andric std::function<bool(const SCEV *)> isValidDiff, 287480093f4SDimitry Andric unsigned MaxCandidateNum); 288480093f4SDimitry Andric 289349cc55cSDimitry Andric /// Add a candidate to candidates \p Buckets if diff between candidate and 290349cc55cSDimitry Andric /// one base in \p Buckets matches \p isValidDiff. 291480093f4SDimitry Andric void addOneCandidate(Instruction *MemI, const SCEV *LSCEV, 292480093f4SDimitry Andric SmallVector<Bucket, 16> &Buckets, 293349cc55cSDimitry Andric std::function<bool(const SCEV *)> isValidDiff, 294480093f4SDimitry Andric unsigned MaxCandidateNum); 295480093f4SDimitry Andric 296480093f4SDimitry Andric /// Prepare all candidates in \p Buckets for update form. 297480093f4SDimitry Andric bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets); 298480093f4SDimitry Andric 299480093f4SDimitry Andric /// Prepare all candidates in \p Buckets for displacement form, now for 300480093f4SDimitry Andric /// ds/dq. 301349cc55cSDimitry Andric bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form); 302480093f4SDimitry Andric 303480093f4SDimitry Andric /// Prepare for one chain \p BucketChain, find the best base element and 304480093f4SDimitry Andric /// update all other elements in \p BucketChain accordingly. 305480093f4SDimitry Andric /// \p Form is used to find the best base element. 306480093f4SDimitry Andric /// If success, best base element must be stored as the first element of 307480093f4SDimitry Andric /// \p BucketChain. 308480093f4SDimitry Andric /// Return false if no base element found, otherwise return true. 309349cc55cSDimitry Andric bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form); 310480093f4SDimitry Andric 311480093f4SDimitry Andric /// Prepare for one chain \p BucketChain, find the best base element and 312480093f4SDimitry Andric /// update all other elements in \p BucketChain accordingly. 313480093f4SDimitry Andric /// If success, best base element must be stored as the first element of 314480093f4SDimitry Andric /// \p BucketChain. 315480093f4SDimitry Andric /// Return false if no base element found, otherwise return true. 316480093f4SDimitry Andric bool prepareBaseForUpdateFormChain(Bucket &BucketChain); 317480093f4SDimitry Andric 318480093f4SDimitry Andric /// Rewrite load/store instructions in \p BucketChain according to 319480093f4SDimitry Andric /// preparation. 320480093f4SDimitry Andric bool rewriteLoadStores(Loop *L, Bucket &BucketChain, 321480093f4SDimitry Andric SmallSet<BasicBlock *, 16> &BBChanged, 322349cc55cSDimitry Andric PrepForm Form); 323349cc55cSDimitry Andric 324349cc55cSDimitry Andric /// Rewrite for the base load/store of a chain. 325349cc55cSDimitry Andric std::pair<Instruction *, Instruction *> 326349cc55cSDimitry Andric rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV, 327349cc55cSDimitry Andric Instruction *BaseMemI, bool CanPreInc, PrepForm Form, 328349cc55cSDimitry Andric SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs); 329349cc55cSDimitry Andric 330349cc55cSDimitry Andric /// Rewrite for the other load/stores of a chain according to the new \p 331349cc55cSDimitry Andric /// Base. 332349cc55cSDimitry Andric Instruction * 333349cc55cSDimitry Andric rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base, 334349cc55cSDimitry Andric const BucketElement &Element, Value *OffToBase, 335349cc55cSDimitry Andric SmallPtrSet<Value *, 16> &DeletedPtrs); 336480093f4SDimitry Andric }; 337480093f4SDimitry Andric 338480093f4SDimitry Andric } // end anonymous namespace 339480093f4SDimitry Andric 340480093f4SDimitry Andric char PPCLoopInstrFormPrep::ID = 0; 341480093f4SDimitry Andric static const char *name = "Prepare loop for ppc preferred instruction forms"; 342480093f4SDimitry Andric INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false) 343480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 344480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 345480093f4SDimitry Andric INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false) 346480093f4SDimitry Andric 3475ffd83dbSDimitry Andric static constexpr StringRef PHINodeNameSuffix = ".phi"; 3485ffd83dbSDimitry Andric static constexpr StringRef CastNodeNameSuffix = ".cast"; 3495ffd83dbSDimitry Andric static constexpr StringRef GEPNodeIncNameSuffix = ".inc"; 3505ffd83dbSDimitry Andric static constexpr StringRef GEPNodeOffNameSuffix = ".off"; 351480093f4SDimitry Andric 352480093f4SDimitry Andric FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) { 353480093f4SDimitry Andric return new PPCLoopInstrFormPrep(TM); 354480093f4SDimitry Andric } 355480093f4SDimitry Andric 356480093f4SDimitry Andric static bool IsPtrInBounds(Value *BasePtr) { 357480093f4SDimitry Andric Value *StrippedBasePtr = BasePtr; 358480093f4SDimitry Andric while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr)) 359480093f4SDimitry Andric StrippedBasePtr = BC->getOperand(0); 360480093f4SDimitry Andric if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr)) 361480093f4SDimitry Andric return GEP->isInBounds(); 362480093f4SDimitry Andric 363480093f4SDimitry Andric return false; 364480093f4SDimitry Andric } 365480093f4SDimitry Andric 3665ffd83dbSDimitry Andric static std::string getInstrName(const Value *I, StringRef Suffix) { 367480093f4SDimitry Andric assert(I && "Invalid paramater!"); 368480093f4SDimitry Andric if (I->hasName()) 369480093f4SDimitry Andric return (I->getName() + Suffix).str(); 370480093f4SDimitry Andric else 371480093f4SDimitry Andric return ""; 372480093f4SDimitry Andric } 373480093f4SDimitry Andric 374349cc55cSDimitry Andric static Value *getPointerOperandAndType(Value *MemI, 375349cc55cSDimitry Andric Type **PtrElementType = nullptr) { 376480093f4SDimitry Andric 377349cc55cSDimitry Andric Value *PtrValue = nullptr; 378349cc55cSDimitry Andric Type *PointerElementType = nullptr; 379349cc55cSDimitry Andric 380349cc55cSDimitry Andric if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) { 381349cc55cSDimitry Andric PtrValue = LMemI->getPointerOperand(); 382349cc55cSDimitry Andric PointerElementType = LMemI->getType(); 383349cc55cSDimitry Andric } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) { 384349cc55cSDimitry Andric PtrValue = SMemI->getPointerOperand(); 385349cc55cSDimitry Andric PointerElementType = SMemI->getValueOperand()->getType(); 386349cc55cSDimitry Andric } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) { 387349cc55cSDimitry Andric PointerElementType = Type::getInt8Ty(MemI->getContext()); 388349cc55cSDimitry Andric if (IMemI->getIntrinsicID() == Intrinsic::prefetch || 389349cc55cSDimitry Andric IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) { 390349cc55cSDimitry Andric PtrValue = IMemI->getArgOperand(0); 391349cc55cSDimitry Andric } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) { 392349cc55cSDimitry Andric PtrValue = IMemI->getArgOperand(1); 393349cc55cSDimitry Andric } 394349cc55cSDimitry Andric } 395349cc55cSDimitry Andric /*Get ElementType if PtrElementType is not null.*/ 396349cc55cSDimitry Andric if (PtrElementType) 397349cc55cSDimitry Andric *PtrElementType = PointerElementType; 398349cc55cSDimitry Andric 399349cc55cSDimitry Andric return PtrValue; 400480093f4SDimitry Andric } 401480093f4SDimitry Andric 402480093f4SDimitry Andric bool PPCLoopInstrFormPrep::runOnFunction(Function &F) { 403480093f4SDimitry Andric if (skipFunction(F)) 404480093f4SDimitry Andric return false; 405480093f4SDimitry Andric 406480093f4SDimitry Andric LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 407480093f4SDimitry Andric SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 408480093f4SDimitry Andric auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 409480093f4SDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 410480093f4SDimitry Andric PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 411480093f4SDimitry Andric ST = TM ? TM->getSubtargetImpl(F) : nullptr; 412480093f4SDimitry Andric SuccPrepCount = 0; 413480093f4SDimitry Andric 414480093f4SDimitry Andric bool MadeChange = false; 415480093f4SDimitry Andric 4160eae32dcSDimitry Andric for (Loop *I : *LI) 4170eae32dcSDimitry Andric for (Loop *L : depth_first(I)) 4180eae32dcSDimitry Andric MadeChange |= runOnLoop(L); 419480093f4SDimitry Andric 420480093f4SDimitry Andric return MadeChange; 421480093f4SDimitry Andric } 422480093f4SDimitry Andric 423349cc55cSDimitry Andric // Finding the minimal(chain_number + reusable_offset_number) is a complicated 424349cc55cSDimitry Andric // algorithmic problem. 425349cc55cSDimitry Andric // For now, the algorithm used here is simply adjusted to handle the case for 426349cc55cSDimitry Andric // manually unrolling cases. 427349cc55cSDimitry Andric // FIXME: use a more powerful algorithm to find minimal sum of chain_number and 428349cc55cSDimitry Andric // reusable_offset_number for one base with multiple offsets. 429349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) { 430349cc55cSDimitry Andric // The minimal size for profitable chain commoning: 431349cc55cSDimitry Andric // A1 = base + offset1 432349cc55cSDimitry Andric // A2 = base + offset2 (offset2 - offset1 = X) 433349cc55cSDimitry Andric // A3 = base + offset3 434349cc55cSDimitry Andric // A4 = base + offset4 (offset4 - offset3 = X) 435349cc55cSDimitry Andric // ======> 436349cc55cSDimitry Andric // base1 = base + offset1 437349cc55cSDimitry Andric // base2 = base + offset3 438349cc55cSDimitry Andric // A1 = base1 439349cc55cSDimitry Andric // A2 = base1 + X 440349cc55cSDimitry Andric // A3 = base2 441349cc55cSDimitry Andric // A4 = base2 + X 442349cc55cSDimitry Andric // 443349cc55cSDimitry Andric // There is benefit because of reuse of offest 'X'. 444349cc55cSDimitry Andric 445349cc55cSDimitry Andric assert(ChainCommonPrepMinThreshold >= 4 && 446349cc55cSDimitry Andric "Thredhold can not be smaller than 4!\n"); 447349cc55cSDimitry Andric if (CBucket.Elements.size() < ChainCommonPrepMinThreshold) 448349cc55cSDimitry Andric return false; 449349cc55cSDimitry Andric 450349cc55cSDimitry Andric // We simply select the FirstOffset as the first reusable offset between each 451349cc55cSDimitry Andric // chain element 1 and element 0. 452349cc55cSDimitry Andric const SCEV *FirstOffset = CBucket.Elements[1].Offset; 453349cc55cSDimitry Andric 454349cc55cSDimitry Andric // Figure out how many times above FirstOffset is used in the chain. 455349cc55cSDimitry Andric // For a success commoning chain candidate, offset difference between each 456349cc55cSDimitry Andric // chain element 1 and element 0 must be also FirstOffset. 457349cc55cSDimitry Andric unsigned FirstOffsetReusedCount = 1; 458349cc55cSDimitry Andric 459349cc55cSDimitry Andric // Figure out how many times above FirstOffset is used in the first chain. 460349cc55cSDimitry Andric // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain 461349cc55cSDimitry Andric unsigned FirstOffsetReusedCountInFirstChain = 1; 462349cc55cSDimitry Andric 463349cc55cSDimitry Andric unsigned EleNum = CBucket.Elements.size(); 464349cc55cSDimitry Andric bool SawChainSeparater = false; 465349cc55cSDimitry Andric for (unsigned j = 2; j != EleNum; ++j) { 466349cc55cSDimitry Andric if (SE->getMinusSCEV(CBucket.Elements[j].Offset, 467349cc55cSDimitry Andric CBucket.Elements[j - 1].Offset) == FirstOffset) { 468349cc55cSDimitry Andric if (!SawChainSeparater) 469349cc55cSDimitry Andric FirstOffsetReusedCountInFirstChain++; 470349cc55cSDimitry Andric FirstOffsetReusedCount++; 471349cc55cSDimitry Andric } else 472349cc55cSDimitry Andric // For now, if we meet any offset which is not FirstOffset, we assume we 473349cc55cSDimitry Andric // find a new Chain. 474349cc55cSDimitry Andric // This makes us miss some opportunities. 475349cc55cSDimitry Andric // For example, we can common: 476349cc55cSDimitry Andric // 477349cc55cSDimitry Andric // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB} 478349cc55cSDimitry Andric // 479349cc55cSDimitry Andric // as two chains: 480349cc55cSDimitry Andric // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}} 481349cc55cSDimitry Andric // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2 482349cc55cSDimitry Andric // 483349cc55cSDimitry Andric // But we fail to common: 484349cc55cSDimitry Andric // 485349cc55cSDimitry Andric // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA} 486349cc55cSDimitry Andric // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1 487349cc55cSDimitry Andric 488349cc55cSDimitry Andric SawChainSeparater = true; 489349cc55cSDimitry Andric } 490349cc55cSDimitry Andric 491349cc55cSDimitry Andric // FirstOffset is not reused, skip this bucket. 492349cc55cSDimitry Andric if (FirstOffsetReusedCount == 1) 493349cc55cSDimitry Andric return false; 494349cc55cSDimitry Andric 495349cc55cSDimitry Andric unsigned ChainNum = 496349cc55cSDimitry Andric FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain; 497349cc55cSDimitry Andric 498349cc55cSDimitry Andric // All elements are increased by FirstOffset. 499349cc55cSDimitry Andric // The number of chains should be sqrt(EleNum). 500349cc55cSDimitry Andric if (!SawChainSeparater) 501349cc55cSDimitry Andric ChainNum = (unsigned)sqrt((double)EleNum); 502349cc55cSDimitry Andric 503349cc55cSDimitry Andric CBucket.ChainSize = (unsigned)(EleNum / ChainNum); 504349cc55cSDimitry Andric 505349cc55cSDimitry Andric // If this is not a perfect chain(eg: not all elements can be put inside 506349cc55cSDimitry Andric // commoning chains.), skip now. 507349cc55cSDimitry Andric if (CBucket.ChainSize * ChainNum != EleNum) 508349cc55cSDimitry Andric return false; 509349cc55cSDimitry Andric 510349cc55cSDimitry Andric if (SawChainSeparater) { 511349cc55cSDimitry Andric // Check that the offset seqs are the same for all chains. 512349cc55cSDimitry Andric for (unsigned i = 1; i < CBucket.ChainSize; i++) 513349cc55cSDimitry Andric for (unsigned j = 1; j < ChainNum; j++) 514349cc55cSDimitry Andric if (CBucket.Elements[i].Offset != 515349cc55cSDimitry Andric SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset, 516349cc55cSDimitry Andric CBucket.Elements[j * CBucket.ChainSize].Offset)) 517349cc55cSDimitry Andric return false; 518349cc55cSDimitry Andric } 519349cc55cSDimitry Andric 520349cc55cSDimitry Andric for (unsigned i = 0; i < ChainNum; i++) 521349cc55cSDimitry Andric CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]); 522349cc55cSDimitry Andric 523349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n"); 524349cc55cSDimitry Andric 525349cc55cSDimitry Andric return true; 526349cc55cSDimitry Andric } 527349cc55cSDimitry Andric 528349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::chainCommoning(Loop *L, 529349cc55cSDimitry Andric SmallVector<Bucket, 16> &Buckets) { 530349cc55cSDimitry Andric bool MadeChange = false; 531349cc55cSDimitry Andric 532349cc55cSDimitry Andric if (Buckets.empty()) 533349cc55cSDimitry Andric return MadeChange; 534349cc55cSDimitry Andric 535349cc55cSDimitry Andric SmallSet<BasicBlock *, 16> BBChanged; 536349cc55cSDimitry Andric 537349cc55cSDimitry Andric for (auto &Bucket : Buckets) { 538349cc55cSDimitry Andric if (prepareBasesForCommoningChains(Bucket)) 539349cc55cSDimitry Andric MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged); 540349cc55cSDimitry Andric } 541349cc55cSDimitry Andric 542349cc55cSDimitry Andric if (MadeChange) 543349cc55cSDimitry Andric for (auto *BB : BBChanged) 544349cc55cSDimitry Andric DeleteDeadPHIs(BB); 545349cc55cSDimitry Andric return MadeChange; 546349cc55cSDimitry Andric } 547349cc55cSDimitry Andric 548349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains( 549349cc55cSDimitry Andric Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) { 550349cc55cSDimitry Andric bool MadeChange = false; 551349cc55cSDimitry Andric 552349cc55cSDimitry Andric assert(Bucket.Elements.size() == 553349cc55cSDimitry Andric Bucket.ChainBases.size() * Bucket.ChainSize && 554349cc55cSDimitry Andric "invalid bucket for chain commoning!\n"); 555349cc55cSDimitry Andric SmallPtrSet<Value *, 16> DeletedPtrs; 556349cc55cSDimitry Andric 557349cc55cSDimitry Andric BasicBlock *Header = L->getHeader(); 558349cc55cSDimitry Andric BasicBlock *LoopPredecessor = L->getLoopPredecessor(); 559349cc55cSDimitry Andric 560*0fca6ea1SDimitry Andric SCEVExpander SCEVE(*SE, Header->getDataLayout(), 561349cc55cSDimitry Andric "loopprepare-chaincommon"); 562349cc55cSDimitry Andric 563349cc55cSDimitry Andric for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) { 564349cc55cSDimitry Andric unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx; 565349cc55cSDimitry Andric const SCEV *BaseSCEV = 566349cc55cSDimitry Andric ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV, 567349cc55cSDimitry Andric Bucket.Elements[BaseElemIdx].Offset) 568349cc55cSDimitry Andric : Bucket.BaseSCEV; 569349cc55cSDimitry Andric const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV); 570349cc55cSDimitry Andric 571349cc55cSDimitry Andric // Make sure the base is able to expand. 572fcaf7f86SDimitry Andric if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart())) 573349cc55cSDimitry Andric return MadeChange; 574349cc55cSDimitry Andric 575349cc55cSDimitry Andric assert(BasePtrSCEV->isAffine() && 576349cc55cSDimitry Andric "Invalid SCEV type for the base ptr for a candidate chain!\n"); 577349cc55cSDimitry Andric 578349cc55cSDimitry Andric std::pair<Instruction *, Instruction *> Base = rewriteForBase( 579349cc55cSDimitry Andric L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr, 580349cc55cSDimitry Andric false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs); 581349cc55cSDimitry Andric 582349cc55cSDimitry Andric if (!Base.first || !Base.second) 583349cc55cSDimitry Andric return MadeChange; 584349cc55cSDimitry Andric 585349cc55cSDimitry Andric // Keep track of the replacement pointer values we've inserted so that we 586349cc55cSDimitry Andric // don't generate more pointer values than necessary. 587349cc55cSDimitry Andric SmallPtrSet<Value *, 16> NewPtrs; 588349cc55cSDimitry Andric NewPtrs.insert(Base.first); 589349cc55cSDimitry Andric 590349cc55cSDimitry Andric for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize; 591349cc55cSDimitry Andric ++Idx) { 592349cc55cSDimitry Andric BucketElement &I = Bucket.Elements[Idx]; 593349cc55cSDimitry Andric Value *Ptr = getPointerOperandAndType(I.Instr); 594349cc55cSDimitry Andric assert(Ptr && "No pointer operand"); 595349cc55cSDimitry Andric if (NewPtrs.count(Ptr)) 596349cc55cSDimitry Andric continue; 597349cc55cSDimitry Andric 598349cc55cSDimitry Andric const SCEV *OffsetSCEV = 599349cc55cSDimitry Andric BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset, 600349cc55cSDimitry Andric Bucket.Elements[BaseElemIdx].Offset) 601349cc55cSDimitry Andric : Bucket.Elements[Idx].Offset; 602349cc55cSDimitry Andric 603349cc55cSDimitry Andric // Make sure offset is able to expand. Only need to check one time as the 604349cc55cSDimitry Andric // offsets are reused between different chains. 605349cc55cSDimitry Andric if (!BaseElemIdx) 606fcaf7f86SDimitry Andric if (!SCEVE.isSafeToExpand(OffsetSCEV)) 607349cc55cSDimitry Andric return false; 608349cc55cSDimitry Andric 609349cc55cSDimitry Andric Value *OffsetValue = SCEVE.expandCodeFor( 610349cc55cSDimitry Andric OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator()); 611349cc55cSDimitry Andric 612349cc55cSDimitry Andric Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx], 613349cc55cSDimitry Andric OffsetValue, DeletedPtrs); 614349cc55cSDimitry Andric 615349cc55cSDimitry Andric assert(NewPtr && "Wrong rewrite!\n"); 616349cc55cSDimitry Andric NewPtrs.insert(NewPtr); 617349cc55cSDimitry Andric } 618349cc55cSDimitry Andric 619349cc55cSDimitry Andric ++ChainCommoningRewritten; 620349cc55cSDimitry Andric } 621349cc55cSDimitry Andric 622349cc55cSDimitry Andric // Clear the rewriter cache, because values that are in the rewriter's cache 623349cc55cSDimitry Andric // can be deleted below, causing the AssertingVH in the cache to trigger. 624349cc55cSDimitry Andric SCEVE.clear(); 625349cc55cSDimitry Andric 626349cc55cSDimitry Andric for (auto *Ptr : DeletedPtrs) { 627349cc55cSDimitry Andric if (Instruction *IDel = dyn_cast<Instruction>(Ptr)) 628349cc55cSDimitry Andric BBChanged.insert(IDel->getParent()); 629349cc55cSDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(Ptr); 630349cc55cSDimitry Andric } 631349cc55cSDimitry Andric 632349cc55cSDimitry Andric MadeChange = true; 633349cc55cSDimitry Andric return MadeChange; 634349cc55cSDimitry Andric } 635349cc55cSDimitry Andric 636349cc55cSDimitry Andric // Rewrite the new base according to BasePtrSCEV. 637349cc55cSDimitry Andric // bb.loop.preheader: 638349cc55cSDimitry Andric // %newstart = ... 639349cc55cSDimitry Andric // bb.loop.body: 640349cc55cSDimitry Andric // %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ] 641349cc55cSDimitry Andric // ... 642349cc55cSDimitry Andric // %add = getelementptr %phinode, %inc 643349cc55cSDimitry Andric // 644349cc55cSDimitry Andric // First returned instruciton is %phinode (or a type cast to %phinode), caller 645349cc55cSDimitry Andric // needs this value to rewrite other load/stores in the same chain. 646349cc55cSDimitry Andric // Second returned instruction is %add, caller needs this value to rewrite other 647349cc55cSDimitry Andric // load/stores in the same chain. 648349cc55cSDimitry Andric std::pair<Instruction *, Instruction *> 649349cc55cSDimitry Andric PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV, 650349cc55cSDimitry Andric Instruction *BaseMemI, bool CanPreInc, 651349cc55cSDimitry Andric PrepForm Form, SCEVExpander &SCEVE, 652349cc55cSDimitry Andric SmallPtrSet<Value *, 16> &DeletedPtrs) { 653349cc55cSDimitry Andric 654349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n"); 655349cc55cSDimitry Andric 656349cc55cSDimitry Andric assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?"); 657349cc55cSDimitry Andric 658349cc55cSDimitry Andric Value *BasePtr = getPointerOperandAndType(BaseMemI); 659349cc55cSDimitry Andric assert(BasePtr && "No pointer operand"); 660349cc55cSDimitry Andric 661349cc55cSDimitry Andric Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext()); 662349cc55cSDimitry Andric Type *I8PtrTy = 6635f757f3fSDimitry Andric PointerType::get(BaseMemI->getParent()->getContext(), 664349cc55cSDimitry Andric BasePtr->getType()->getPointerAddressSpace()); 665349cc55cSDimitry Andric 666349cc55cSDimitry Andric bool IsConstantInc = false; 667349cc55cSDimitry Andric const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE); 668349cc55cSDimitry Andric Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV); 669349cc55cSDimitry Andric 670349cc55cSDimitry Andric const SCEVConstant *BasePtrIncConstantSCEV = 671349cc55cSDimitry Andric dyn_cast<SCEVConstant>(BasePtrIncSCEV); 672349cc55cSDimitry Andric if (BasePtrIncConstantSCEV) 673349cc55cSDimitry Andric IsConstantInc = true; 674349cc55cSDimitry Andric 675349cc55cSDimitry Andric // No valid representation for the increment. 676349cc55cSDimitry Andric if (!IncNode) { 677349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n"); 678349cc55cSDimitry Andric return std::make_pair(nullptr, nullptr); 679349cc55cSDimitry Andric } 680349cc55cSDimitry Andric 681349cc55cSDimitry Andric if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) { 682349cc55cSDimitry Andric LLVM_DEBUG( 683349cc55cSDimitry Andric dbgs() 684349cc55cSDimitry Andric << "Update form prepare for non-const increment is not enabled!\n"); 685349cc55cSDimitry Andric return std::make_pair(nullptr, nullptr); 686349cc55cSDimitry Andric } 687349cc55cSDimitry Andric 688349cc55cSDimitry Andric const SCEV *BasePtrStartSCEV = nullptr; 689349cc55cSDimitry Andric if (CanPreInc) { 690349cc55cSDimitry Andric assert(SE->isLoopInvariant(BasePtrIncSCEV, L) && 691349cc55cSDimitry Andric "Increment is not loop invariant!\n"); 692349cc55cSDimitry Andric BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(), 693349cc55cSDimitry Andric IsConstantInc ? BasePtrIncConstantSCEV 694349cc55cSDimitry Andric : BasePtrIncSCEV); 695349cc55cSDimitry Andric } else 696349cc55cSDimitry Andric BasePtrStartSCEV = BasePtrSCEV->getStart(); 697349cc55cSDimitry Andric 698349cc55cSDimitry Andric if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) { 699349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n"); 700349cc55cSDimitry Andric return std::make_pair(nullptr, nullptr); 701349cc55cSDimitry Andric } 702349cc55cSDimitry Andric 703349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n"); 704349cc55cSDimitry Andric 705349cc55cSDimitry Andric BasicBlock *Header = L->getHeader(); 706349cc55cSDimitry Andric unsigned HeaderLoopPredCount = pred_size(Header); 707349cc55cSDimitry Andric BasicBlock *LoopPredecessor = L->getLoopPredecessor(); 708349cc55cSDimitry Andric 709349cc55cSDimitry Andric PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount, 7105f757f3fSDimitry Andric getInstrName(BaseMemI, PHINodeNameSuffix)); 7115f757f3fSDimitry Andric NewPHI->insertBefore(Header->getFirstNonPHIIt()); 712349cc55cSDimitry Andric 713349cc55cSDimitry Andric Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy, 714349cc55cSDimitry Andric LoopPredecessor->getTerminator()); 715349cc55cSDimitry Andric 716349cc55cSDimitry Andric // Note that LoopPredecessor might occur in the predecessor list multiple 717349cc55cSDimitry Andric // times, and we need to add it the right number of times. 718bdd1243dSDimitry Andric for (auto *PI : predecessors(Header)) { 719349cc55cSDimitry Andric if (PI != LoopPredecessor) 720349cc55cSDimitry Andric continue; 721349cc55cSDimitry Andric 722349cc55cSDimitry Andric NewPHI->addIncoming(BasePtrStart, LoopPredecessor); 723349cc55cSDimitry Andric } 724349cc55cSDimitry Andric 725349cc55cSDimitry Andric Instruction *PtrInc = nullptr; 726349cc55cSDimitry Andric Instruction *NewBasePtr = nullptr; 727349cc55cSDimitry Andric if (CanPreInc) { 728*0fca6ea1SDimitry Andric BasicBlock::iterator InsPoint = Header->getFirstInsertionPt(); 729349cc55cSDimitry Andric PtrInc = GetElementPtrInst::Create( 730349cc55cSDimitry Andric I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix), 731349cc55cSDimitry Andric InsPoint); 732349cc55cSDimitry Andric cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr)); 733bdd1243dSDimitry Andric for (auto *PI : predecessors(Header)) { 734349cc55cSDimitry Andric if (PI == LoopPredecessor) 735349cc55cSDimitry Andric continue; 736349cc55cSDimitry Andric 737349cc55cSDimitry Andric NewPHI->addIncoming(PtrInc, PI); 738349cc55cSDimitry Andric } 739349cc55cSDimitry Andric if (PtrInc->getType() != BasePtr->getType()) 740349cc55cSDimitry Andric NewBasePtr = 741349cc55cSDimitry Andric new BitCastInst(PtrInc, BasePtr->getType(), 742349cc55cSDimitry Andric getInstrName(PtrInc, CastNodeNameSuffix), InsPoint); 743349cc55cSDimitry Andric else 744349cc55cSDimitry Andric NewBasePtr = PtrInc; 745349cc55cSDimitry Andric } else { 746349cc55cSDimitry Andric // Note that LoopPredecessor might occur in the predecessor list multiple 747349cc55cSDimitry Andric // times, and we need to make sure no more incoming value for them in PHI. 748bdd1243dSDimitry Andric for (auto *PI : predecessors(Header)) { 749349cc55cSDimitry Andric if (PI == LoopPredecessor) 750349cc55cSDimitry Andric continue; 751349cc55cSDimitry Andric 752349cc55cSDimitry Andric // For the latch predecessor, we need to insert a GEP just before the 753349cc55cSDimitry Andric // terminator to increase the address. 754349cc55cSDimitry Andric BasicBlock *BB = PI; 755*0fca6ea1SDimitry Andric BasicBlock::iterator InsPoint = BB->getTerminator()->getIterator(); 756349cc55cSDimitry Andric PtrInc = GetElementPtrInst::Create( 757349cc55cSDimitry Andric I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix), 758349cc55cSDimitry Andric InsPoint); 759349cc55cSDimitry Andric cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr)); 760349cc55cSDimitry Andric 761349cc55cSDimitry Andric NewPHI->addIncoming(PtrInc, PI); 762349cc55cSDimitry Andric } 763349cc55cSDimitry Andric PtrInc = NewPHI; 764349cc55cSDimitry Andric if (NewPHI->getType() != BasePtr->getType()) 765349cc55cSDimitry Andric NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(), 766349cc55cSDimitry Andric getInstrName(NewPHI, CastNodeNameSuffix), 767*0fca6ea1SDimitry Andric Header->getFirstInsertionPt()); 768349cc55cSDimitry Andric else 769349cc55cSDimitry Andric NewBasePtr = NewPHI; 770349cc55cSDimitry Andric } 771349cc55cSDimitry Andric 772349cc55cSDimitry Andric BasePtr->replaceAllUsesWith(NewBasePtr); 773349cc55cSDimitry Andric 774349cc55cSDimitry Andric DeletedPtrs.insert(BasePtr); 775349cc55cSDimitry Andric 776349cc55cSDimitry Andric return std::make_pair(NewBasePtr, PtrInc); 777349cc55cSDimitry Andric } 778349cc55cSDimitry Andric 779349cc55cSDimitry Andric Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement( 780349cc55cSDimitry Andric std::pair<Instruction *, Instruction *> Base, const BucketElement &Element, 781349cc55cSDimitry Andric Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) { 782349cc55cSDimitry Andric Instruction *NewBasePtr = Base.first; 783349cc55cSDimitry Andric Instruction *PtrInc = Base.second; 784349cc55cSDimitry Andric assert((NewBasePtr && PtrInc) && "base does not exist!\n"); 785349cc55cSDimitry Andric 786349cc55cSDimitry Andric Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext()); 787349cc55cSDimitry Andric 788349cc55cSDimitry Andric Value *Ptr = getPointerOperandAndType(Element.Instr); 789349cc55cSDimitry Andric assert(Ptr && "No pointer operand"); 790349cc55cSDimitry Andric 791349cc55cSDimitry Andric Instruction *RealNewPtr; 792349cc55cSDimitry Andric if (!Element.Offset || 793349cc55cSDimitry Andric (isa<SCEVConstant>(Element.Offset) && 794349cc55cSDimitry Andric cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) { 795349cc55cSDimitry Andric RealNewPtr = NewBasePtr; 796349cc55cSDimitry Andric } else { 797*0fca6ea1SDimitry Andric std::optional<BasicBlock::iterator> PtrIP = std::nullopt; 798*0fca6ea1SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(Ptr)) 799*0fca6ea1SDimitry Andric PtrIP = I->getIterator(); 800*0fca6ea1SDimitry Andric 801349cc55cSDimitry Andric if (PtrIP && isa<Instruction>(NewBasePtr) && 802*0fca6ea1SDimitry Andric cast<Instruction>(NewBasePtr)->getParent() == (*PtrIP)->getParent()) 803*0fca6ea1SDimitry Andric PtrIP = std::nullopt; 804*0fca6ea1SDimitry Andric else if (PtrIP && isa<PHINode>(*PtrIP)) 805*0fca6ea1SDimitry Andric PtrIP = (*PtrIP)->getParent()->getFirstInsertionPt(); 806349cc55cSDimitry Andric else if (!PtrIP) 807*0fca6ea1SDimitry Andric PtrIP = Element.Instr->getIterator(); 808349cc55cSDimitry Andric 809349cc55cSDimitry Andric assert(OffToBase && "There should be an offset for non base element!\n"); 810349cc55cSDimitry Andric GetElementPtrInst *NewPtr = GetElementPtrInst::Create( 811349cc55cSDimitry Andric I8Ty, PtrInc, OffToBase, 812*0fca6ea1SDimitry Andric getInstrName(Element.Instr, GEPNodeOffNameSuffix)); 813*0fca6ea1SDimitry Andric if (PtrIP) 814*0fca6ea1SDimitry Andric NewPtr->insertBefore(*(*PtrIP)->getParent(), *PtrIP); 815*0fca6ea1SDimitry Andric else 816349cc55cSDimitry Andric NewPtr->insertAfter(cast<Instruction>(PtrInc)); 817349cc55cSDimitry Andric NewPtr->setIsInBounds(IsPtrInBounds(Ptr)); 818349cc55cSDimitry Andric RealNewPtr = NewPtr; 819349cc55cSDimitry Andric } 820349cc55cSDimitry Andric 821349cc55cSDimitry Andric Instruction *ReplNewPtr; 822349cc55cSDimitry Andric if (Ptr->getType() != RealNewPtr->getType()) { 823349cc55cSDimitry Andric ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(), 824349cc55cSDimitry Andric getInstrName(Ptr, CastNodeNameSuffix)); 825349cc55cSDimitry Andric ReplNewPtr->insertAfter(RealNewPtr); 826349cc55cSDimitry Andric } else 827349cc55cSDimitry Andric ReplNewPtr = RealNewPtr; 828349cc55cSDimitry Andric 829349cc55cSDimitry Andric Ptr->replaceAllUsesWith(ReplNewPtr); 830349cc55cSDimitry Andric DeletedPtrs.insert(Ptr); 831349cc55cSDimitry Andric 832349cc55cSDimitry Andric return ReplNewPtr; 833349cc55cSDimitry Andric } 834349cc55cSDimitry Andric 835349cc55cSDimitry Andric void PPCLoopInstrFormPrep::addOneCandidate( 836349cc55cSDimitry Andric Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets, 837349cc55cSDimitry Andric std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) { 838349cc55cSDimitry Andric assert((MemI && getPointerOperandAndType(MemI)) && 839480093f4SDimitry Andric "Candidate should be a memory instruction."); 840480093f4SDimitry Andric assert(LSCEV && "Invalid SCEV for Ptr value."); 841349cc55cSDimitry Andric 842480093f4SDimitry Andric bool FoundBucket = false; 843480093f4SDimitry Andric for (auto &B : Buckets) { 844349cc55cSDimitry Andric if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) != 845349cc55cSDimitry Andric cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE)) 846349cc55cSDimitry Andric continue; 847480093f4SDimitry Andric const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV); 848349cc55cSDimitry Andric if (isValidDiff(Diff)) { 849349cc55cSDimitry Andric B.Elements.push_back(BucketElement(Diff, MemI)); 850480093f4SDimitry Andric FoundBucket = true; 851480093f4SDimitry Andric break; 852480093f4SDimitry Andric } 853480093f4SDimitry Andric } 854480093f4SDimitry Andric 855480093f4SDimitry Andric if (!FoundBucket) { 856349cc55cSDimitry Andric if (Buckets.size() == MaxCandidateNum) { 857349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit " 858349cc55cSDimitry Andric << MaxCandidateNum << "\n"); 859480093f4SDimitry Andric return; 860349cc55cSDimitry Andric } 861480093f4SDimitry Andric Buckets.push_back(Bucket(LSCEV, MemI)); 862480093f4SDimitry Andric } 863480093f4SDimitry Andric } 864480093f4SDimitry Andric 865480093f4SDimitry Andric SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates( 866480093f4SDimitry Andric Loop *L, 867349cc55cSDimitry Andric std::function<bool(const Instruction *, Value *, const Type *)> 868fe6060f1SDimitry Andric isValidCandidate, 869349cc55cSDimitry Andric std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) { 870480093f4SDimitry Andric SmallVector<Bucket, 16> Buckets; 871349cc55cSDimitry Andric 872480093f4SDimitry Andric for (const auto &BB : L->blocks()) 873480093f4SDimitry Andric for (auto &J : *BB) { 874349cc55cSDimitry Andric Value *PtrValue = nullptr; 875349cc55cSDimitry Andric Type *PointerElementType = nullptr; 876349cc55cSDimitry Andric PtrValue = getPointerOperandAndType(&J, &PointerElementType); 877480093f4SDimitry Andric 878349cc55cSDimitry Andric if (!PtrValue) 879349cc55cSDimitry Andric continue; 880480093f4SDimitry Andric 881349cc55cSDimitry Andric if (PtrValue->getType()->getPointerAddressSpace()) 882480093f4SDimitry Andric continue; 883480093f4SDimitry Andric 884480093f4SDimitry Andric if (L->isLoopInvariant(PtrValue)) 885480093f4SDimitry Andric continue; 886480093f4SDimitry Andric 887480093f4SDimitry Andric const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L); 888480093f4SDimitry Andric const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV); 889480093f4SDimitry Andric if (!LARSCEV || LARSCEV->getLoop() != L) 890480093f4SDimitry Andric continue; 891480093f4SDimitry Andric 892349cc55cSDimitry Andric // Mark that we have candidates for preparing. 893349cc55cSDimitry Andric HasCandidateForPrepare = true; 894349cc55cSDimitry Andric 895fe6060f1SDimitry Andric if (isValidCandidate(&J, PtrValue, PointerElementType)) 896349cc55cSDimitry Andric addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum); 897480093f4SDimitry Andric } 898480093f4SDimitry Andric return Buckets; 899480093f4SDimitry Andric } 900480093f4SDimitry Andric 901480093f4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain, 902349cc55cSDimitry Andric PrepForm Form) { 903480093f4SDimitry Andric // RemainderOffsetInfo details: 904480093f4SDimitry Andric // key: value of (Offset urem DispConstraint). For DSForm, it can 905480093f4SDimitry Andric // be [0, 4). 906480093f4SDimitry Andric // first of pair: the index of first BucketElement whose remainder is equal 907480093f4SDimitry Andric // to key. For key 0, this value must be 0. 908480093f4SDimitry Andric // second of pair: number of load/stores with the same remainder. 909480093f4SDimitry Andric DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo; 910480093f4SDimitry Andric 911480093f4SDimitry Andric for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) { 912480093f4SDimitry Andric if (!BucketChain.Elements[j].Offset) 913480093f4SDimitry Andric RemainderOffsetInfo[0] = std::make_pair(0, 1); 914480093f4SDimitry Andric else { 915349cc55cSDimitry Andric unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset) 916349cc55cSDimitry Andric ->getAPInt() 917349cc55cSDimitry Andric .urem(Form); 91806c3fb27SDimitry Andric if (!RemainderOffsetInfo.contains(Remainder)) 919480093f4SDimitry Andric RemainderOffsetInfo[Remainder] = std::make_pair(j, 1); 920480093f4SDimitry Andric else 921480093f4SDimitry Andric RemainderOffsetInfo[Remainder].second++; 922480093f4SDimitry Andric } 923480093f4SDimitry Andric } 924480093f4SDimitry Andric // Currently we choose the most profitable base as the one which has the max 925480093f4SDimitry Andric // number of load/store with same remainder. 926480093f4SDimitry Andric // FIXME: adjust the base selection strategy according to load/store offset 927480093f4SDimitry Andric // distribution. 928480093f4SDimitry Andric // For example, if we have one candidate chain for DS form preparation, which 929480093f4SDimitry Andric // contains following load/stores with different remainders: 930480093f4SDimitry Andric // 1: 10 load/store whose remainder is 1; 931480093f4SDimitry Andric // 2: 9 load/store whose remainder is 2; 932480093f4SDimitry Andric // 3: 1 for remainder 3 and 0 for remainder 0; 933480093f4SDimitry Andric // Now we will choose the first load/store whose remainder is 1 as base and 934480093f4SDimitry Andric // adjust all other load/stores according to new base, so we will get 10 DS 935480093f4SDimitry Andric // form and 10 X form. 936480093f4SDimitry Andric // But we should be more clever, for this case we could use two bases, one for 937349cc55cSDimitry Andric // remainder 1 and the other for remainder 2, thus we could get 19 DS form and 938349cc55cSDimitry Andric // 1 X form. 939480093f4SDimitry Andric unsigned MaxCountRemainder = 0; 940480093f4SDimitry Andric for (unsigned j = 0; j < (unsigned)Form; j++) 94106c3fb27SDimitry Andric if ((RemainderOffsetInfo.contains(j)) && 942480093f4SDimitry Andric RemainderOffsetInfo[j].second > 943480093f4SDimitry Andric RemainderOffsetInfo[MaxCountRemainder].second) 944480093f4SDimitry Andric MaxCountRemainder = j; 945480093f4SDimitry Andric 946480093f4SDimitry Andric // Abort when there are too few insts with common base. 947480093f4SDimitry Andric if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold) 948480093f4SDimitry Andric return false; 949480093f4SDimitry Andric 950480093f4SDimitry Andric // If the first value is most profitable, no needed to adjust BucketChain 951480093f4SDimitry Andric // elements as they are substracted the first value when collecting. 952480093f4SDimitry Andric if (MaxCountRemainder == 0) 953480093f4SDimitry Andric return true; 954480093f4SDimitry Andric 955480093f4SDimitry Andric // Adjust load/store to the new chosen base. 956480093f4SDimitry Andric const SCEV *Offset = 957480093f4SDimitry Andric BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset; 958480093f4SDimitry Andric BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset); 959480093f4SDimitry Andric for (auto &E : BucketChain.Elements) { 960480093f4SDimitry Andric if (E.Offset) 961480093f4SDimitry Andric E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset)); 962480093f4SDimitry Andric else 963480093f4SDimitry Andric E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset)); 964480093f4SDimitry Andric } 965480093f4SDimitry Andric 966480093f4SDimitry Andric std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first], 967480093f4SDimitry Andric BucketChain.Elements[0]); 968480093f4SDimitry Andric return true; 969480093f4SDimitry Andric } 970480093f4SDimitry Andric 971480093f4SDimitry Andric // FIXME: implement a more clever base choosing policy. 972480093f4SDimitry Andric // Currently we always choose an exist load/store offset. This maybe lead to 973480093f4SDimitry Andric // suboptimal code sequences. For example, for one DS chain with offsets 974480093f4SDimitry Andric // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp 975480093f4SDimitry Andric // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a 976480093f4SDimitry Andric // multipler of 4, it cannot be represented by sint16. 977480093f4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) { 978480093f4SDimitry Andric // We have a choice now of which instruction's memory operand we use as the 979480093f4SDimitry Andric // base for the generated PHI. Always picking the first instruction in each 980480093f4SDimitry Andric // bucket does not work well, specifically because that instruction might 981480093f4SDimitry Andric // be a prefetch (and there are no pre-increment dcbt variants). Otherwise, 982480093f4SDimitry Andric // the choice is somewhat arbitrary, because the backend will happily 983480093f4SDimitry Andric // generate direct offsets from both the pre-incremented and 984480093f4SDimitry Andric // post-incremented pointer values. Thus, we'll pick the first non-prefetch 985480093f4SDimitry Andric // instruction in each bucket, and adjust the recurrence and other offsets 986480093f4SDimitry Andric // accordingly. 987480093f4SDimitry Andric for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) { 988480093f4SDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr)) 989480093f4SDimitry Andric if (II->getIntrinsicID() == Intrinsic::prefetch) 990480093f4SDimitry Andric continue; 991480093f4SDimitry Andric 992480093f4SDimitry Andric // If we'd otherwise pick the first element anyway, there's nothing to do. 993480093f4SDimitry Andric if (j == 0) 994480093f4SDimitry Andric break; 995480093f4SDimitry Andric 996480093f4SDimitry Andric // If our chosen element has no offset from the base pointer, there's 997480093f4SDimitry Andric // nothing to do. 998480093f4SDimitry Andric if (!BucketChain.Elements[j].Offset || 999349cc55cSDimitry Andric cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero()) 1000480093f4SDimitry Andric break; 1001480093f4SDimitry Andric 1002480093f4SDimitry Andric const SCEV *Offset = BucketChain.Elements[j].Offset; 1003480093f4SDimitry Andric BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset); 1004480093f4SDimitry Andric for (auto &E : BucketChain.Elements) { 1005480093f4SDimitry Andric if (E.Offset) 1006480093f4SDimitry Andric E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset)); 1007480093f4SDimitry Andric else 1008480093f4SDimitry Andric E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset)); 1009480093f4SDimitry Andric } 1010480093f4SDimitry Andric 1011480093f4SDimitry Andric std::swap(BucketChain.Elements[j], BucketChain.Elements[0]); 1012480093f4SDimitry Andric break; 1013480093f4SDimitry Andric } 1014480093f4SDimitry Andric return true; 1015480093f4SDimitry Andric } 1016480093f4SDimitry Andric 1017349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStores( 1018349cc55cSDimitry Andric Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged, 1019349cc55cSDimitry Andric PrepForm Form) { 1020480093f4SDimitry Andric bool MadeChange = false; 1021349cc55cSDimitry Andric 1022480093f4SDimitry Andric const SCEVAddRecExpr *BasePtrSCEV = 1023480093f4SDimitry Andric cast<SCEVAddRecExpr>(BucketChain.BaseSCEV); 1024480093f4SDimitry Andric if (!BasePtrSCEV->isAffine()) 1025480093f4SDimitry Andric return MadeChange; 1026480093f4SDimitry Andric 1027480093f4SDimitry Andric BasicBlock *Header = L->getHeader(); 1028*0fca6ea1SDimitry Andric SCEVExpander SCEVE(*SE, Header->getDataLayout(), 1029349cc55cSDimitry Andric "loopprepare-formrewrite"); 1030fcaf7f86SDimitry Andric if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart())) 1031fcaf7f86SDimitry Andric return MadeChange; 1032fcaf7f86SDimitry Andric 1033fcaf7f86SDimitry Andric SmallPtrSet<Value *, 16> DeletedPtrs; 1034480093f4SDimitry Andric 1035349cc55cSDimitry Andric // For some DS form load/store instructions, it can also be an update form, 1036349cc55cSDimitry Andric // if the stride is constant and is a multipler of 4. Use update form if 1037349cc55cSDimitry Andric // prefer it. 1038349cc55cSDimitry Andric bool CanPreInc = (Form == UpdateForm || 1039349cc55cSDimitry Andric ((Form == DSForm) && 1040349cc55cSDimitry Andric isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) && 1041349cc55cSDimitry Andric !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) 1042349cc55cSDimitry Andric ->getAPInt() 1043349cc55cSDimitry Andric .urem(4) && 1044349cc55cSDimitry Andric PreferUpdateForm)); 1045480093f4SDimitry Andric 1046349cc55cSDimitry Andric std::pair<Instruction *, Instruction *> Base = 1047349cc55cSDimitry Andric rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr, 1048349cc55cSDimitry Andric CanPreInc, Form, SCEVE, DeletedPtrs); 1049480093f4SDimitry Andric 1050349cc55cSDimitry Andric if (!Base.first || !Base.second) 1051349cc55cSDimitry Andric return MadeChange; 1052349cc55cSDimitry Andric 1053349cc55cSDimitry Andric // Keep track of the replacement pointer values we've inserted so that we 1054349cc55cSDimitry Andric // don't generate more pointer values than necessary. 1055349cc55cSDimitry Andric SmallPtrSet<Value *, 16> NewPtrs; 1056349cc55cSDimitry Andric NewPtrs.insert(Base.first); 1057349cc55cSDimitry Andric 1058bdd1243dSDimitry Andric for (const BucketElement &BE : llvm::drop_begin(BucketChain.Elements)) { 1059bdd1243dSDimitry Andric Value *Ptr = getPointerOperandAndType(BE.Instr); 1060349cc55cSDimitry Andric assert(Ptr && "No pointer operand"); 1061349cc55cSDimitry Andric if (NewPtrs.count(Ptr)) 1062480093f4SDimitry Andric continue; 1063480093f4SDimitry Andric 1064349cc55cSDimitry Andric Instruction *NewPtr = rewriteForBucketElement( 1065bdd1243dSDimitry Andric Base, BE, 1066bdd1243dSDimitry Andric BE.Offset ? cast<SCEVConstant>(BE.Offset)->getValue() : nullptr, 1067349cc55cSDimitry Andric DeletedPtrs); 1068349cc55cSDimitry Andric assert(NewPtr && "wrong rewrite!\n"); 1069349cc55cSDimitry Andric NewPtrs.insert(NewPtr); 1070480093f4SDimitry Andric } 1071480093f4SDimitry Andric 1072e8d8bef9SDimitry Andric // Clear the rewriter cache, because values that are in the rewriter's cache 1073e8d8bef9SDimitry Andric // can be deleted below, causing the AssertingVH in the cache to trigger. 1074e8d8bef9SDimitry Andric SCEVE.clear(); 1075e8d8bef9SDimitry Andric 1076349cc55cSDimitry Andric for (auto *Ptr : DeletedPtrs) { 1077480093f4SDimitry Andric if (Instruction *IDel = dyn_cast<Instruction>(Ptr)) 1078480093f4SDimitry Andric BBChanged.insert(IDel->getParent()); 1079480093f4SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(Ptr); 1080480093f4SDimitry Andric } 1081480093f4SDimitry Andric 1082480093f4SDimitry Andric MadeChange = true; 1083480093f4SDimitry Andric 1084480093f4SDimitry Andric SuccPrepCount++; 1085480093f4SDimitry Andric 1086480093f4SDimitry Andric if (Form == DSForm && !CanPreInc) 1087480093f4SDimitry Andric DSFormChainRewritten++; 1088480093f4SDimitry Andric else if (Form == DQForm) 1089480093f4SDimitry Andric DQFormChainRewritten++; 1090480093f4SDimitry Andric else if (Form == UpdateForm || (Form == DSForm && CanPreInc)) 1091480093f4SDimitry Andric UpdFormChainRewritten++; 1092480093f4SDimitry Andric 1093480093f4SDimitry Andric return MadeChange; 1094480093f4SDimitry Andric } 1095480093f4SDimitry Andric 1096480093f4SDimitry Andric bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L, 1097480093f4SDimitry Andric SmallVector<Bucket, 16> &Buckets) { 1098480093f4SDimitry Andric bool MadeChange = false; 1099480093f4SDimitry Andric if (Buckets.empty()) 1100480093f4SDimitry Andric return MadeChange; 1101480093f4SDimitry Andric SmallSet<BasicBlock *, 16> BBChanged; 1102480093f4SDimitry Andric for (auto &Bucket : Buckets) 1103480093f4SDimitry Andric // The base address of each bucket is transformed into a phi and the others 1104480093f4SDimitry Andric // are rewritten based on new base. 1105480093f4SDimitry Andric if (prepareBaseForUpdateFormChain(Bucket)) 1106480093f4SDimitry Andric MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm); 1107480093f4SDimitry Andric 1108480093f4SDimitry Andric if (MadeChange) 1109349cc55cSDimitry Andric for (auto *BB : BBChanged) 1110480093f4SDimitry Andric DeleteDeadPHIs(BB); 1111480093f4SDimitry Andric return MadeChange; 1112480093f4SDimitry Andric } 1113480093f4SDimitry Andric 1114349cc55cSDimitry Andric bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L, 1115349cc55cSDimitry Andric SmallVector<Bucket, 16> &Buckets, 1116349cc55cSDimitry Andric PrepForm Form) { 1117480093f4SDimitry Andric bool MadeChange = false; 1118480093f4SDimitry Andric 1119480093f4SDimitry Andric if (Buckets.empty()) 1120480093f4SDimitry Andric return MadeChange; 1121480093f4SDimitry Andric 1122480093f4SDimitry Andric SmallSet<BasicBlock *, 16> BBChanged; 1123480093f4SDimitry Andric for (auto &Bucket : Buckets) { 1124480093f4SDimitry Andric if (Bucket.Elements.size() < DispFormPrepMinThreshold) 1125480093f4SDimitry Andric continue; 1126480093f4SDimitry Andric if (prepareBaseForDispFormChain(Bucket, Form)) 1127480093f4SDimitry Andric MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form); 1128480093f4SDimitry Andric } 1129480093f4SDimitry Andric 1130480093f4SDimitry Andric if (MadeChange) 1131349cc55cSDimitry Andric for (auto *BB : BBChanged) 1132480093f4SDimitry Andric DeleteDeadPHIs(BB); 1133480093f4SDimitry Andric return MadeChange; 1134480093f4SDimitry Andric } 1135480093f4SDimitry Andric 1136349cc55cSDimitry Andric // Find the loop invariant increment node for SCEV BasePtrIncSCEV. 1137349cc55cSDimitry Andric // bb.loop.preheader: 1138349cc55cSDimitry Andric // %start = ... 1139349cc55cSDimitry Andric // bb.loop.body: 1140349cc55cSDimitry Andric // %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ] 1141349cc55cSDimitry Andric // ... 1142349cc55cSDimitry Andric // %add = add %phinode, %inc ; %inc is what we want to get. 1143349cc55cSDimitry Andric // 1144349cc55cSDimitry Andric Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI, 1145349cc55cSDimitry Andric const SCEV *BasePtrIncSCEV) { 1146349cc55cSDimitry Andric // If the increment is a constant, no definition is needed. 1147349cc55cSDimitry Andric // Return the value directly. 1148349cc55cSDimitry Andric if (isa<SCEVConstant>(BasePtrIncSCEV)) 1149349cc55cSDimitry Andric return cast<SCEVConstant>(BasePtrIncSCEV)->getValue(); 1150349cc55cSDimitry Andric 1151349cc55cSDimitry Andric if (!SE->isLoopInvariant(BasePtrIncSCEV, L)) 1152349cc55cSDimitry Andric return nullptr; 1153349cc55cSDimitry Andric 1154349cc55cSDimitry Andric BasicBlock *BB = MemI->getParent(); 1155349cc55cSDimitry Andric if (!BB) 1156349cc55cSDimitry Andric return nullptr; 1157349cc55cSDimitry Andric 1158349cc55cSDimitry Andric BasicBlock *LatchBB = L->getLoopLatch(); 1159349cc55cSDimitry Andric 1160349cc55cSDimitry Andric if (!LatchBB) 1161349cc55cSDimitry Andric return nullptr; 1162349cc55cSDimitry Andric 1163349cc55cSDimitry Andric // Run through the PHIs and check their operands to find valid representation 1164349cc55cSDimitry Andric // for the increment SCEV. 1165349cc55cSDimitry Andric iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis(); 1166349cc55cSDimitry Andric for (auto &CurrentPHI : PHIIter) { 1167349cc55cSDimitry Andric PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI); 1168349cc55cSDimitry Andric if (!CurrentPHINode) 1169349cc55cSDimitry Andric continue; 1170349cc55cSDimitry Andric 1171349cc55cSDimitry Andric if (!SE->isSCEVable(CurrentPHINode->getType())) 1172349cc55cSDimitry Andric continue; 1173349cc55cSDimitry Andric 1174349cc55cSDimitry Andric const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L); 1175349cc55cSDimitry Andric 1176349cc55cSDimitry Andric const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV); 1177349cc55cSDimitry Andric if (!PHIBasePtrSCEV) 1178349cc55cSDimitry Andric continue; 1179349cc55cSDimitry Andric 1180349cc55cSDimitry Andric const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE); 1181349cc55cSDimitry Andric 1182349cc55cSDimitry Andric if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV)) 1183349cc55cSDimitry Andric continue; 1184349cc55cSDimitry Andric 1185349cc55cSDimitry Andric // Get the incoming value from the loop latch and check if the value has 1186349cc55cSDimitry Andric // the add form with the required increment. 118706c3fb27SDimitry Andric if (CurrentPHINode->getBasicBlockIndex(LatchBB) < 0) 118806c3fb27SDimitry Andric continue; 1189349cc55cSDimitry Andric if (Instruction *I = dyn_cast<Instruction>( 1190349cc55cSDimitry Andric CurrentPHINode->getIncomingValueForBlock(LatchBB))) { 1191349cc55cSDimitry Andric Value *StrippedBaseI = I; 1192349cc55cSDimitry Andric while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI)) 1193349cc55cSDimitry Andric StrippedBaseI = BC->getOperand(0); 1194349cc55cSDimitry Andric 1195349cc55cSDimitry Andric Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI); 1196349cc55cSDimitry Andric if (!StrippedI) 1197349cc55cSDimitry Andric continue; 1198349cc55cSDimitry Andric 1199349cc55cSDimitry Andric // LSR pass may add a getelementptr instruction to do the loop increment, 1200349cc55cSDimitry Andric // also search in that getelementptr instruction. 1201349cc55cSDimitry Andric if (StrippedI->getOpcode() == Instruction::Add || 1202349cc55cSDimitry Andric (StrippedI->getOpcode() == Instruction::GetElementPtr && 1203349cc55cSDimitry Andric StrippedI->getNumOperands() == 2)) { 1204349cc55cSDimitry Andric if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV) 1205349cc55cSDimitry Andric return StrippedI->getOperand(0); 1206349cc55cSDimitry Andric if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV) 1207349cc55cSDimitry Andric return StrippedI->getOperand(1); 1208349cc55cSDimitry Andric } 1209349cc55cSDimitry Andric } 1210349cc55cSDimitry Andric } 1211349cc55cSDimitry Andric return nullptr; 1212349cc55cSDimitry Andric } 1213349cc55cSDimitry Andric 1214480093f4SDimitry Andric // In order to prepare for the preferred instruction form, a PHI is added. 1215480093f4SDimitry Andric // This function will check to see if that PHI already exists and will return 1216480093f4SDimitry Andric // true if it found an existing PHI with the matched start and increment as the 1217480093f4SDimitry Andric // one we wanted to create. 1218480093f4SDimitry Andric bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI, 1219480093f4SDimitry Andric const SCEV *BasePtrStartSCEV, 1220349cc55cSDimitry Andric const SCEV *BasePtrIncSCEV, 1221349cc55cSDimitry Andric PrepForm Form) { 1222480093f4SDimitry Andric BasicBlock *BB = MemI->getParent(); 1223480093f4SDimitry Andric if (!BB) 1224480093f4SDimitry Andric return false; 1225480093f4SDimitry Andric 1226480093f4SDimitry Andric BasicBlock *PredBB = L->getLoopPredecessor(); 1227480093f4SDimitry Andric BasicBlock *LatchBB = L->getLoopLatch(); 1228480093f4SDimitry Andric 1229480093f4SDimitry Andric if (!PredBB || !LatchBB) 1230480093f4SDimitry Andric return false; 1231480093f4SDimitry Andric 1232480093f4SDimitry Andric // Run through the PHIs and see if we have some that looks like a preparation 1233480093f4SDimitry Andric iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis(); 1234480093f4SDimitry Andric for (auto & CurrentPHI : PHIIter) { 1235480093f4SDimitry Andric PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI); 1236480093f4SDimitry Andric if (!CurrentPHINode) 1237480093f4SDimitry Andric continue; 1238480093f4SDimitry Andric 1239480093f4SDimitry Andric if (!SE->isSCEVable(CurrentPHINode->getType())) 1240480093f4SDimitry Andric continue; 1241480093f4SDimitry Andric 1242480093f4SDimitry Andric const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L); 1243480093f4SDimitry Andric 1244480093f4SDimitry Andric const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV); 1245480093f4SDimitry Andric if (!PHIBasePtrSCEV) 1246480093f4SDimitry Andric continue; 1247480093f4SDimitry Andric 1248480093f4SDimitry Andric const SCEVConstant *PHIBasePtrIncSCEV = 1249480093f4SDimitry Andric dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE)); 1250480093f4SDimitry Andric if (!PHIBasePtrIncSCEV) 1251480093f4SDimitry Andric continue; 1252480093f4SDimitry Andric 1253480093f4SDimitry Andric if (CurrentPHINode->getNumIncomingValues() == 2) { 1254480093f4SDimitry Andric if ((CurrentPHINode->getIncomingBlock(0) == LatchBB && 1255480093f4SDimitry Andric CurrentPHINode->getIncomingBlock(1) == PredBB) || 1256480093f4SDimitry Andric (CurrentPHINode->getIncomingBlock(1) == LatchBB && 1257480093f4SDimitry Andric CurrentPHINode->getIncomingBlock(0) == PredBB)) { 1258480093f4SDimitry Andric if (PHIBasePtrIncSCEV == BasePtrIncSCEV) { 1259480093f4SDimitry Andric // The existing PHI (CurrentPHINode) has the same start and increment 1260480093f4SDimitry Andric // as the PHI that we wanted to create. 1261349cc55cSDimitry Andric if ((Form == UpdateForm || Form == ChainCommoning ) && 1262480093f4SDimitry Andric PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) { 1263480093f4SDimitry Andric ++PHINodeAlreadyExistsUpdate; 1264480093f4SDimitry Andric return true; 1265480093f4SDimitry Andric } 1266480093f4SDimitry Andric if (Form == DSForm || Form == DQForm) { 1267480093f4SDimitry Andric const SCEVConstant *Diff = dyn_cast<SCEVConstant>( 1268480093f4SDimitry Andric SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV)); 1269480093f4SDimitry Andric if (Diff && !Diff->getAPInt().urem(Form)) { 1270480093f4SDimitry Andric if (Form == DSForm) 1271480093f4SDimitry Andric ++PHINodeAlreadyExistsDS; 1272480093f4SDimitry Andric else 1273480093f4SDimitry Andric ++PHINodeAlreadyExistsDQ; 1274480093f4SDimitry Andric return true; 1275480093f4SDimitry Andric } 1276480093f4SDimitry Andric } 1277480093f4SDimitry Andric } 1278480093f4SDimitry Andric } 1279480093f4SDimitry Andric } 1280480093f4SDimitry Andric } 1281480093f4SDimitry Andric return false; 1282480093f4SDimitry Andric } 1283480093f4SDimitry Andric 1284480093f4SDimitry Andric bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) { 1285480093f4SDimitry Andric bool MadeChange = false; 1286480093f4SDimitry Andric 1287480093f4SDimitry Andric // Only prep. the inner-most loop 1288e8d8bef9SDimitry Andric if (!L->isInnermost()) 1289480093f4SDimitry Andric return MadeChange; 1290480093f4SDimitry Andric 1291480093f4SDimitry Andric // Return if already done enough preparation. 1292480093f4SDimitry Andric if (SuccPrepCount >= MaxVarsPrep) 1293480093f4SDimitry Andric return MadeChange; 1294480093f4SDimitry Andric 1295480093f4SDimitry Andric LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n"); 1296480093f4SDimitry Andric 1297480093f4SDimitry Andric BasicBlock *LoopPredecessor = L->getLoopPredecessor(); 1298480093f4SDimitry Andric // If there is no loop predecessor, or the loop predecessor's terminator 1299480093f4SDimitry Andric // returns a value (which might contribute to determining the loop's 1300480093f4SDimitry Andric // iteration space), insert a new preheader for the loop. 1301480093f4SDimitry Andric if (!LoopPredecessor || 1302480093f4SDimitry Andric !LoopPredecessor->getTerminator()->getType()->isVoidTy()) { 1303480093f4SDimitry Andric LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA); 1304480093f4SDimitry Andric if (LoopPredecessor) 1305480093f4SDimitry Andric MadeChange = true; 1306480093f4SDimitry Andric } 1307480093f4SDimitry Andric if (!LoopPredecessor) { 1308480093f4SDimitry Andric LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n"); 1309480093f4SDimitry Andric return MadeChange; 1310480093f4SDimitry Andric } 1311480093f4SDimitry Andric // Check if a load/store has update form. This lambda is used by function 1312480093f4SDimitry Andric // collectCandidates which can collect candidates for types defined by lambda. 1313349cc55cSDimitry Andric auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue, 1314fe6060f1SDimitry Andric const Type *PointerElementType) { 1315480093f4SDimitry Andric assert((PtrValue && I) && "Invalid parameter!"); 1316480093f4SDimitry Andric // There are no update forms for Altivec vector load/stores. 1317fe6060f1SDimitry Andric if (ST && ST->hasAltivec() && PointerElementType->isVectorTy()) 1318480093f4SDimitry Andric return false; 1319e8d8bef9SDimitry Andric // There are no update forms for P10 lxvp/stxvp intrinsic. 1320e8d8bef9SDimitry Andric auto *II = dyn_cast<IntrinsicInst>(I); 1321e8d8bef9SDimitry Andric if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) || 1322e8d8bef9SDimitry Andric II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp)) 1323e8d8bef9SDimitry Andric return false; 1324480093f4SDimitry Andric // See getPreIndexedAddressParts, the displacement for LDU/STDU has to 1325480093f4SDimitry Andric // be 4's multiple (DS-form). For i64 loads/stores when the displacement 1326480093f4SDimitry Andric // fits in a 16-bit signed field but isn't a multiple of 4, it will be 1327480093f4SDimitry Andric // useless and possible to break some original well-form addressing mode 1328480093f4SDimitry Andric // to make this pre-inc prep for it. 1329fe6060f1SDimitry Andric if (PointerElementType->isIntegerTy(64)) { 1330480093f4SDimitry Andric const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L); 1331480093f4SDimitry Andric const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV); 1332480093f4SDimitry Andric if (!LARSCEV || LARSCEV->getLoop() != L) 1333480093f4SDimitry Andric return false; 1334480093f4SDimitry Andric if (const SCEVConstant *StepConst = 1335480093f4SDimitry Andric dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) { 1336480093f4SDimitry Andric const APInt &ConstInt = StepConst->getValue()->getValue(); 1337480093f4SDimitry Andric if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0) 1338480093f4SDimitry Andric return false; 1339480093f4SDimitry Andric } 1340480093f4SDimitry Andric } 1341480093f4SDimitry Andric return true; 1342480093f4SDimitry Andric }; 1343480093f4SDimitry Andric 1344480093f4SDimitry Andric // Check if a load/store has DS form. 1345349cc55cSDimitry Andric auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue, 1346fe6060f1SDimitry Andric const Type *PointerElementType) { 1347480093f4SDimitry Andric assert((PtrValue && I) && "Invalid parameter!"); 1348480093f4SDimitry Andric if (isa<IntrinsicInst>(I)) 1349480093f4SDimitry Andric return false; 1350480093f4SDimitry Andric return (PointerElementType->isIntegerTy(64)) || 1351480093f4SDimitry Andric (PointerElementType->isFloatTy()) || 1352480093f4SDimitry Andric (PointerElementType->isDoubleTy()) || 1353480093f4SDimitry Andric (PointerElementType->isIntegerTy(32) && 1354480093f4SDimitry Andric llvm::any_of(I->users(), 1355480093f4SDimitry Andric [](const User *U) { return isa<SExtInst>(U); })); 1356480093f4SDimitry Andric }; 1357480093f4SDimitry Andric 1358480093f4SDimitry Andric // Check if a load/store has DQ form. 1359349cc55cSDimitry Andric auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue, 1360fe6060f1SDimitry Andric const Type *PointerElementType) { 1361480093f4SDimitry Andric assert((PtrValue && I) && "Invalid parameter!"); 1362e8d8bef9SDimitry Andric // Check if it is a P10 lxvp/stxvp intrinsic. 1363e8d8bef9SDimitry Andric auto *II = dyn_cast<IntrinsicInst>(I); 1364e8d8bef9SDimitry Andric if (II) 1365e8d8bef9SDimitry Andric return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp || 1366e8d8bef9SDimitry Andric II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp; 1367e8d8bef9SDimitry Andric // Check if it is a P9 vector load/store. 1368fe6060f1SDimitry Andric return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy()); 1369480093f4SDimitry Andric }; 1370480093f4SDimitry Andric 1371349cc55cSDimitry Andric // Check if a load/store is candidate for chain commoning. 1372349cc55cSDimitry Andric // If the SCEV is only with one ptr operand in its start, we can use that 1373349cc55cSDimitry Andric // start as a chain separator. Mark this load/store as a candidate. 1374349cc55cSDimitry Andric auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue, 1375349cc55cSDimitry Andric const Type *PointerElementType) { 1376349cc55cSDimitry Andric const SCEVAddRecExpr *ARSCEV = 1377349cc55cSDimitry Andric cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L)); 1378349cc55cSDimitry Andric if (!ARSCEV) 1379349cc55cSDimitry Andric return false; 1380349cc55cSDimitry Andric 1381349cc55cSDimitry Andric if (!ARSCEV->isAffine()) 1382349cc55cSDimitry Andric return false; 1383349cc55cSDimitry Andric 1384349cc55cSDimitry Andric const SCEV *Start = ARSCEV->getStart(); 1385349cc55cSDimitry Andric 1386349cc55cSDimitry Andric // A single pointer. We can treat it as offset 0. 1387349cc55cSDimitry Andric if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy()) 1388349cc55cSDimitry Andric return true; 1389349cc55cSDimitry Andric 1390349cc55cSDimitry Andric const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start); 1391349cc55cSDimitry Andric 1392349cc55cSDimitry Andric // We need a SCEVAddExpr to include both base and offset. 1393349cc55cSDimitry Andric if (!ASCEV) 1394349cc55cSDimitry Andric return false; 1395349cc55cSDimitry Andric 1396349cc55cSDimitry Andric // Make sure there is only one pointer operand(base) and all other operands 1397349cc55cSDimitry Andric // are integer type. 1398349cc55cSDimitry Andric bool SawPointer = false; 1399349cc55cSDimitry Andric for (const SCEV *Op : ASCEV->operands()) { 1400349cc55cSDimitry Andric if (Op->getType()->isPointerTy()) { 1401349cc55cSDimitry Andric if (SawPointer) 1402349cc55cSDimitry Andric return false; 1403349cc55cSDimitry Andric SawPointer = true; 1404349cc55cSDimitry Andric } else if (!Op->getType()->isIntegerTy()) 1405349cc55cSDimitry Andric return false; 1406349cc55cSDimitry Andric } 1407349cc55cSDimitry Andric 1408349cc55cSDimitry Andric return SawPointer; 1409349cc55cSDimitry Andric }; 1410349cc55cSDimitry Andric 1411349cc55cSDimitry Andric // Check if the diff is a constant type. This is used for update/DS/DQ form 1412349cc55cSDimitry Andric // preparation. 1413349cc55cSDimitry Andric auto isValidConstantDiff = [](const SCEV *Diff) { 1414349cc55cSDimitry Andric return dyn_cast<SCEVConstant>(Diff) != nullptr; 1415349cc55cSDimitry Andric }; 1416349cc55cSDimitry Andric 1417349cc55cSDimitry Andric // Make sure the diff between the base and new candidate is required type. 1418349cc55cSDimitry Andric // This is used for chain commoning preparation. 1419349cc55cSDimitry Andric auto isValidChainCommoningDiff = [](const SCEV *Diff) { 1420349cc55cSDimitry Andric assert(Diff && "Invalid Diff!\n"); 1421349cc55cSDimitry Andric 1422349cc55cSDimitry Andric // Don't mess up previous dform prepare. 1423349cc55cSDimitry Andric if (isa<SCEVConstant>(Diff)) 1424349cc55cSDimitry Andric return false; 1425349cc55cSDimitry Andric 1426349cc55cSDimitry Andric // A single integer type offset. 1427349cc55cSDimitry Andric if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy()) 1428349cc55cSDimitry Andric return true; 1429349cc55cSDimitry Andric 1430349cc55cSDimitry Andric const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff); 1431349cc55cSDimitry Andric if (!ADiff) 1432349cc55cSDimitry Andric return false; 1433349cc55cSDimitry Andric 1434349cc55cSDimitry Andric for (const SCEV *Op : ADiff->operands()) 1435349cc55cSDimitry Andric if (!Op->getType()->isIntegerTy()) 1436349cc55cSDimitry Andric return false; 1437349cc55cSDimitry Andric 1438349cc55cSDimitry Andric return true; 1439349cc55cSDimitry Andric }; 1440349cc55cSDimitry Andric 1441349cc55cSDimitry Andric HasCandidateForPrepare = false; 1442349cc55cSDimitry Andric 1443349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n"); 1444349cc55cSDimitry Andric // Collect buckets of comparable addresses used by loads and stores for update 1445349cc55cSDimitry Andric // form. 1446349cc55cSDimitry Andric SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates( 1447349cc55cSDimitry Andric L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm); 1448480093f4SDimitry Andric 1449480093f4SDimitry Andric // Prepare for update form. 1450480093f4SDimitry Andric if (!UpdateFormBuckets.empty()) 1451480093f4SDimitry Andric MadeChange |= updateFormPrep(L, UpdateFormBuckets); 1452349cc55cSDimitry Andric else if (!HasCandidateForPrepare) { 1453349cc55cSDimitry Andric LLVM_DEBUG( 1454349cc55cSDimitry Andric dbgs() 1455349cc55cSDimitry Andric << "No prepare candidates found, stop praparation for current loop!\n"); 1456349cc55cSDimitry Andric // If no candidate for preparing, return early. 1457349cc55cSDimitry Andric return MadeChange; 1458349cc55cSDimitry Andric } 1459480093f4SDimitry Andric 1460349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n"); 1461480093f4SDimitry Andric // Collect buckets of comparable addresses used by loads and stores for DS 1462480093f4SDimitry Andric // form. 1463349cc55cSDimitry Andric SmallVector<Bucket, 16> DSFormBuckets = collectCandidates( 1464349cc55cSDimitry Andric L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm); 1465480093f4SDimitry Andric 1466480093f4SDimitry Andric // Prepare for DS form. 1467480093f4SDimitry Andric if (!DSFormBuckets.empty()) 1468480093f4SDimitry Andric MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm); 1469480093f4SDimitry Andric 1470349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n"); 1471480093f4SDimitry Andric // Collect buckets of comparable addresses used by loads and stores for DQ 1472480093f4SDimitry Andric // form. 1473349cc55cSDimitry Andric SmallVector<Bucket, 16> DQFormBuckets = collectCandidates( 1474349cc55cSDimitry Andric L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm); 1475480093f4SDimitry Andric 1476480093f4SDimitry Andric // Prepare for DQ form. 1477480093f4SDimitry Andric if (!DQFormBuckets.empty()) 1478480093f4SDimitry Andric MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm); 1479480093f4SDimitry Andric 1480349cc55cSDimitry Andric // Collect buckets of comparable addresses used by loads and stores for chain 1481349cc55cSDimitry Andric // commoning. With chain commoning, we reuse offsets between the chains, so 1482349cc55cSDimitry Andric // the register pressure will be reduced. 1483349cc55cSDimitry Andric if (!EnableChainCommoning) { 1484349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n"); 1485349cc55cSDimitry Andric return MadeChange; 1486349cc55cSDimitry Andric } 1487349cc55cSDimitry Andric 1488349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n"); 1489349cc55cSDimitry Andric SmallVector<Bucket, 16> Buckets = 1490349cc55cSDimitry Andric collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff, 1491349cc55cSDimitry Andric MaxVarsChainCommon); 1492349cc55cSDimitry Andric 1493349cc55cSDimitry Andric // Prepare for chain commoning. 1494349cc55cSDimitry Andric if (!Buckets.empty()) 1495349cc55cSDimitry Andric MadeChange |= chainCommoning(L, Buckets); 1496349cc55cSDimitry Andric 1497480093f4SDimitry Andric return MadeChange; 1498480093f4SDimitry Andric } 1499