10b57cec5SDimitry Andric //===- HexagonLoopIdiomRecognition.cpp ------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric 9e8d8bef9SDimitry Andric #include "HexagonLoopIdiomRecognition.h" 100b57cec5SDimitry Andric #include "llvm/ADT/APInt.h" 110b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 120b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h" 130b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 140b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h" 150b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 160b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 170b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 180b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 19e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h" 200b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 210b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h" 220b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h" 230b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 240b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h" 250b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 260b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 270b57cec5SDimitry Andric #include "llvm/IR/Attributes.h" 280b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 290b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 300b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 310b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 320b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 330b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 340b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 350b57cec5SDimitry Andric #include "llvm/IR/Function.h" 360b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h" 370b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 380b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 390b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 400b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 410b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 42480093f4SDimitry Andric #include "llvm/IR/IntrinsicsHexagon.h" 430b57cec5SDimitry Andric #include "llvm/IR/Module.h" 44e8d8bef9SDimitry Andric #include "llvm/IR/PassManager.h" 450b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h" 460b57cec5SDimitry Andric #include "llvm/IR/Type.h" 470b57cec5SDimitry Andric #include "llvm/IR/User.h" 480b57cec5SDimitry Andric #include "llvm/IR/Value.h" 49480093f4SDimitry Andric #include "llvm/InitializePasses.h" 500b57cec5SDimitry Andric #include "llvm/Pass.h" 510b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 520b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 530b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 540b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 550b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 560b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h" 570b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 5806c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h" 590b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h" 600b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h" 61480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 625ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 630b57cec5SDimitry Andric #include <algorithm> 640b57cec5SDimitry Andric #include <array> 650b57cec5SDimitry Andric #include <cassert> 660b57cec5SDimitry Andric #include <cstdint> 670b57cec5SDimitry Andric #include <cstdlib> 680b57cec5SDimitry Andric #include <deque> 690b57cec5SDimitry Andric #include <functional> 700b57cec5SDimitry Andric #include <iterator> 710b57cec5SDimitry Andric #include <map> 720b57cec5SDimitry Andric #include <set> 730b57cec5SDimitry Andric #include <utility> 740b57cec5SDimitry Andric #include <vector> 750b57cec5SDimitry Andric 76480093f4SDimitry Andric #define DEBUG_TYPE "hexagon-lir" 77480093f4SDimitry Andric 780b57cec5SDimitry Andric using namespace llvm; 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric static cl::opt<bool> DisableMemcpyIdiom("disable-memcpy-idiom", 810b57cec5SDimitry Andric cl::Hidden, cl::init(false), 820b57cec5SDimitry Andric cl::desc("Disable generation of memcpy in loop idiom recognition")); 830b57cec5SDimitry Andric 840b57cec5SDimitry Andric static cl::opt<bool> DisableMemmoveIdiom("disable-memmove-idiom", 850b57cec5SDimitry Andric cl::Hidden, cl::init(false), 860b57cec5SDimitry Andric cl::desc("Disable generation of memmove in loop idiom recognition")); 870b57cec5SDimitry Andric 880b57cec5SDimitry Andric static cl::opt<unsigned> RuntimeMemSizeThreshold("runtime-mem-idiom-threshold", 890b57cec5SDimitry Andric cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime " 900b57cec5SDimitry Andric "check guarding the memmove.")); 910b57cec5SDimitry Andric 920b57cec5SDimitry Andric static cl::opt<unsigned> CompileTimeMemSizeThreshold( 930b57cec5SDimitry Andric "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64), 940b57cec5SDimitry Andric cl::desc("Threshold (in bytes) to perform the transformation, if the " 950b57cec5SDimitry Andric "runtime loop count (mem transfer size) is known at compile-time.")); 960b57cec5SDimitry Andric 970b57cec5SDimitry Andric static cl::opt<bool> OnlyNonNestedMemmove("only-nonnested-memmove-idiom", 980b57cec5SDimitry Andric cl::Hidden, cl::init(true), 990b57cec5SDimitry Andric cl::desc("Only enable generating memmove in non-nested loops")); 1000b57cec5SDimitry Andric 1018bcb0991SDimitry Andric static cl::opt<bool> HexagonVolatileMemcpy( 1028bcb0991SDimitry Andric "disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false), 1030b57cec5SDimitry Andric cl::desc("Enable Hexagon-specific memcpy for volatile destination.")); 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(10000), 1060b57cec5SDimitry Andric cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR")); 1070b57cec5SDimitry Andric 1080b57cec5SDimitry Andric static const char *HexagonVolatileMemcpyName 1090b57cec5SDimitry Andric = "hexagon_memcpy_forward_vp4cp4n2"; 1100b57cec5SDimitry Andric 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric namespace llvm { 1130b57cec5SDimitry Andric 114e8d8bef9SDimitry Andric void initializeHexagonLoopIdiomRecognizeLegacyPassPass(PassRegistry &); 1150b57cec5SDimitry Andric Pass *createHexagonLoopIdiomPass(); 1160b57cec5SDimitry Andric 1170b57cec5SDimitry Andric } // end namespace llvm 1180b57cec5SDimitry Andric 1190b57cec5SDimitry Andric namespace { 1200b57cec5SDimitry Andric 121e8d8bef9SDimitry Andric class HexagonLoopIdiomRecognize { 1220b57cec5SDimitry Andric public: 123e8d8bef9SDimitry Andric explicit HexagonLoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, 124e8d8bef9SDimitry Andric LoopInfo *LF, const TargetLibraryInfo *TLI, 125e8d8bef9SDimitry Andric ScalarEvolution *SE) 126e8d8bef9SDimitry Andric : AA(AA), DT(DT), LF(LF), TLI(TLI), SE(SE) {} 1270b57cec5SDimitry Andric 128e8d8bef9SDimitry Andric bool run(Loop *L); 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric private: 1310b57cec5SDimitry Andric int getSCEVStride(const SCEVAddRecExpr *StoreEv); 1320b57cec5SDimitry Andric bool isLegalStore(Loop *CurLoop, StoreInst *SI); 1330b57cec5SDimitry Andric void collectStores(Loop *CurLoop, BasicBlock *BB, 1340b57cec5SDimitry Andric SmallVectorImpl<StoreInst *> &Stores); 1350b57cec5SDimitry Andric bool processCopyingStore(Loop *CurLoop, StoreInst *SI, const SCEV *BECount); 1360b57cec5SDimitry Andric bool coverLoop(Loop *L, SmallVectorImpl<Instruction *> &Insts) const; 1370b57cec5SDimitry Andric bool runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, const SCEV *BECount, 1380b57cec5SDimitry Andric SmallVectorImpl<BasicBlock *> &ExitBlocks); 1390b57cec5SDimitry Andric bool runOnCountableLoop(Loop *L); 1400b57cec5SDimitry Andric 1410b57cec5SDimitry Andric AliasAnalysis *AA; 1420b57cec5SDimitry Andric const DataLayout *DL; 1430b57cec5SDimitry Andric DominatorTree *DT; 1440b57cec5SDimitry Andric LoopInfo *LF; 1450b57cec5SDimitry Andric const TargetLibraryInfo *TLI; 1460b57cec5SDimitry Andric ScalarEvolution *SE; 1470b57cec5SDimitry Andric bool HasMemcpy, HasMemmove; 1480b57cec5SDimitry Andric }; 1490b57cec5SDimitry Andric 150e8d8bef9SDimitry Andric class HexagonLoopIdiomRecognizeLegacyPass : public LoopPass { 151e8d8bef9SDimitry Andric public: 152e8d8bef9SDimitry Andric static char ID; 153e8d8bef9SDimitry Andric 154e8d8bef9SDimitry Andric explicit HexagonLoopIdiomRecognizeLegacyPass() : LoopPass(ID) { 155e8d8bef9SDimitry Andric initializeHexagonLoopIdiomRecognizeLegacyPassPass( 156e8d8bef9SDimitry Andric *PassRegistry::getPassRegistry()); 157e8d8bef9SDimitry Andric } 158e8d8bef9SDimitry Andric 159e8d8bef9SDimitry Andric StringRef getPassName() const override { 160e8d8bef9SDimitry Andric return "Recognize Hexagon-specific loop idioms"; 161e8d8bef9SDimitry Andric } 162e8d8bef9SDimitry Andric 163e8d8bef9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 164e8d8bef9SDimitry Andric AU.addRequired<LoopInfoWrapperPass>(); 165e8d8bef9SDimitry Andric AU.addRequiredID(LoopSimplifyID); 166e8d8bef9SDimitry Andric AU.addRequiredID(LCSSAID); 167e8d8bef9SDimitry Andric AU.addRequired<AAResultsWrapperPass>(); 168e8d8bef9SDimitry Andric AU.addRequired<ScalarEvolutionWrapperPass>(); 169e8d8bef9SDimitry Andric AU.addRequired<DominatorTreeWrapperPass>(); 170e8d8bef9SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>(); 171e8d8bef9SDimitry Andric AU.addPreserved<TargetLibraryInfoWrapperPass>(); 172e8d8bef9SDimitry Andric } 173e8d8bef9SDimitry Andric 174e8d8bef9SDimitry Andric bool runOnLoop(Loop *L, LPPassManager &LPM) override; 175e8d8bef9SDimitry Andric }; 176e8d8bef9SDimitry Andric 1770b57cec5SDimitry Andric struct Simplifier { 1780b57cec5SDimitry Andric struct Rule { 1790b57cec5SDimitry Andric using FuncType = std::function<Value *(Instruction *, LLVMContext &)>; 1800b57cec5SDimitry Andric Rule(StringRef N, FuncType F) : Name(N), Fn(F) {} 1810b57cec5SDimitry Andric StringRef Name; // For debugging. 1820b57cec5SDimitry Andric FuncType Fn; 1830b57cec5SDimitry Andric }; 1840b57cec5SDimitry Andric 1850b57cec5SDimitry Andric void addRule(StringRef N, const Rule::FuncType &F) { 1860b57cec5SDimitry Andric Rules.push_back(Rule(N, F)); 1870b57cec5SDimitry Andric } 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric private: 1900b57cec5SDimitry Andric struct WorkListType { 1910b57cec5SDimitry Andric WorkListType() = default; 1920b57cec5SDimitry Andric 1930b57cec5SDimitry Andric void push_back(Value *V) { 1940b57cec5SDimitry Andric // Do not push back duplicates. 19581ad6265SDimitry Andric if (S.insert(V).second) 196e8d8bef9SDimitry Andric Q.push_back(V); 1970b57cec5SDimitry Andric } 1980b57cec5SDimitry Andric 1990b57cec5SDimitry Andric Value *pop_front_val() { 200e8d8bef9SDimitry Andric Value *V = Q.front(); 201e8d8bef9SDimitry Andric Q.pop_front(); 202e8d8bef9SDimitry Andric S.erase(V); 2030b57cec5SDimitry Andric return V; 2040b57cec5SDimitry Andric } 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric bool empty() const { return Q.empty(); } 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric private: 2090b57cec5SDimitry Andric std::deque<Value *> Q; 2100b57cec5SDimitry Andric std::set<Value *> S; 2110b57cec5SDimitry Andric }; 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric using ValueSetType = std::set<Value *>; 2140b57cec5SDimitry Andric 2150b57cec5SDimitry Andric std::vector<Rule> Rules; 2160b57cec5SDimitry Andric 2170b57cec5SDimitry Andric public: 2180b57cec5SDimitry Andric struct Context { 2190b57cec5SDimitry Andric using ValueMapType = DenseMap<Value *, Value *>; 2200b57cec5SDimitry Andric 2210b57cec5SDimitry Andric Value *Root; 2220b57cec5SDimitry Andric ValueSetType Used; // The set of all cloned values used by Root. 2230b57cec5SDimitry Andric ValueSetType Clones; // The set of all cloned values. 2240b57cec5SDimitry Andric LLVMContext &Ctx; 2250b57cec5SDimitry Andric 2260b57cec5SDimitry Andric Context(Instruction *Exp) 2270b57cec5SDimitry Andric : Ctx(Exp->getParent()->getParent()->getContext()) { 2280b57cec5SDimitry Andric initialize(Exp); 2290b57cec5SDimitry Andric } 2300b57cec5SDimitry Andric 2310b57cec5SDimitry Andric ~Context() { cleanup(); } 2320b57cec5SDimitry Andric 2330b57cec5SDimitry Andric void print(raw_ostream &OS, const Value *V) const; 2340b57cec5SDimitry Andric Value *materialize(BasicBlock *B, BasicBlock::iterator At); 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric private: 2370b57cec5SDimitry Andric friend struct Simplifier; 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric void initialize(Instruction *Exp); 2400b57cec5SDimitry Andric void cleanup(); 2410b57cec5SDimitry Andric 2420b57cec5SDimitry Andric template <typename FuncT> void traverse(Value *V, FuncT F); 2430b57cec5SDimitry Andric void record(Value *V); 2440b57cec5SDimitry Andric void use(Value *V); 2450b57cec5SDimitry Andric void unuse(Value *V); 2460b57cec5SDimitry Andric 2470b57cec5SDimitry Andric bool equal(const Instruction *I, const Instruction *J) const; 2480b57cec5SDimitry Andric Value *find(Value *Tree, Value *Sub) const; 2490b57cec5SDimitry Andric Value *subst(Value *Tree, Value *OldV, Value *NewV); 2500b57cec5SDimitry Andric void replace(Value *OldV, Value *NewV); 2510b57cec5SDimitry Andric void link(Instruction *I, BasicBlock *B, BasicBlock::iterator At); 2520b57cec5SDimitry Andric }; 2530b57cec5SDimitry Andric 2540b57cec5SDimitry Andric Value *simplify(Context &C); 2550b57cec5SDimitry Andric }; 2560b57cec5SDimitry Andric 2570b57cec5SDimitry Andric struct PE { 2580b57cec5SDimitry Andric PE(const Simplifier::Context &c, Value *v = nullptr) : C(c), V(v) {} 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric const Simplifier::Context &C; 2610b57cec5SDimitry Andric const Value *V; 2620b57cec5SDimitry Andric }; 2630b57cec5SDimitry Andric 2640b57cec5SDimitry Andric LLVM_ATTRIBUTE_USED 2650b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const PE &P) { 2660b57cec5SDimitry Andric P.C.print(OS, P.V ? P.V : P.C.Root); 2670b57cec5SDimitry Andric return OS; 2680b57cec5SDimitry Andric } 2690b57cec5SDimitry Andric 2700b57cec5SDimitry Andric } // end anonymous namespace 2710b57cec5SDimitry Andric 272e8d8bef9SDimitry Andric char HexagonLoopIdiomRecognizeLegacyPass::ID = 0; 2730b57cec5SDimitry Andric 274e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognizeLegacyPass, "hexagon-loop-idiom", 2750b57cec5SDimitry Andric "Recognize Hexagon-specific loop idioms", false, false) 2760b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2770b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 2780b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 2790b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 2800b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2810b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2820b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 283e8d8bef9SDimitry Andric INITIALIZE_PASS_END(HexagonLoopIdiomRecognizeLegacyPass, "hexagon-loop-idiom", 2840b57cec5SDimitry Andric "Recognize Hexagon-specific loop idioms", false, false) 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric template <typename FuncT> 2870b57cec5SDimitry Andric void Simplifier::Context::traverse(Value *V, FuncT F) { 2880b57cec5SDimitry Andric WorkListType Q; 2890b57cec5SDimitry Andric Q.push_back(V); 2900b57cec5SDimitry Andric 2910b57cec5SDimitry Andric while (!Q.empty()) { 2920b57cec5SDimitry Andric Instruction *U = dyn_cast<Instruction>(Q.pop_front_val()); 2930b57cec5SDimitry Andric if (!U || U->getParent()) 2940b57cec5SDimitry Andric continue; 2950b57cec5SDimitry Andric if (!F(U)) 2960b57cec5SDimitry Andric continue; 2970b57cec5SDimitry Andric for (Value *Op : U->operands()) 2980b57cec5SDimitry Andric Q.push_back(Op); 2990b57cec5SDimitry Andric } 3000b57cec5SDimitry Andric } 3010b57cec5SDimitry Andric 3020b57cec5SDimitry Andric void Simplifier::Context::print(raw_ostream &OS, const Value *V) const { 3030b57cec5SDimitry Andric const auto *U = dyn_cast<const Instruction>(V); 3040b57cec5SDimitry Andric if (!U) { 3050b57cec5SDimitry Andric OS << V << '(' << *V << ')'; 3060b57cec5SDimitry Andric return; 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric 3090b57cec5SDimitry Andric if (U->getParent()) { 3100b57cec5SDimitry Andric OS << U << '('; 3110b57cec5SDimitry Andric U->printAsOperand(OS, true); 3120b57cec5SDimitry Andric OS << ')'; 3130b57cec5SDimitry Andric return; 3140b57cec5SDimitry Andric } 3150b57cec5SDimitry Andric 3160b57cec5SDimitry Andric unsigned N = U->getNumOperands(); 3170b57cec5SDimitry Andric if (N != 0) 3180b57cec5SDimitry Andric OS << U << '('; 3190b57cec5SDimitry Andric OS << U->getOpcodeName(); 3200b57cec5SDimitry Andric for (const Value *Op : U->operands()) { 3210b57cec5SDimitry Andric OS << ' '; 3220b57cec5SDimitry Andric print(OS, Op); 3230b57cec5SDimitry Andric } 3240b57cec5SDimitry Andric if (N != 0) 3250b57cec5SDimitry Andric OS << ')'; 3260b57cec5SDimitry Andric } 3270b57cec5SDimitry Andric 3280b57cec5SDimitry Andric void Simplifier::Context::initialize(Instruction *Exp) { 3290b57cec5SDimitry Andric // Perform a deep clone of the expression, set Root to the root 3300b57cec5SDimitry Andric // of the clone, and build a map from the cloned values to the 3310b57cec5SDimitry Andric // original ones. 3320b57cec5SDimitry Andric ValueMapType M; 3330b57cec5SDimitry Andric BasicBlock *Block = Exp->getParent(); 3340b57cec5SDimitry Andric WorkListType Q; 3350b57cec5SDimitry Andric Q.push_back(Exp); 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric while (!Q.empty()) { 3380b57cec5SDimitry Andric Value *V = Q.pop_front_val(); 33906c3fb27SDimitry Andric if (M.contains(V)) 3400b57cec5SDimitry Andric continue; 3410b57cec5SDimitry Andric if (Instruction *U = dyn_cast<Instruction>(V)) { 3420b57cec5SDimitry Andric if (isa<PHINode>(U) || U->getParent() != Block) 3430b57cec5SDimitry Andric continue; 3440b57cec5SDimitry Andric for (Value *Op : U->operands()) 3450b57cec5SDimitry Andric Q.push_back(Op); 3460b57cec5SDimitry Andric M.insert({U, U->clone()}); 3470b57cec5SDimitry Andric } 3480b57cec5SDimitry Andric } 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric for (std::pair<Value*,Value*> P : M) { 3510b57cec5SDimitry Andric Instruction *U = cast<Instruction>(P.second); 3520b57cec5SDimitry Andric for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) { 3530b57cec5SDimitry Andric auto F = M.find(U->getOperand(i)); 3540b57cec5SDimitry Andric if (F != M.end()) 3550b57cec5SDimitry Andric U->setOperand(i, F->second); 3560b57cec5SDimitry Andric } 3570b57cec5SDimitry Andric } 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric auto R = M.find(Exp); 3600b57cec5SDimitry Andric assert(R != M.end()); 3610b57cec5SDimitry Andric Root = R->second; 3620b57cec5SDimitry Andric 3630b57cec5SDimitry Andric record(Root); 3640b57cec5SDimitry Andric use(Root); 3650b57cec5SDimitry Andric } 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric void Simplifier::Context::record(Value *V) { 3680b57cec5SDimitry Andric auto Record = [this](Instruction *U) -> bool { 3690b57cec5SDimitry Andric Clones.insert(U); 3700b57cec5SDimitry Andric return true; 3710b57cec5SDimitry Andric }; 3720b57cec5SDimitry Andric traverse(V, Record); 3730b57cec5SDimitry Andric } 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric void Simplifier::Context::use(Value *V) { 3760b57cec5SDimitry Andric auto Use = [this](Instruction *U) -> bool { 3770b57cec5SDimitry Andric Used.insert(U); 3780b57cec5SDimitry Andric return true; 3790b57cec5SDimitry Andric }; 3800b57cec5SDimitry Andric traverse(V, Use); 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric void Simplifier::Context::unuse(Value *V) { 3840b57cec5SDimitry Andric if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != nullptr) 3850b57cec5SDimitry Andric return; 3860b57cec5SDimitry Andric 3870b57cec5SDimitry Andric auto Unuse = [this](Instruction *U) -> bool { 3880b57cec5SDimitry Andric if (!U->use_empty()) 3890b57cec5SDimitry Andric return false; 3900b57cec5SDimitry Andric Used.erase(U); 3910b57cec5SDimitry Andric return true; 3920b57cec5SDimitry Andric }; 3930b57cec5SDimitry Andric traverse(V, Unuse); 3940b57cec5SDimitry Andric } 3950b57cec5SDimitry Andric 3960b57cec5SDimitry Andric Value *Simplifier::Context::subst(Value *Tree, Value *OldV, Value *NewV) { 3970b57cec5SDimitry Andric if (Tree == OldV) 3980b57cec5SDimitry Andric return NewV; 3990b57cec5SDimitry Andric if (OldV == NewV) 4000b57cec5SDimitry Andric return Tree; 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric WorkListType Q; 4030b57cec5SDimitry Andric Q.push_back(Tree); 4040b57cec5SDimitry Andric while (!Q.empty()) { 4050b57cec5SDimitry Andric Instruction *U = dyn_cast<Instruction>(Q.pop_front_val()); 4060b57cec5SDimitry Andric // If U is not an instruction, or it's not a clone, skip it. 4070b57cec5SDimitry Andric if (!U || U->getParent()) 4080b57cec5SDimitry Andric continue; 4090b57cec5SDimitry Andric for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) { 4100b57cec5SDimitry Andric Value *Op = U->getOperand(i); 4110b57cec5SDimitry Andric if (Op == OldV) { 4120b57cec5SDimitry Andric U->setOperand(i, NewV); 4130b57cec5SDimitry Andric unuse(OldV); 4140b57cec5SDimitry Andric } else { 4150b57cec5SDimitry Andric Q.push_back(Op); 4160b57cec5SDimitry Andric } 4170b57cec5SDimitry Andric } 4180b57cec5SDimitry Andric } 4190b57cec5SDimitry Andric return Tree; 4200b57cec5SDimitry Andric } 4210b57cec5SDimitry Andric 4220b57cec5SDimitry Andric void Simplifier::Context::replace(Value *OldV, Value *NewV) { 4230b57cec5SDimitry Andric if (Root == OldV) { 4240b57cec5SDimitry Andric Root = NewV; 4250b57cec5SDimitry Andric use(Root); 4260b57cec5SDimitry Andric return; 4270b57cec5SDimitry Andric } 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric // NewV may be a complex tree that has just been created by one of the 4300b57cec5SDimitry Andric // transformation rules. We need to make sure that it is commoned with 4310b57cec5SDimitry Andric // the existing Root to the maximum extent possible. 4320b57cec5SDimitry Andric // Identify all subtrees of NewV (including NewV itself) that have 4330b57cec5SDimitry Andric // equivalent counterparts in Root, and replace those subtrees with 4340b57cec5SDimitry Andric // these counterparts. 4350b57cec5SDimitry Andric WorkListType Q; 4360b57cec5SDimitry Andric Q.push_back(NewV); 4370b57cec5SDimitry Andric while (!Q.empty()) { 4380b57cec5SDimitry Andric Value *V = Q.pop_front_val(); 4390b57cec5SDimitry Andric Instruction *U = dyn_cast<Instruction>(V); 4400b57cec5SDimitry Andric if (!U || U->getParent()) 4410b57cec5SDimitry Andric continue; 4420b57cec5SDimitry Andric if (Value *DupV = find(Root, V)) { 4430b57cec5SDimitry Andric if (DupV != V) 4440b57cec5SDimitry Andric NewV = subst(NewV, V, DupV); 4450b57cec5SDimitry Andric } else { 4460b57cec5SDimitry Andric for (Value *Op : U->operands()) 4470b57cec5SDimitry Andric Q.push_back(Op); 4480b57cec5SDimitry Andric } 4490b57cec5SDimitry Andric } 4500b57cec5SDimitry Andric 4510b57cec5SDimitry Andric // Now, simply replace OldV with NewV in Root. 4520b57cec5SDimitry Andric Root = subst(Root, OldV, NewV); 4530b57cec5SDimitry Andric use(Root); 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric void Simplifier::Context::cleanup() { 4570b57cec5SDimitry Andric for (Value *V : Clones) { 4580b57cec5SDimitry Andric Instruction *U = cast<Instruction>(V); 4590b57cec5SDimitry Andric if (!U->getParent()) 4600b57cec5SDimitry Andric U->dropAllReferences(); 4610b57cec5SDimitry Andric } 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric for (Value *V : Clones) { 4640b57cec5SDimitry Andric Instruction *U = cast<Instruction>(V); 4650b57cec5SDimitry Andric if (!U->getParent()) 4660b57cec5SDimitry Andric U->deleteValue(); 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric } 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric bool Simplifier::Context::equal(const Instruction *I, 4710b57cec5SDimitry Andric const Instruction *J) const { 4720b57cec5SDimitry Andric if (I == J) 4730b57cec5SDimitry Andric return true; 4740b57cec5SDimitry Andric if (!I->isSameOperationAs(J)) 4750b57cec5SDimitry Andric return false; 4760b57cec5SDimitry Andric if (isa<PHINode>(I)) 4770b57cec5SDimitry Andric return I->isIdenticalTo(J); 4780b57cec5SDimitry Andric 4790b57cec5SDimitry Andric for (unsigned i = 0, n = I->getNumOperands(); i != n; ++i) { 4800b57cec5SDimitry Andric Value *OpI = I->getOperand(i), *OpJ = J->getOperand(i); 4810b57cec5SDimitry Andric if (OpI == OpJ) 4820b57cec5SDimitry Andric continue; 4830b57cec5SDimitry Andric auto *InI = dyn_cast<const Instruction>(OpI); 4840b57cec5SDimitry Andric auto *InJ = dyn_cast<const Instruction>(OpJ); 4850b57cec5SDimitry Andric if (InI && InJ) { 4860b57cec5SDimitry Andric if (!equal(InI, InJ)) 4870b57cec5SDimitry Andric return false; 4880b57cec5SDimitry Andric } else if (InI != InJ || !InI) 4890b57cec5SDimitry Andric return false; 4900b57cec5SDimitry Andric } 4910b57cec5SDimitry Andric return true; 4920b57cec5SDimitry Andric } 4930b57cec5SDimitry Andric 4940b57cec5SDimitry Andric Value *Simplifier::Context::find(Value *Tree, Value *Sub) const { 4950b57cec5SDimitry Andric Instruction *SubI = dyn_cast<Instruction>(Sub); 4960b57cec5SDimitry Andric WorkListType Q; 4970b57cec5SDimitry Andric Q.push_back(Tree); 4980b57cec5SDimitry Andric 4990b57cec5SDimitry Andric while (!Q.empty()) { 5000b57cec5SDimitry Andric Value *V = Q.pop_front_val(); 5010b57cec5SDimitry Andric if (V == Sub) 5020b57cec5SDimitry Andric return V; 5030b57cec5SDimitry Andric Instruction *U = dyn_cast<Instruction>(V); 5040b57cec5SDimitry Andric if (!U || U->getParent()) 5050b57cec5SDimitry Andric continue; 5060b57cec5SDimitry Andric if (SubI && equal(SubI, U)) 5070b57cec5SDimitry Andric return U; 5080b57cec5SDimitry Andric assert(!isa<PHINode>(U)); 5090b57cec5SDimitry Andric for (Value *Op : U->operands()) 5100b57cec5SDimitry Andric Q.push_back(Op); 5110b57cec5SDimitry Andric } 5120b57cec5SDimitry Andric return nullptr; 5130b57cec5SDimitry Andric } 5140b57cec5SDimitry Andric 5150b57cec5SDimitry Andric void Simplifier::Context::link(Instruction *I, BasicBlock *B, 5160b57cec5SDimitry Andric BasicBlock::iterator At) { 5170b57cec5SDimitry Andric if (I->getParent()) 5180b57cec5SDimitry Andric return; 5190b57cec5SDimitry Andric 5200b57cec5SDimitry Andric for (Value *Op : I->operands()) { 5210b57cec5SDimitry Andric if (Instruction *OpI = dyn_cast<Instruction>(Op)) 5220b57cec5SDimitry Andric link(OpI, B, At); 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 525bdd1243dSDimitry Andric I->insertInto(B, At); 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric Value *Simplifier::Context::materialize(BasicBlock *B, 5290b57cec5SDimitry Andric BasicBlock::iterator At) { 5300b57cec5SDimitry Andric if (Instruction *RootI = dyn_cast<Instruction>(Root)) 5310b57cec5SDimitry Andric link(RootI, B, At); 5320b57cec5SDimitry Andric return Root; 5330b57cec5SDimitry Andric } 5340b57cec5SDimitry Andric 5350b57cec5SDimitry Andric Value *Simplifier::simplify(Context &C) { 5360b57cec5SDimitry Andric WorkListType Q; 5370b57cec5SDimitry Andric Q.push_back(C.Root); 5380b57cec5SDimitry Andric unsigned Count = 0; 5390b57cec5SDimitry Andric const unsigned Limit = SimplifyLimit; 5400b57cec5SDimitry Andric 5410b57cec5SDimitry Andric while (!Q.empty()) { 5420b57cec5SDimitry Andric if (Count++ >= Limit) 5430b57cec5SDimitry Andric break; 5440b57cec5SDimitry Andric Instruction *U = dyn_cast<Instruction>(Q.pop_front_val()); 5450b57cec5SDimitry Andric if (!U || U->getParent() || !C.Used.count(U)) 5460b57cec5SDimitry Andric continue; 5470b57cec5SDimitry Andric bool Changed = false; 5480b57cec5SDimitry Andric for (Rule &R : Rules) { 5490b57cec5SDimitry Andric Value *W = R.Fn(U, C.Ctx); 5500b57cec5SDimitry Andric if (!W) 5510b57cec5SDimitry Andric continue; 5520b57cec5SDimitry Andric Changed = true; 5530b57cec5SDimitry Andric C.record(W); 5540b57cec5SDimitry Andric C.replace(U, W); 5550b57cec5SDimitry Andric Q.push_back(C.Root); 5560b57cec5SDimitry Andric break; 5570b57cec5SDimitry Andric } 5580b57cec5SDimitry Andric if (!Changed) { 5590b57cec5SDimitry Andric for (Value *Op : U->operands()) 5600b57cec5SDimitry Andric Q.push_back(Op); 5610b57cec5SDimitry Andric } 5620b57cec5SDimitry Andric } 5630b57cec5SDimitry Andric return Count < Limit ? C.Root : nullptr; 5640b57cec5SDimitry Andric } 5650b57cec5SDimitry Andric 5660b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 5670b57cec5SDimitry Andric // 5680b57cec5SDimitry Andric // Implementation of PolynomialMultiplyRecognize 5690b57cec5SDimitry Andric // 5700b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric namespace { 5730b57cec5SDimitry Andric 5740b57cec5SDimitry Andric class PolynomialMultiplyRecognize { 5750b57cec5SDimitry Andric public: 5760b57cec5SDimitry Andric explicit PolynomialMultiplyRecognize(Loop *loop, const DataLayout &dl, 5770b57cec5SDimitry Andric const DominatorTree &dt, const TargetLibraryInfo &tli, 5780b57cec5SDimitry Andric ScalarEvolution &se) 5790b57cec5SDimitry Andric : CurLoop(loop), DL(dl), DT(dt), TLI(tli), SE(se) {} 5800b57cec5SDimitry Andric 5810b57cec5SDimitry Andric bool recognize(); 5820b57cec5SDimitry Andric 5830b57cec5SDimitry Andric private: 5840b57cec5SDimitry Andric using ValueSeq = SetVector<Value *>; 5850b57cec5SDimitry Andric 5860b57cec5SDimitry Andric IntegerType *getPmpyType() const { 5870b57cec5SDimitry Andric LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext(); 5880b57cec5SDimitry Andric return IntegerType::get(Ctx, 32); 5890b57cec5SDimitry Andric } 5900b57cec5SDimitry Andric 5910b57cec5SDimitry Andric bool isPromotableTo(Value *V, IntegerType *Ty); 5920b57cec5SDimitry Andric void promoteTo(Instruction *In, IntegerType *DestTy, BasicBlock *LoopB); 5930b57cec5SDimitry Andric bool promoteTypes(BasicBlock *LoopB, BasicBlock *ExitB); 5940b57cec5SDimitry Andric 5950b57cec5SDimitry Andric Value *getCountIV(BasicBlock *BB); 5960b57cec5SDimitry Andric bool findCycle(Value *Out, Value *In, ValueSeq &Cycle); 5970b57cec5SDimitry Andric void classifyCycle(Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early, 5980b57cec5SDimitry Andric ValueSeq &Late); 5990b57cec5SDimitry Andric bool classifyInst(Instruction *UseI, ValueSeq &Early, ValueSeq &Late); 6000b57cec5SDimitry Andric bool commutesWithShift(Instruction *I); 6010b57cec5SDimitry Andric bool highBitsAreZero(Value *V, unsigned IterCount); 6020b57cec5SDimitry Andric bool keepsHighBitsZero(Value *V, unsigned IterCount); 6030b57cec5SDimitry Andric bool isOperandShifted(Instruction *I, Value *Op); 6040b57cec5SDimitry Andric bool convertShiftsToLeft(BasicBlock *LoopB, BasicBlock *ExitB, 6050b57cec5SDimitry Andric unsigned IterCount); 6060b57cec5SDimitry Andric void cleanupLoopBody(BasicBlock *LoopB); 6070b57cec5SDimitry Andric 6080b57cec5SDimitry Andric struct ParsedValues { 6090b57cec5SDimitry Andric ParsedValues() = default; 6100b57cec5SDimitry Andric 6110b57cec5SDimitry Andric Value *M = nullptr; 6120b57cec5SDimitry Andric Value *P = nullptr; 6130b57cec5SDimitry Andric Value *Q = nullptr; 6140b57cec5SDimitry Andric Value *R = nullptr; 6150b57cec5SDimitry Andric Value *X = nullptr; 6160b57cec5SDimitry Andric Instruction *Res = nullptr; 6170b57cec5SDimitry Andric unsigned IterCount = 0; 6180b57cec5SDimitry Andric bool Left = false; 6190b57cec5SDimitry Andric bool Inv = false; 6200b57cec5SDimitry Andric }; 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric bool matchLeftShift(SelectInst *SelI, Value *CIV, ParsedValues &PV); 6230b57cec5SDimitry Andric bool matchRightShift(SelectInst *SelI, ParsedValues &PV); 6240b57cec5SDimitry Andric bool scanSelect(SelectInst *SI, BasicBlock *LoopB, BasicBlock *PrehB, 6250b57cec5SDimitry Andric Value *CIV, ParsedValues &PV, bool PreScan); 6260b57cec5SDimitry Andric unsigned getInverseMxN(unsigned QP); 6270b57cec5SDimitry Andric Value *generate(BasicBlock::iterator At, ParsedValues &PV); 6280b57cec5SDimitry Andric 6290b57cec5SDimitry Andric void setupPreSimplifier(Simplifier &S); 6300b57cec5SDimitry Andric void setupPostSimplifier(Simplifier &S); 6310b57cec5SDimitry Andric 6320b57cec5SDimitry Andric Loop *CurLoop; 6330b57cec5SDimitry Andric const DataLayout &DL; 6340b57cec5SDimitry Andric const DominatorTree &DT; 6350b57cec5SDimitry Andric const TargetLibraryInfo &TLI; 6360b57cec5SDimitry Andric ScalarEvolution &SE; 6370b57cec5SDimitry Andric }; 6380b57cec5SDimitry Andric 6390b57cec5SDimitry Andric } // end anonymous namespace 6400b57cec5SDimitry Andric 6410b57cec5SDimitry Andric Value *PolynomialMultiplyRecognize::getCountIV(BasicBlock *BB) { 6420b57cec5SDimitry Andric pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 6430b57cec5SDimitry Andric if (std::distance(PI, PE) != 2) 6440b57cec5SDimitry Andric return nullptr; 6450b57cec5SDimitry Andric BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI; 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) { 6480b57cec5SDimitry Andric auto *PN = cast<PHINode>(I); 6490b57cec5SDimitry Andric Value *InitV = PN->getIncomingValueForBlock(PB); 6500b57cec5SDimitry Andric if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->isZero()) 6510b57cec5SDimitry Andric continue; 6520b57cec5SDimitry Andric Value *IterV = PN->getIncomingValueForBlock(BB); 6530b57cec5SDimitry Andric auto *BO = dyn_cast<BinaryOperator>(IterV); 6548bcb0991SDimitry Andric if (!BO) 6558bcb0991SDimitry Andric continue; 6560b57cec5SDimitry Andric if (BO->getOpcode() != Instruction::Add) 6570b57cec5SDimitry Andric continue; 6580b57cec5SDimitry Andric Value *IncV = nullptr; 6590b57cec5SDimitry Andric if (BO->getOperand(0) == PN) 6600b57cec5SDimitry Andric IncV = BO->getOperand(1); 6610b57cec5SDimitry Andric else if (BO->getOperand(1) == PN) 6620b57cec5SDimitry Andric IncV = BO->getOperand(0); 6630b57cec5SDimitry Andric if (IncV == nullptr) 6640b57cec5SDimitry Andric continue; 6650b57cec5SDimitry Andric 6660b57cec5SDimitry Andric if (auto *T = dyn_cast<ConstantInt>(IncV)) 66706c3fb27SDimitry Andric if (T->isOne()) 6680b57cec5SDimitry Andric return PN; 6690b57cec5SDimitry Andric } 6700b57cec5SDimitry Andric return nullptr; 6710b57cec5SDimitry Andric } 6720b57cec5SDimitry Andric 6730b57cec5SDimitry Andric static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB) { 6740b57cec5SDimitry Andric for (auto UI = I->user_begin(), UE = I->user_end(); UI != UE;) { 6750b57cec5SDimitry Andric Use &TheUse = UI.getUse(); 6760b57cec5SDimitry Andric ++UI; 6770b57cec5SDimitry Andric if (auto *II = dyn_cast<Instruction>(TheUse.getUser())) 6780b57cec5SDimitry Andric if (BB == II->getParent()) 6790b57cec5SDimitry Andric II->replaceUsesOfWith(I, J); 6800b57cec5SDimitry Andric } 6810b57cec5SDimitry Andric } 6820b57cec5SDimitry Andric 6830b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::matchLeftShift(SelectInst *SelI, 6840b57cec5SDimitry Andric Value *CIV, ParsedValues &PV) { 6850b57cec5SDimitry Andric // Match the following: 6860b57cec5SDimitry Andric // select (X & (1 << i)) != 0 ? R ^ (Q << i) : R 6870b57cec5SDimitry Andric // select (X & (1 << i)) == 0 ? R : R ^ (Q << i) 6880b57cec5SDimitry Andric // The condition may also check for equality with the masked value, i.e 6890b57cec5SDimitry Andric // select (X & (1 << i)) == (1 << i) ? R ^ (Q << i) : R 6900b57cec5SDimitry Andric // select (X & (1 << i)) != (1 << i) ? R : R ^ (Q << i); 6910b57cec5SDimitry Andric 6920b57cec5SDimitry Andric Value *CondV = SelI->getCondition(); 6930b57cec5SDimitry Andric Value *TrueV = SelI->getTrueValue(); 6940b57cec5SDimitry Andric Value *FalseV = SelI->getFalseValue(); 6950b57cec5SDimitry Andric 6960b57cec5SDimitry Andric using namespace PatternMatch; 6970b57cec5SDimitry Andric 6980b57cec5SDimitry Andric CmpInst::Predicate P; 6990b57cec5SDimitry Andric Value *A = nullptr, *B = nullptr, *C = nullptr; 7000b57cec5SDimitry Andric 7010b57cec5SDimitry Andric if (!match(CondV, m_ICmp(P, m_And(m_Value(A), m_Value(B)), m_Value(C))) && 7020b57cec5SDimitry Andric !match(CondV, m_ICmp(P, m_Value(C), m_And(m_Value(A), m_Value(B))))) 7030b57cec5SDimitry Andric return false; 7040b57cec5SDimitry Andric if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE) 7050b57cec5SDimitry Andric return false; 7060b57cec5SDimitry Andric // Matched: select (A & B) == C ? ... : ... 7070b57cec5SDimitry Andric // select (A & B) != C ? ... : ... 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric Value *X = nullptr, *Sh1 = nullptr; 7100b57cec5SDimitry Andric // Check (A & B) for (X & (1 << i)): 7110b57cec5SDimitry Andric if (match(A, m_Shl(m_One(), m_Specific(CIV)))) { 7120b57cec5SDimitry Andric Sh1 = A; 7130b57cec5SDimitry Andric X = B; 7140b57cec5SDimitry Andric } else if (match(B, m_Shl(m_One(), m_Specific(CIV)))) { 7150b57cec5SDimitry Andric Sh1 = B; 7160b57cec5SDimitry Andric X = A; 7170b57cec5SDimitry Andric } else { 7180b57cec5SDimitry Andric // TODO: Could also check for an induction variable containing single 7190b57cec5SDimitry Andric // bit shifted left by 1 in each iteration. 7200b57cec5SDimitry Andric return false; 7210b57cec5SDimitry Andric } 7220b57cec5SDimitry Andric 7230b57cec5SDimitry Andric bool TrueIfZero; 7240b57cec5SDimitry Andric 7250b57cec5SDimitry Andric // Check C against the possible values for comparison: 0 and (1 << i): 7260b57cec5SDimitry Andric if (match(C, m_Zero())) 7270b57cec5SDimitry Andric TrueIfZero = (P == CmpInst::ICMP_EQ); 7280b57cec5SDimitry Andric else if (C == Sh1) 7290b57cec5SDimitry Andric TrueIfZero = (P == CmpInst::ICMP_NE); 7300b57cec5SDimitry Andric else 7310b57cec5SDimitry Andric return false; 7320b57cec5SDimitry Andric 7330b57cec5SDimitry Andric // So far, matched: 7340b57cec5SDimitry Andric // select (X & (1 << i)) ? ... : ... 7350b57cec5SDimitry Andric // including variations of the check against zero/non-zero value. 7360b57cec5SDimitry Andric 7370b57cec5SDimitry Andric Value *ShouldSameV = nullptr, *ShouldXoredV = nullptr; 7380b57cec5SDimitry Andric if (TrueIfZero) { 7390b57cec5SDimitry Andric ShouldSameV = TrueV; 7400b57cec5SDimitry Andric ShouldXoredV = FalseV; 7410b57cec5SDimitry Andric } else { 7420b57cec5SDimitry Andric ShouldSameV = FalseV; 7430b57cec5SDimitry Andric ShouldXoredV = TrueV; 7440b57cec5SDimitry Andric } 7450b57cec5SDimitry Andric 7460b57cec5SDimitry Andric Value *Q = nullptr, *R = nullptr, *Y = nullptr, *Z = nullptr; 7470b57cec5SDimitry Andric Value *T = nullptr; 7480b57cec5SDimitry Andric if (match(ShouldXoredV, m_Xor(m_Value(Y), m_Value(Z)))) { 7490b57cec5SDimitry Andric // Matched: select +++ ? ... : Y ^ Z 7500b57cec5SDimitry Andric // select +++ ? Y ^ Z : ... 7510b57cec5SDimitry Andric // where +++ denotes previously checked matches. 7520b57cec5SDimitry Andric if (ShouldSameV == Y) 7530b57cec5SDimitry Andric T = Z; 7540b57cec5SDimitry Andric else if (ShouldSameV == Z) 7550b57cec5SDimitry Andric T = Y; 7560b57cec5SDimitry Andric else 7570b57cec5SDimitry Andric return false; 7580b57cec5SDimitry Andric R = ShouldSameV; 7590b57cec5SDimitry Andric // Matched: select +++ ? R : R ^ T 7600b57cec5SDimitry Andric // select +++ ? R ^ T : R 7610b57cec5SDimitry Andric // depending on TrueIfZero. 7620b57cec5SDimitry Andric 7630b57cec5SDimitry Andric } else if (match(ShouldSameV, m_Zero())) { 7640b57cec5SDimitry Andric // Matched: select +++ ? 0 : ... 7650b57cec5SDimitry Andric // select +++ ? ... : 0 7660b57cec5SDimitry Andric if (!SelI->hasOneUse()) 7670b57cec5SDimitry Andric return false; 7680b57cec5SDimitry Andric T = ShouldXoredV; 7690b57cec5SDimitry Andric // Matched: select +++ ? 0 : T 7700b57cec5SDimitry Andric // select +++ ? T : 0 7710b57cec5SDimitry Andric 7720b57cec5SDimitry Andric Value *U = *SelI->user_begin(); 7730b57cec5SDimitry Andric if (!match(U, m_Xor(m_Specific(SelI), m_Value(R))) && 7740b57cec5SDimitry Andric !match(U, m_Xor(m_Value(R), m_Specific(SelI)))) 7750b57cec5SDimitry Andric return false; 7760b57cec5SDimitry Andric // Matched: xor (select +++ ? 0 : T), R 7770b57cec5SDimitry Andric // xor (select +++ ? T : 0), R 7780b57cec5SDimitry Andric } else 7790b57cec5SDimitry Andric return false; 7800b57cec5SDimitry Andric 7810b57cec5SDimitry Andric // The xor input value T is isolated into its own match so that it could 7820b57cec5SDimitry Andric // be checked against an induction variable containing a shifted bit 7830b57cec5SDimitry Andric // (todo). 7840b57cec5SDimitry Andric // For now, check against (Q << i). 7850b57cec5SDimitry Andric if (!match(T, m_Shl(m_Value(Q), m_Specific(CIV))) && 7860b57cec5SDimitry Andric !match(T, m_Shl(m_ZExt(m_Value(Q)), m_ZExt(m_Specific(CIV))))) 7870b57cec5SDimitry Andric return false; 7880b57cec5SDimitry Andric // Matched: select +++ ? R : R ^ (Q << i) 7890b57cec5SDimitry Andric // select +++ ? R ^ (Q << i) : R 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric PV.X = X; 7920b57cec5SDimitry Andric PV.Q = Q; 7930b57cec5SDimitry Andric PV.R = R; 7940b57cec5SDimitry Andric PV.Left = true; 7950b57cec5SDimitry Andric return true; 7960b57cec5SDimitry Andric } 7970b57cec5SDimitry Andric 7980b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::matchRightShift(SelectInst *SelI, 7990b57cec5SDimitry Andric ParsedValues &PV) { 8000b57cec5SDimitry Andric // Match the following: 8010b57cec5SDimitry Andric // select (X & 1) != 0 ? (R >> 1) ^ Q : (R >> 1) 8020b57cec5SDimitry Andric // select (X & 1) == 0 ? (R >> 1) : (R >> 1) ^ Q 8030b57cec5SDimitry Andric // The condition may also check for equality with the masked value, i.e 8040b57cec5SDimitry Andric // select (X & 1) == 1 ? (R >> 1) ^ Q : (R >> 1) 8050b57cec5SDimitry Andric // select (X & 1) != 1 ? (R >> 1) : (R >> 1) ^ Q 8060b57cec5SDimitry Andric 8070b57cec5SDimitry Andric Value *CondV = SelI->getCondition(); 8080b57cec5SDimitry Andric Value *TrueV = SelI->getTrueValue(); 8090b57cec5SDimitry Andric Value *FalseV = SelI->getFalseValue(); 8100b57cec5SDimitry Andric 8110b57cec5SDimitry Andric using namespace PatternMatch; 8120b57cec5SDimitry Andric 8130b57cec5SDimitry Andric Value *C = nullptr; 8140b57cec5SDimitry Andric CmpInst::Predicate P; 8150b57cec5SDimitry Andric bool TrueIfZero; 8160b57cec5SDimitry Andric 8170b57cec5SDimitry Andric if (match(CondV, m_ICmp(P, m_Value(C), m_Zero())) || 8180b57cec5SDimitry Andric match(CondV, m_ICmp(P, m_Zero(), m_Value(C)))) { 8190b57cec5SDimitry Andric if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE) 8200b57cec5SDimitry Andric return false; 8210b57cec5SDimitry Andric // Matched: select C == 0 ? ... : ... 8220b57cec5SDimitry Andric // select C != 0 ? ... : ... 8230b57cec5SDimitry Andric TrueIfZero = (P == CmpInst::ICMP_EQ); 8240b57cec5SDimitry Andric } else if (match(CondV, m_ICmp(P, m_Value(C), m_One())) || 8250b57cec5SDimitry Andric match(CondV, m_ICmp(P, m_One(), m_Value(C)))) { 8260b57cec5SDimitry Andric if (P != CmpInst::ICMP_EQ && P != CmpInst::ICMP_NE) 8270b57cec5SDimitry Andric return false; 8280b57cec5SDimitry Andric // Matched: select C == 1 ? ... : ... 8290b57cec5SDimitry Andric // select C != 1 ? ... : ... 8300b57cec5SDimitry Andric TrueIfZero = (P == CmpInst::ICMP_NE); 8310b57cec5SDimitry Andric } else 8320b57cec5SDimitry Andric return false; 8330b57cec5SDimitry Andric 8340b57cec5SDimitry Andric Value *X = nullptr; 8350b57cec5SDimitry Andric if (!match(C, m_And(m_Value(X), m_One())) && 8360b57cec5SDimitry Andric !match(C, m_And(m_One(), m_Value(X)))) 8370b57cec5SDimitry Andric return false; 8380b57cec5SDimitry Andric // Matched: select (X & 1) == +++ ? ... : ... 8390b57cec5SDimitry Andric // select (X & 1) != +++ ? ... : ... 8400b57cec5SDimitry Andric 8410b57cec5SDimitry Andric Value *R = nullptr, *Q = nullptr; 8420b57cec5SDimitry Andric if (TrueIfZero) { 8430b57cec5SDimitry Andric // The select's condition is true if the tested bit is 0. 8440b57cec5SDimitry Andric // TrueV must be the shift, FalseV must be the xor. 8450b57cec5SDimitry Andric if (!match(TrueV, m_LShr(m_Value(R), m_One()))) 8460b57cec5SDimitry Andric return false; 8470b57cec5SDimitry Andric // Matched: select +++ ? (R >> 1) : ... 8480b57cec5SDimitry Andric if (!match(FalseV, m_Xor(m_Specific(TrueV), m_Value(Q))) && 8490b57cec5SDimitry Andric !match(FalseV, m_Xor(m_Value(Q), m_Specific(TrueV)))) 8500b57cec5SDimitry Andric return false; 8510b57cec5SDimitry Andric // Matched: select +++ ? (R >> 1) : (R >> 1) ^ Q 8520b57cec5SDimitry Andric // with commuting ^. 8530b57cec5SDimitry Andric } else { 8540b57cec5SDimitry Andric // The select's condition is true if the tested bit is 1. 8550b57cec5SDimitry Andric // TrueV must be the xor, FalseV must be the shift. 8560b57cec5SDimitry Andric if (!match(FalseV, m_LShr(m_Value(R), m_One()))) 8570b57cec5SDimitry Andric return false; 8580b57cec5SDimitry Andric // Matched: select +++ ? ... : (R >> 1) 8590b57cec5SDimitry Andric if (!match(TrueV, m_Xor(m_Specific(FalseV), m_Value(Q))) && 8600b57cec5SDimitry Andric !match(TrueV, m_Xor(m_Value(Q), m_Specific(FalseV)))) 8610b57cec5SDimitry Andric return false; 8620b57cec5SDimitry Andric // Matched: select +++ ? (R >> 1) ^ Q : (R >> 1) 8630b57cec5SDimitry Andric // with commuting ^. 8640b57cec5SDimitry Andric } 8650b57cec5SDimitry Andric 8660b57cec5SDimitry Andric PV.X = X; 8670b57cec5SDimitry Andric PV.Q = Q; 8680b57cec5SDimitry Andric PV.R = R; 8690b57cec5SDimitry Andric PV.Left = false; 8700b57cec5SDimitry Andric return true; 8710b57cec5SDimitry Andric } 8720b57cec5SDimitry Andric 8730b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::scanSelect(SelectInst *SelI, 8740b57cec5SDimitry Andric BasicBlock *LoopB, BasicBlock *PrehB, Value *CIV, ParsedValues &PV, 8750b57cec5SDimitry Andric bool PreScan) { 8760b57cec5SDimitry Andric using namespace PatternMatch; 8770b57cec5SDimitry Andric 8780b57cec5SDimitry Andric // The basic pattern for R = P.Q is: 8790b57cec5SDimitry Andric // for i = 0..31 8800b57cec5SDimitry Andric // R = phi (0, R') 8810b57cec5SDimitry Andric // if (P & (1 << i)) ; test-bit(P, i) 8820b57cec5SDimitry Andric // R' = R ^ (Q << i) 8830b57cec5SDimitry Andric // 8840b57cec5SDimitry Andric // Similarly, the basic pattern for R = (P/Q).Q - P 8850b57cec5SDimitry Andric // for i = 0..31 8860b57cec5SDimitry Andric // R = phi(P, R') 8870b57cec5SDimitry Andric // if (R & (1 << i)) 8880b57cec5SDimitry Andric // R' = R ^ (Q << i) 8890b57cec5SDimitry Andric 8900b57cec5SDimitry Andric // There exist idioms, where instead of Q being shifted left, P is shifted 8910b57cec5SDimitry Andric // right. This produces a result that is shifted right by 32 bits (the 8920b57cec5SDimitry Andric // non-shifted result is 64-bit). 8930b57cec5SDimitry Andric // 8940b57cec5SDimitry Andric // For R = P.Q, this would be: 8950b57cec5SDimitry Andric // for i = 0..31 8960b57cec5SDimitry Andric // R = phi (0, R') 8970b57cec5SDimitry Andric // if ((P >> i) & 1) 8980b57cec5SDimitry Andric // R' = (R >> 1) ^ Q ; R is cycled through the loop, so it must 8990b57cec5SDimitry Andric // else ; be shifted by 1, not i. 9000b57cec5SDimitry Andric // R' = R >> 1 9010b57cec5SDimitry Andric // 9020b57cec5SDimitry Andric // And for the inverse: 9030b57cec5SDimitry Andric // for i = 0..31 9040b57cec5SDimitry Andric // R = phi (P, R') 9050b57cec5SDimitry Andric // if (R & 1) 9060b57cec5SDimitry Andric // R' = (R >> 1) ^ Q 9070b57cec5SDimitry Andric // else 9080b57cec5SDimitry Andric // R' = R >> 1 9090b57cec5SDimitry Andric 9100b57cec5SDimitry Andric // The left-shifting idioms share the same pattern: 9110b57cec5SDimitry Andric // select (X & (1 << i)) ? R ^ (Q << i) : R 9120b57cec5SDimitry Andric // Similarly for right-shifting idioms: 9130b57cec5SDimitry Andric // select (X & 1) ? (R >> 1) ^ Q 9140b57cec5SDimitry Andric 9150b57cec5SDimitry Andric if (matchLeftShift(SelI, CIV, PV)) { 9160b57cec5SDimitry Andric // If this is a pre-scan, getting this far is sufficient. 9170b57cec5SDimitry Andric if (PreScan) 9180b57cec5SDimitry Andric return true; 9190b57cec5SDimitry Andric 9200b57cec5SDimitry Andric // Need to make sure that the SelI goes back into R. 9210b57cec5SDimitry Andric auto *RPhi = dyn_cast<PHINode>(PV.R); 9220b57cec5SDimitry Andric if (!RPhi) 9230b57cec5SDimitry Andric return false; 9240b57cec5SDimitry Andric if (SelI != RPhi->getIncomingValueForBlock(LoopB)) 9250b57cec5SDimitry Andric return false; 9260b57cec5SDimitry Andric PV.Res = SelI; 9270b57cec5SDimitry Andric 9280b57cec5SDimitry Andric // If X is loop invariant, it must be the input polynomial, and the 9290b57cec5SDimitry Andric // idiom is the basic polynomial multiply. 9300b57cec5SDimitry Andric if (CurLoop->isLoopInvariant(PV.X)) { 9310b57cec5SDimitry Andric PV.P = PV.X; 9320b57cec5SDimitry Andric PV.Inv = false; 9330b57cec5SDimitry Andric } else { 9340b57cec5SDimitry Andric // X is not loop invariant. If X == R, this is the inverse pmpy. 9350b57cec5SDimitry Andric // Otherwise, check for an xor with an invariant value. If the 9360b57cec5SDimitry Andric // variable argument to the xor is R, then this is still a valid 9370b57cec5SDimitry Andric // inverse pmpy. 9380b57cec5SDimitry Andric PV.Inv = true; 9390b57cec5SDimitry Andric if (PV.X != PV.R) { 9400b57cec5SDimitry Andric Value *Var = nullptr, *Inv = nullptr, *X1 = nullptr, *X2 = nullptr; 9410b57cec5SDimitry Andric if (!match(PV.X, m_Xor(m_Value(X1), m_Value(X2)))) 9420b57cec5SDimitry Andric return false; 9430b57cec5SDimitry Andric auto *I1 = dyn_cast<Instruction>(X1); 9440b57cec5SDimitry Andric auto *I2 = dyn_cast<Instruction>(X2); 9450b57cec5SDimitry Andric if (!I1 || I1->getParent() != LoopB) { 9460b57cec5SDimitry Andric Var = X2; 9470b57cec5SDimitry Andric Inv = X1; 9480b57cec5SDimitry Andric } else if (!I2 || I2->getParent() != LoopB) { 9490b57cec5SDimitry Andric Var = X1; 9500b57cec5SDimitry Andric Inv = X2; 9510b57cec5SDimitry Andric } else 9520b57cec5SDimitry Andric return false; 9530b57cec5SDimitry Andric if (Var != PV.R) 9540b57cec5SDimitry Andric return false; 9550b57cec5SDimitry Andric PV.M = Inv; 9560b57cec5SDimitry Andric } 9570b57cec5SDimitry Andric // The input polynomial P still needs to be determined. It will be 9580b57cec5SDimitry Andric // the entry value of R. 9590b57cec5SDimitry Andric Value *EntryP = RPhi->getIncomingValueForBlock(PrehB); 9600b57cec5SDimitry Andric PV.P = EntryP; 9610b57cec5SDimitry Andric } 9620b57cec5SDimitry Andric 9630b57cec5SDimitry Andric return true; 9640b57cec5SDimitry Andric } 9650b57cec5SDimitry Andric 9660b57cec5SDimitry Andric if (matchRightShift(SelI, PV)) { 9670b57cec5SDimitry Andric // If this is an inverse pattern, the Q polynomial must be known at 9680b57cec5SDimitry Andric // compile time. 9690b57cec5SDimitry Andric if (PV.Inv && !isa<ConstantInt>(PV.Q)) 9700b57cec5SDimitry Andric return false; 9710b57cec5SDimitry Andric if (PreScan) 9720b57cec5SDimitry Andric return true; 9730b57cec5SDimitry Andric // There is no exact matching of right-shift pmpy. 9740b57cec5SDimitry Andric return false; 9750b57cec5SDimitry Andric } 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric return false; 9780b57cec5SDimitry Andric } 9790b57cec5SDimitry Andric 9800b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::isPromotableTo(Value *Val, 9810b57cec5SDimitry Andric IntegerType *DestTy) { 9820b57cec5SDimitry Andric IntegerType *T = dyn_cast<IntegerType>(Val->getType()); 9830b57cec5SDimitry Andric if (!T || T->getBitWidth() > DestTy->getBitWidth()) 9840b57cec5SDimitry Andric return false; 9850b57cec5SDimitry Andric if (T->getBitWidth() == DestTy->getBitWidth()) 9860b57cec5SDimitry Andric return true; 9870b57cec5SDimitry Andric // Non-instructions are promotable. The reason why an instruction may not 9880b57cec5SDimitry Andric // be promotable is that it may produce a different result if its operands 9890b57cec5SDimitry Andric // and the result are promoted, for example, it may produce more non-zero 9900b57cec5SDimitry Andric // bits. While it would still be possible to represent the proper result 9910b57cec5SDimitry Andric // in a wider type, it may require adding additional instructions (which 9920b57cec5SDimitry Andric // we don't want to do). 9930b57cec5SDimitry Andric Instruction *In = dyn_cast<Instruction>(Val); 9940b57cec5SDimitry Andric if (!In) 9950b57cec5SDimitry Andric return true; 9960b57cec5SDimitry Andric // The bitwidth of the source type is smaller than the destination. 9970b57cec5SDimitry Andric // Check if the individual operation can be promoted. 9980b57cec5SDimitry Andric switch (In->getOpcode()) { 9990b57cec5SDimitry Andric case Instruction::PHI: 10000b57cec5SDimitry Andric case Instruction::ZExt: 10010b57cec5SDimitry Andric case Instruction::And: 10020b57cec5SDimitry Andric case Instruction::Or: 10030b57cec5SDimitry Andric case Instruction::Xor: 10040b57cec5SDimitry Andric case Instruction::LShr: // Shift right is ok. 10050b57cec5SDimitry Andric case Instruction::Select: 10060b57cec5SDimitry Andric case Instruction::Trunc: 10070b57cec5SDimitry Andric return true; 10080b57cec5SDimitry Andric case Instruction::ICmp: 10090b57cec5SDimitry Andric if (CmpInst *CI = cast<CmpInst>(In)) 10100b57cec5SDimitry Andric return CI->isEquality() || CI->isUnsigned(); 10110b57cec5SDimitry Andric llvm_unreachable("Cast failed unexpectedly"); 10120b57cec5SDimitry Andric case Instruction::Add: 10130b57cec5SDimitry Andric return In->hasNoSignedWrap() && In->hasNoUnsignedWrap(); 10140b57cec5SDimitry Andric } 10150b57cec5SDimitry Andric return false; 10160b57cec5SDimitry Andric } 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric void PolynomialMultiplyRecognize::promoteTo(Instruction *In, 10190b57cec5SDimitry Andric IntegerType *DestTy, BasicBlock *LoopB) { 10200b57cec5SDimitry Andric Type *OrigTy = In->getType(); 10210b57cec5SDimitry Andric assert(!OrigTy->isVoidTy() && "Invalid instruction to promote"); 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric // Leave boolean values alone. 10240b57cec5SDimitry Andric if (!In->getType()->isIntegerTy(1)) 10250b57cec5SDimitry Andric In->mutateType(DestTy); 10260b57cec5SDimitry Andric unsigned DestBW = DestTy->getBitWidth(); 10270b57cec5SDimitry Andric 10280b57cec5SDimitry Andric // Handle PHIs. 10290b57cec5SDimitry Andric if (PHINode *P = dyn_cast<PHINode>(In)) { 10300b57cec5SDimitry Andric unsigned N = P->getNumIncomingValues(); 10310b57cec5SDimitry Andric for (unsigned i = 0; i != N; ++i) { 10320b57cec5SDimitry Andric BasicBlock *InB = P->getIncomingBlock(i); 10330b57cec5SDimitry Andric if (InB == LoopB) 10340b57cec5SDimitry Andric continue; 10350b57cec5SDimitry Andric Value *InV = P->getIncomingValue(i); 10360b57cec5SDimitry Andric IntegerType *Ty = cast<IntegerType>(InV->getType()); 10370b57cec5SDimitry Andric // Do not promote values in PHI nodes of type i1. 10380b57cec5SDimitry Andric if (Ty != P->getType()) { 10390b57cec5SDimitry Andric // If the value type does not match the PHI type, the PHI type 10400b57cec5SDimitry Andric // must have been promoted. 10410b57cec5SDimitry Andric assert(Ty->getBitWidth() < DestBW); 10420b57cec5SDimitry Andric InV = IRBuilder<>(InB->getTerminator()).CreateZExt(InV, DestTy); 10430b57cec5SDimitry Andric P->setIncomingValue(i, InV); 10440b57cec5SDimitry Andric } 10450b57cec5SDimitry Andric } 10460b57cec5SDimitry Andric } else if (ZExtInst *Z = dyn_cast<ZExtInst>(In)) { 10470b57cec5SDimitry Andric Value *Op = Z->getOperand(0); 10480b57cec5SDimitry Andric if (Op->getType() == Z->getType()) 10490b57cec5SDimitry Andric Z->replaceAllUsesWith(Op); 10500b57cec5SDimitry Andric Z->eraseFromParent(); 10510b57cec5SDimitry Andric return; 10520b57cec5SDimitry Andric } 10530b57cec5SDimitry Andric if (TruncInst *T = dyn_cast<TruncInst>(In)) { 10540b57cec5SDimitry Andric IntegerType *TruncTy = cast<IntegerType>(OrigTy); 10550b57cec5SDimitry Andric Value *Mask = ConstantInt::get(DestTy, (1u << TruncTy->getBitWidth()) - 1); 10560b57cec5SDimitry Andric Value *And = IRBuilder<>(In).CreateAnd(T->getOperand(0), Mask); 10570b57cec5SDimitry Andric T->replaceAllUsesWith(And); 10580b57cec5SDimitry Andric T->eraseFromParent(); 10590b57cec5SDimitry Andric return; 10600b57cec5SDimitry Andric } 10610b57cec5SDimitry Andric 10620b57cec5SDimitry Andric // Promote immediates. 10630b57cec5SDimitry Andric for (unsigned i = 0, n = In->getNumOperands(); i != n; ++i) { 10640b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(In->getOperand(i))) 1065*cb14a3feSDimitry Andric if (CI->getBitWidth() < DestBW) 10660b57cec5SDimitry Andric In->setOperand(i, ConstantInt::get(DestTy, CI->getZExtValue())); 10670b57cec5SDimitry Andric } 10680b57cec5SDimitry Andric } 10690b57cec5SDimitry Andric 10700b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::promoteTypes(BasicBlock *LoopB, 10710b57cec5SDimitry Andric BasicBlock *ExitB) { 10720b57cec5SDimitry Andric assert(LoopB); 10730b57cec5SDimitry Andric // Skip loops where the exit block has more than one predecessor. The values 10740b57cec5SDimitry Andric // coming from the loop block will be promoted to another type, and so the 10750b57cec5SDimitry Andric // values coming into the exit block from other predecessors would also have 10760b57cec5SDimitry Andric // to be promoted. 10770b57cec5SDimitry Andric if (!ExitB || (ExitB->getSinglePredecessor() != LoopB)) 10780b57cec5SDimitry Andric return false; 10790b57cec5SDimitry Andric IntegerType *DestTy = getPmpyType(); 10800b57cec5SDimitry Andric // Check if the exit values have types that are no wider than the type 10810b57cec5SDimitry Andric // that we want to promote to. 10820b57cec5SDimitry Andric unsigned DestBW = DestTy->getBitWidth(); 10830b57cec5SDimitry Andric for (PHINode &P : ExitB->phis()) { 10840b57cec5SDimitry Andric if (P.getNumIncomingValues() != 1) 10850b57cec5SDimitry Andric return false; 10860b57cec5SDimitry Andric assert(P.getIncomingBlock(0) == LoopB); 10870b57cec5SDimitry Andric IntegerType *T = dyn_cast<IntegerType>(P.getType()); 10880b57cec5SDimitry Andric if (!T || T->getBitWidth() > DestBW) 10890b57cec5SDimitry Andric return false; 10900b57cec5SDimitry Andric } 10910b57cec5SDimitry Andric 10920b57cec5SDimitry Andric // Check all instructions in the loop. 10930b57cec5SDimitry Andric for (Instruction &In : *LoopB) 10940b57cec5SDimitry Andric if (!In.isTerminator() && !isPromotableTo(&In, DestTy)) 10950b57cec5SDimitry Andric return false; 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric // Perform the promotion. 10980b57cec5SDimitry Andric std::vector<Instruction*> LoopIns; 10990b57cec5SDimitry Andric std::transform(LoopB->begin(), LoopB->end(), std::back_inserter(LoopIns), 11000b57cec5SDimitry Andric [](Instruction &In) { return &In; }); 11010b57cec5SDimitry Andric for (Instruction *In : LoopIns) 11020b57cec5SDimitry Andric if (!In->isTerminator()) 11030b57cec5SDimitry Andric promoteTo(In, DestTy, LoopB); 11040b57cec5SDimitry Andric 11050b57cec5SDimitry Andric // Fix up the PHI nodes in the exit block. 11060b57cec5SDimitry Andric Instruction *EndI = ExitB->getFirstNonPHI(); 11070b57cec5SDimitry Andric BasicBlock::iterator End = EndI ? EndI->getIterator() : ExitB->end(); 11080b57cec5SDimitry Andric for (auto I = ExitB->begin(); I != End; ++I) { 11090b57cec5SDimitry Andric PHINode *P = dyn_cast<PHINode>(I); 11100b57cec5SDimitry Andric if (!P) 11110b57cec5SDimitry Andric break; 11120b57cec5SDimitry Andric Type *Ty0 = P->getIncomingValue(0)->getType(); 11130b57cec5SDimitry Andric Type *PTy = P->getType(); 11140b57cec5SDimitry Andric if (PTy != Ty0) { 11150b57cec5SDimitry Andric assert(Ty0 == DestTy); 11160b57cec5SDimitry Andric // In order to create the trunc, P must have the promoted type. 11170b57cec5SDimitry Andric P->mutateType(Ty0); 11180b57cec5SDimitry Andric Value *T = IRBuilder<>(ExitB, End).CreateTrunc(P, PTy); 11190b57cec5SDimitry Andric // In order for the RAUW to work, the types of P and T must match. 11200b57cec5SDimitry Andric P->mutateType(PTy); 11210b57cec5SDimitry Andric P->replaceAllUsesWith(T); 11220b57cec5SDimitry Andric // Final update of the P's type. 11230b57cec5SDimitry Andric P->mutateType(Ty0); 11240b57cec5SDimitry Andric cast<Instruction>(T)->setOperand(0, P); 11250b57cec5SDimitry Andric } 11260b57cec5SDimitry Andric } 11270b57cec5SDimitry Andric 11280b57cec5SDimitry Andric return true; 11290b57cec5SDimitry Andric } 11300b57cec5SDimitry Andric 11310b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::findCycle(Value *Out, Value *In, 11320b57cec5SDimitry Andric ValueSeq &Cycle) { 11330b57cec5SDimitry Andric // Out = ..., In, ... 11340b57cec5SDimitry Andric if (Out == In) 11350b57cec5SDimitry Andric return true; 11360b57cec5SDimitry Andric 11370b57cec5SDimitry Andric auto *BB = cast<Instruction>(Out)->getParent(); 11380b57cec5SDimitry Andric bool HadPhi = false; 11390b57cec5SDimitry Andric 1140bdd1243dSDimitry Andric for (auto *U : Out->users()) { 11410b57cec5SDimitry Andric auto *I = dyn_cast<Instruction>(&*U); 11420b57cec5SDimitry Andric if (I == nullptr || I->getParent() != BB) 11430b57cec5SDimitry Andric continue; 11440b57cec5SDimitry Andric // Make sure that there are no multi-iteration cycles, e.g. 11450b57cec5SDimitry Andric // p1 = phi(p2) 11460b57cec5SDimitry Andric // p2 = phi(p1) 11470b57cec5SDimitry Andric // The cycle p1->p2->p1 would span two loop iterations. 11480b57cec5SDimitry Andric // Check that there is only one phi in the cycle. 11490b57cec5SDimitry Andric bool IsPhi = isa<PHINode>(I); 11500b57cec5SDimitry Andric if (IsPhi && HadPhi) 11510b57cec5SDimitry Andric return false; 11520b57cec5SDimitry Andric HadPhi |= IsPhi; 115381ad6265SDimitry Andric if (!Cycle.insert(I)) 11540b57cec5SDimitry Andric return false; 11550b57cec5SDimitry Andric if (findCycle(I, In, Cycle)) 11560b57cec5SDimitry Andric break; 11570b57cec5SDimitry Andric Cycle.remove(I); 11580b57cec5SDimitry Andric } 11590b57cec5SDimitry Andric return !Cycle.empty(); 11600b57cec5SDimitry Andric } 11610b57cec5SDimitry Andric 11620b57cec5SDimitry Andric void PolynomialMultiplyRecognize::classifyCycle(Instruction *DivI, 11630b57cec5SDimitry Andric ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) { 11640b57cec5SDimitry Andric // All the values in the cycle that are between the phi node and the 11650b57cec5SDimitry Andric // divider instruction will be classified as "early", all other values 11660b57cec5SDimitry Andric // will be "late". 11670b57cec5SDimitry Andric 11680b57cec5SDimitry Andric bool IsE = true; 11690b57cec5SDimitry Andric unsigned I, N = Cycle.size(); 11700b57cec5SDimitry Andric for (I = 0; I < N; ++I) { 11710b57cec5SDimitry Andric Value *V = Cycle[I]; 11720b57cec5SDimitry Andric if (DivI == V) 11730b57cec5SDimitry Andric IsE = false; 11740b57cec5SDimitry Andric else if (!isa<PHINode>(V)) 11750b57cec5SDimitry Andric continue; 11760b57cec5SDimitry Andric // Stop if found either. 11770b57cec5SDimitry Andric break; 11780b57cec5SDimitry Andric } 11790b57cec5SDimitry Andric // "I" is the index of either DivI or the phi node, whichever was first. 11800b57cec5SDimitry Andric // "E" is "false" or "true" respectively. 11810b57cec5SDimitry Andric ValueSeq &First = !IsE ? Early : Late; 11820b57cec5SDimitry Andric for (unsigned J = 0; J < I; ++J) 11830b57cec5SDimitry Andric First.insert(Cycle[J]); 11840b57cec5SDimitry Andric 11850b57cec5SDimitry Andric ValueSeq &Second = IsE ? Early : Late; 11860b57cec5SDimitry Andric Second.insert(Cycle[I]); 11870b57cec5SDimitry Andric for (++I; I < N; ++I) { 11880b57cec5SDimitry Andric Value *V = Cycle[I]; 11890b57cec5SDimitry Andric if (DivI == V || isa<PHINode>(V)) 11900b57cec5SDimitry Andric break; 11910b57cec5SDimitry Andric Second.insert(V); 11920b57cec5SDimitry Andric } 11930b57cec5SDimitry Andric 11940b57cec5SDimitry Andric for (; I < N; ++I) 11950b57cec5SDimitry Andric First.insert(Cycle[I]); 11960b57cec5SDimitry Andric } 11970b57cec5SDimitry Andric 11980b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::classifyInst(Instruction *UseI, 11990b57cec5SDimitry Andric ValueSeq &Early, ValueSeq &Late) { 12000b57cec5SDimitry Andric // Select is an exception, since the condition value does not have to be 12010b57cec5SDimitry Andric // classified in the same way as the true/false values. The true/false 12020b57cec5SDimitry Andric // values do have to be both early or both late. 12030b57cec5SDimitry Andric if (UseI->getOpcode() == Instruction::Select) { 12040b57cec5SDimitry Andric Value *TV = UseI->getOperand(1), *FV = UseI->getOperand(2); 12050b57cec5SDimitry Andric if (Early.count(TV) || Early.count(FV)) { 12060b57cec5SDimitry Andric if (Late.count(TV) || Late.count(FV)) 12070b57cec5SDimitry Andric return false; 12080b57cec5SDimitry Andric Early.insert(UseI); 12090b57cec5SDimitry Andric } else if (Late.count(TV) || Late.count(FV)) { 12100b57cec5SDimitry Andric if (Early.count(TV) || Early.count(FV)) 12110b57cec5SDimitry Andric return false; 12120b57cec5SDimitry Andric Late.insert(UseI); 12130b57cec5SDimitry Andric } 12140b57cec5SDimitry Andric return true; 12150b57cec5SDimitry Andric } 12160b57cec5SDimitry Andric 12170b57cec5SDimitry Andric // Not sure what would be the example of this, but the code below relies 12180b57cec5SDimitry Andric // on having at least one operand. 12190b57cec5SDimitry Andric if (UseI->getNumOperands() == 0) 12200b57cec5SDimitry Andric return true; 12210b57cec5SDimitry Andric 12220b57cec5SDimitry Andric bool AE = true, AL = true; 12230b57cec5SDimitry Andric for (auto &I : UseI->operands()) { 12240b57cec5SDimitry Andric if (Early.count(&*I)) 12250b57cec5SDimitry Andric AL = false; 12260b57cec5SDimitry Andric else if (Late.count(&*I)) 12270b57cec5SDimitry Andric AE = false; 12280b57cec5SDimitry Andric } 12290b57cec5SDimitry Andric // If the operands appear "all early" and "all late" at the same time, 12300b57cec5SDimitry Andric // then it means that none of them are actually classified as either. 12310b57cec5SDimitry Andric // This is harmless. 12320b57cec5SDimitry Andric if (AE && AL) 12330b57cec5SDimitry Andric return true; 12340b57cec5SDimitry Andric // Conversely, if they are neither "all early" nor "all late", then 12350b57cec5SDimitry Andric // we have a mixture of early and late operands that is not a known 12360b57cec5SDimitry Andric // exception. 12370b57cec5SDimitry Andric if (!AE && !AL) 12380b57cec5SDimitry Andric return false; 12390b57cec5SDimitry Andric 12400b57cec5SDimitry Andric // Check that we have covered the two special cases. 12410b57cec5SDimitry Andric assert(AE != AL); 12420b57cec5SDimitry Andric 12430b57cec5SDimitry Andric if (AE) 12440b57cec5SDimitry Andric Early.insert(UseI); 12450b57cec5SDimitry Andric else 12460b57cec5SDimitry Andric Late.insert(UseI); 12470b57cec5SDimitry Andric return true; 12480b57cec5SDimitry Andric } 12490b57cec5SDimitry Andric 12500b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::commutesWithShift(Instruction *I) { 12510b57cec5SDimitry Andric switch (I->getOpcode()) { 12520b57cec5SDimitry Andric case Instruction::And: 12530b57cec5SDimitry Andric case Instruction::Or: 12540b57cec5SDimitry Andric case Instruction::Xor: 12550b57cec5SDimitry Andric case Instruction::LShr: 12560b57cec5SDimitry Andric case Instruction::Shl: 12570b57cec5SDimitry Andric case Instruction::Select: 12580b57cec5SDimitry Andric case Instruction::ICmp: 12590b57cec5SDimitry Andric case Instruction::PHI: 12600b57cec5SDimitry Andric break; 12610b57cec5SDimitry Andric default: 12620b57cec5SDimitry Andric return false; 12630b57cec5SDimitry Andric } 12640b57cec5SDimitry Andric return true; 12650b57cec5SDimitry Andric } 12660b57cec5SDimitry Andric 12670b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V, 12680b57cec5SDimitry Andric unsigned IterCount) { 12690b57cec5SDimitry Andric auto *T = dyn_cast<IntegerType>(V->getType()); 12700b57cec5SDimitry Andric if (!T) 12710b57cec5SDimitry Andric return false; 12720b57cec5SDimitry Andric 12730b57cec5SDimitry Andric KnownBits Known(T->getBitWidth()); 12740b57cec5SDimitry Andric computeKnownBits(V, Known, DL); 12750b57cec5SDimitry Andric return Known.countMinLeadingZeros() >= IterCount; 12760b57cec5SDimitry Andric } 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::keepsHighBitsZero(Value *V, 12790b57cec5SDimitry Andric unsigned IterCount) { 12800b57cec5SDimitry Andric // Assume that all inputs to the value have the high bits zero. 12810b57cec5SDimitry Andric // Check if the value itself preserves the zeros in the high bits. 12820b57cec5SDimitry Andric if (auto *C = dyn_cast<ConstantInt>(V)) 128306c3fb27SDimitry Andric return C->getValue().countl_zero() >= IterCount; 12840b57cec5SDimitry Andric 12850b57cec5SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) { 12860b57cec5SDimitry Andric switch (I->getOpcode()) { 12870b57cec5SDimitry Andric case Instruction::And: 12880b57cec5SDimitry Andric case Instruction::Or: 12890b57cec5SDimitry Andric case Instruction::Xor: 12900b57cec5SDimitry Andric case Instruction::LShr: 12910b57cec5SDimitry Andric case Instruction::Select: 12920b57cec5SDimitry Andric case Instruction::ICmp: 12930b57cec5SDimitry Andric case Instruction::PHI: 12940b57cec5SDimitry Andric case Instruction::ZExt: 12950b57cec5SDimitry Andric return true; 12960b57cec5SDimitry Andric } 12970b57cec5SDimitry Andric } 12980b57cec5SDimitry Andric 12990b57cec5SDimitry Andric return false; 13000b57cec5SDimitry Andric } 13010b57cec5SDimitry Andric 13020b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::isOperandShifted(Instruction *I, Value *Op) { 13030b57cec5SDimitry Andric unsigned Opc = I->getOpcode(); 13040b57cec5SDimitry Andric if (Opc == Instruction::Shl || Opc == Instruction::LShr) 13050b57cec5SDimitry Andric return Op != I->getOperand(1); 13060b57cec5SDimitry Andric return true; 13070b57cec5SDimitry Andric } 13080b57cec5SDimitry Andric 13090b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB, 13100b57cec5SDimitry Andric BasicBlock *ExitB, unsigned IterCount) { 13110b57cec5SDimitry Andric Value *CIV = getCountIV(LoopB); 13120b57cec5SDimitry Andric if (CIV == nullptr) 13130b57cec5SDimitry Andric return false; 13140b57cec5SDimitry Andric auto *CIVTy = dyn_cast<IntegerType>(CIV->getType()); 13150b57cec5SDimitry Andric if (CIVTy == nullptr) 13160b57cec5SDimitry Andric return false; 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric ValueSeq RShifts; 13190b57cec5SDimitry Andric ValueSeq Early, Late, Cycled; 13200b57cec5SDimitry Andric 13210b57cec5SDimitry Andric // Find all value cycles that contain logical right shifts by 1. 13220b57cec5SDimitry Andric for (Instruction &I : *LoopB) { 13230b57cec5SDimitry Andric using namespace PatternMatch; 13240b57cec5SDimitry Andric 13250b57cec5SDimitry Andric Value *V = nullptr; 13260b57cec5SDimitry Andric if (!match(&I, m_LShr(m_Value(V), m_One()))) 13270b57cec5SDimitry Andric continue; 13280b57cec5SDimitry Andric ValueSeq C; 13290b57cec5SDimitry Andric if (!findCycle(&I, V, C)) 13300b57cec5SDimitry Andric continue; 13310b57cec5SDimitry Andric 13320b57cec5SDimitry Andric // Found a cycle. 13330b57cec5SDimitry Andric C.insert(&I); 13340b57cec5SDimitry Andric classifyCycle(&I, C, Early, Late); 13350b57cec5SDimitry Andric Cycled.insert(C.begin(), C.end()); 13360b57cec5SDimitry Andric RShifts.insert(&I); 13370b57cec5SDimitry Andric } 13380b57cec5SDimitry Andric 13390b57cec5SDimitry Andric // Find the set of all values affected by the shift cycles, i.e. all 13400b57cec5SDimitry Andric // cycled values, and (recursively) all their users. 13410b57cec5SDimitry Andric ValueSeq Users(Cycled.begin(), Cycled.end()); 13420b57cec5SDimitry Andric for (unsigned i = 0; i < Users.size(); ++i) { 13430b57cec5SDimitry Andric Value *V = Users[i]; 13440b57cec5SDimitry Andric if (!isa<IntegerType>(V->getType())) 13450b57cec5SDimitry Andric return false; 13460b57cec5SDimitry Andric auto *R = cast<Instruction>(V); 13470b57cec5SDimitry Andric // If the instruction does not commute with shifts, the loop cannot 13480b57cec5SDimitry Andric // be unshifted. 13490b57cec5SDimitry Andric if (!commutesWithShift(R)) 13500b57cec5SDimitry Andric return false; 1351349cc55cSDimitry Andric for (User *U : R->users()) { 1352349cc55cSDimitry Andric auto *T = cast<Instruction>(U); 13530b57cec5SDimitry Andric // Skip users from outside of the loop. They will be handled later. 13540b57cec5SDimitry Andric // Also, skip the right-shifts and phi nodes, since they mix early 13550b57cec5SDimitry Andric // and late values. 13560b57cec5SDimitry Andric if (T->getParent() != LoopB || RShifts.count(T) || isa<PHINode>(T)) 13570b57cec5SDimitry Andric continue; 13580b57cec5SDimitry Andric 13590b57cec5SDimitry Andric Users.insert(T); 13600b57cec5SDimitry Andric if (!classifyInst(T, Early, Late)) 13610b57cec5SDimitry Andric return false; 13620b57cec5SDimitry Andric } 13630b57cec5SDimitry Andric } 13640b57cec5SDimitry Andric 13650b57cec5SDimitry Andric if (Users.empty()) 13660b57cec5SDimitry Andric return false; 13670b57cec5SDimitry Andric 13680b57cec5SDimitry Andric // Verify that high bits remain zero. 13690b57cec5SDimitry Andric ValueSeq Internal(Users.begin(), Users.end()); 13700b57cec5SDimitry Andric ValueSeq Inputs; 13710b57cec5SDimitry Andric for (unsigned i = 0; i < Internal.size(); ++i) { 13720b57cec5SDimitry Andric auto *R = dyn_cast<Instruction>(Internal[i]); 13730b57cec5SDimitry Andric if (!R) 13740b57cec5SDimitry Andric continue; 13750b57cec5SDimitry Andric for (Value *Op : R->operands()) { 13760b57cec5SDimitry Andric auto *T = dyn_cast<Instruction>(Op); 13770b57cec5SDimitry Andric if (T && T->getParent() != LoopB) 13780b57cec5SDimitry Andric Inputs.insert(Op); 13790b57cec5SDimitry Andric else 13800b57cec5SDimitry Andric Internal.insert(Op); 13810b57cec5SDimitry Andric } 13820b57cec5SDimitry Andric } 13830b57cec5SDimitry Andric for (Value *V : Inputs) 13840b57cec5SDimitry Andric if (!highBitsAreZero(V, IterCount)) 13850b57cec5SDimitry Andric return false; 13860b57cec5SDimitry Andric for (Value *V : Internal) 13870b57cec5SDimitry Andric if (!keepsHighBitsZero(V, IterCount)) 13880b57cec5SDimitry Andric return false; 13890b57cec5SDimitry Andric 13900b57cec5SDimitry Andric // Finally, the work can be done. Unshift each user. 13910b57cec5SDimitry Andric IRBuilder<> IRB(LoopB); 13920b57cec5SDimitry Andric std::map<Value*,Value*> ShiftMap; 13930b57cec5SDimitry Andric 13940b57cec5SDimitry Andric using CastMapType = std::map<std::pair<Value *, Type *>, Value *>; 13950b57cec5SDimitry Andric 13960b57cec5SDimitry Andric CastMapType CastMap; 13970b57cec5SDimitry Andric 13980b57cec5SDimitry Andric auto upcast = [] (CastMapType &CM, IRBuilder<> &IRB, Value *V, 13990b57cec5SDimitry Andric IntegerType *Ty) -> Value* { 14000b57cec5SDimitry Andric auto H = CM.find(std::make_pair(V, Ty)); 14010b57cec5SDimitry Andric if (H != CM.end()) 14020b57cec5SDimitry Andric return H->second; 14030b57cec5SDimitry Andric Value *CV = IRB.CreateIntCast(V, Ty, false); 14040b57cec5SDimitry Andric CM.insert(std::make_pair(std::make_pair(V, Ty), CV)); 14050b57cec5SDimitry Andric return CV; 14060b57cec5SDimitry Andric }; 14070b57cec5SDimitry Andric 14080b57cec5SDimitry Andric for (auto I = LoopB->begin(), E = LoopB->end(); I != E; ++I) { 14090b57cec5SDimitry Andric using namespace PatternMatch; 14100b57cec5SDimitry Andric 14110b57cec5SDimitry Andric if (isa<PHINode>(I) || !Users.count(&*I)) 14120b57cec5SDimitry Andric continue; 14130b57cec5SDimitry Andric 14140b57cec5SDimitry Andric // Match lshr x, 1. 14150b57cec5SDimitry Andric Value *V = nullptr; 14160b57cec5SDimitry Andric if (match(&*I, m_LShr(m_Value(V), m_One()))) { 14170b57cec5SDimitry Andric replaceAllUsesOfWithIn(&*I, V, LoopB); 14180b57cec5SDimitry Andric continue; 14190b57cec5SDimitry Andric } 14200b57cec5SDimitry Andric // For each non-cycled operand, replace it with the corresponding 14210b57cec5SDimitry Andric // value shifted left. 14220b57cec5SDimitry Andric for (auto &J : I->operands()) { 14230b57cec5SDimitry Andric Value *Op = J.get(); 14240b57cec5SDimitry Andric if (!isOperandShifted(&*I, Op)) 14250b57cec5SDimitry Andric continue; 14260b57cec5SDimitry Andric if (Users.count(Op)) 14270b57cec5SDimitry Andric continue; 14280b57cec5SDimitry Andric // Skip shifting zeros. 14290b57cec5SDimitry Andric if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero()) 14300b57cec5SDimitry Andric continue; 14310b57cec5SDimitry Andric // Check if we have already generated a shift for this value. 14320b57cec5SDimitry Andric auto F = ShiftMap.find(Op); 14330b57cec5SDimitry Andric Value *W = (F != ShiftMap.end()) ? F->second : nullptr; 14340b57cec5SDimitry Andric if (W == nullptr) { 14350b57cec5SDimitry Andric IRB.SetInsertPoint(&*I); 14360b57cec5SDimitry Andric // First, the shift amount will be CIV or CIV+1, depending on 14370b57cec5SDimitry Andric // whether the value is early or late. Instead of creating CIV+1, 14380b57cec5SDimitry Andric // do a single shift of the value. 14390b57cec5SDimitry Andric Value *ShAmt = CIV, *ShVal = Op; 14400b57cec5SDimitry Andric auto *VTy = cast<IntegerType>(ShVal->getType()); 14410b57cec5SDimitry Andric auto *ATy = cast<IntegerType>(ShAmt->getType()); 14420b57cec5SDimitry Andric if (Late.count(&*I)) 14430b57cec5SDimitry Andric ShVal = IRB.CreateShl(Op, ConstantInt::get(VTy, 1)); 14440b57cec5SDimitry Andric // Second, the types of the shifted value and the shift amount 14450b57cec5SDimitry Andric // must match. 14460b57cec5SDimitry Andric if (VTy != ATy) { 14470b57cec5SDimitry Andric if (VTy->getBitWidth() < ATy->getBitWidth()) 14480b57cec5SDimitry Andric ShVal = upcast(CastMap, IRB, ShVal, ATy); 14490b57cec5SDimitry Andric else 14500b57cec5SDimitry Andric ShAmt = upcast(CastMap, IRB, ShAmt, VTy); 14510b57cec5SDimitry Andric } 14520b57cec5SDimitry Andric // Ready to generate the shift and memoize it. 14530b57cec5SDimitry Andric W = IRB.CreateShl(ShVal, ShAmt); 14540b57cec5SDimitry Andric ShiftMap.insert(std::make_pair(Op, W)); 14550b57cec5SDimitry Andric } 14560b57cec5SDimitry Andric I->replaceUsesOfWith(Op, W); 14570b57cec5SDimitry Andric } 14580b57cec5SDimitry Andric } 14590b57cec5SDimitry Andric 14600b57cec5SDimitry Andric // Update the users outside of the loop to account for having left 14610b57cec5SDimitry Andric // shifts. They would normally be shifted right in the loop, so shift 14620b57cec5SDimitry Andric // them right after the loop exit. 14630b57cec5SDimitry Andric // Take advantage of the loop-closed SSA form, which has all the post- 14640b57cec5SDimitry Andric // loop values in phi nodes. 14650b57cec5SDimitry Andric IRB.SetInsertPoint(ExitB, ExitB->getFirstInsertionPt()); 14660b57cec5SDimitry Andric for (auto P = ExitB->begin(), Q = ExitB->end(); P != Q; ++P) { 14670b57cec5SDimitry Andric if (!isa<PHINode>(P)) 14680b57cec5SDimitry Andric break; 14690b57cec5SDimitry Andric auto *PN = cast<PHINode>(P); 14700b57cec5SDimitry Andric Value *U = PN->getIncomingValueForBlock(LoopB); 14710b57cec5SDimitry Andric if (!Users.count(U)) 14720b57cec5SDimitry Andric continue; 14730b57cec5SDimitry Andric Value *S = IRB.CreateLShr(PN, ConstantInt::get(PN->getType(), IterCount)); 14740b57cec5SDimitry Andric PN->replaceAllUsesWith(S); 14750b57cec5SDimitry Andric // The above RAUW will create 14760b57cec5SDimitry Andric // S = lshr S, IterCount 14770b57cec5SDimitry Andric // so we need to fix it back into 14780b57cec5SDimitry Andric // S = lshr PN, IterCount 14790b57cec5SDimitry Andric cast<User>(S)->replaceUsesOfWith(S, PN); 14800b57cec5SDimitry Andric } 14810b57cec5SDimitry Andric 14820b57cec5SDimitry Andric return true; 14830b57cec5SDimitry Andric } 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) { 14860b57cec5SDimitry Andric for (auto &I : *LoopB) 148781ad6265SDimitry Andric if (Value *SV = simplifyInstruction(&I, {DL, &TLI, &DT})) 14880b57cec5SDimitry Andric I.replaceAllUsesWith(SV); 14890b57cec5SDimitry Andric 1490349cc55cSDimitry Andric for (Instruction &I : llvm::make_early_inc_range(*LoopB)) 1491349cc55cSDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(&I, &TLI); 14920b57cec5SDimitry Andric } 14930b57cec5SDimitry Andric 14940b57cec5SDimitry Andric unsigned PolynomialMultiplyRecognize::getInverseMxN(unsigned QP) { 14950b57cec5SDimitry Andric // Arrays of coefficients of Q and the inverse, C. 14960b57cec5SDimitry Andric // Q[i] = coefficient at x^i. 14970b57cec5SDimitry Andric std::array<char,32> Q, C; 14980b57cec5SDimitry Andric 14990b57cec5SDimitry Andric for (unsigned i = 0; i < 32; ++i) { 15000b57cec5SDimitry Andric Q[i] = QP & 1; 15010b57cec5SDimitry Andric QP >>= 1; 15020b57cec5SDimitry Andric } 15030b57cec5SDimitry Andric assert(Q[0] == 1); 15040b57cec5SDimitry Andric 15050b57cec5SDimitry Andric // Find C, such that 15060b57cec5SDimitry Andric // (Q[n]*x^n + ... + Q[1]*x + Q[0]) * (C[n]*x^n + ... + C[1]*x + C[0]) = 1 15070b57cec5SDimitry Andric // 15080b57cec5SDimitry Andric // For it to have a solution, Q[0] must be 1. Since this is Z2[x], the 15090b57cec5SDimitry Andric // operations * and + are & and ^ respectively. 15100b57cec5SDimitry Andric // 15110b57cec5SDimitry Andric // Find C[i] recursively, by comparing i-th coefficient in the product 15120b57cec5SDimitry Andric // with 0 (or 1 for i=0). 15130b57cec5SDimitry Andric // 15140b57cec5SDimitry Andric // C[0] = 1, since C[0] = Q[0], and Q[0] = 1. 15150b57cec5SDimitry Andric C[0] = 1; 15160b57cec5SDimitry Andric for (unsigned i = 1; i < 32; ++i) { 15170b57cec5SDimitry Andric // Solve for C[i] in: 15180b57cec5SDimitry Andric // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i]Q[0] = 0 15190b57cec5SDimitry Andric // This is equivalent to 15200b57cec5SDimitry Andric // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i] = 0 15210b57cec5SDimitry Andric // which is 15220b57cec5SDimitry Andric // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] = C[i] 15230b57cec5SDimitry Andric unsigned T = 0; 15240b57cec5SDimitry Andric for (unsigned j = 0; j < i; ++j) 15250b57cec5SDimitry Andric T = T ^ (C[j] & Q[i-j]); 15260b57cec5SDimitry Andric C[i] = T; 15270b57cec5SDimitry Andric } 15280b57cec5SDimitry Andric 15290b57cec5SDimitry Andric unsigned QV = 0; 15300b57cec5SDimitry Andric for (unsigned i = 0; i < 32; ++i) 15310b57cec5SDimitry Andric if (C[i]) 15320b57cec5SDimitry Andric QV |= (1 << i); 15330b57cec5SDimitry Andric 15340b57cec5SDimitry Andric return QV; 15350b57cec5SDimitry Andric } 15360b57cec5SDimitry Andric 15370b57cec5SDimitry Andric Value *PolynomialMultiplyRecognize::generate(BasicBlock::iterator At, 15380b57cec5SDimitry Andric ParsedValues &PV) { 15390b57cec5SDimitry Andric IRBuilder<> B(&*At); 15400b57cec5SDimitry Andric Module *M = At->getParent()->getParent()->getParent(); 15410b57cec5SDimitry Andric Function *PMF = Intrinsic::getDeclaration(M, Intrinsic::hexagon_M4_pmpyw); 15420b57cec5SDimitry Andric 15430b57cec5SDimitry Andric Value *P = PV.P, *Q = PV.Q, *P0 = P; 15440b57cec5SDimitry Andric unsigned IC = PV.IterCount; 15450b57cec5SDimitry Andric 15460b57cec5SDimitry Andric if (PV.M != nullptr) 15470b57cec5SDimitry Andric P0 = P = B.CreateXor(P, PV.M); 15480b57cec5SDimitry Andric 15490b57cec5SDimitry Andric // Create a bit mask to clear the high bits beyond IterCount. 15500b57cec5SDimitry Andric auto *BMI = ConstantInt::get(P->getType(), APInt::getLowBitsSet(32, IC)); 15510b57cec5SDimitry Andric 15520b57cec5SDimitry Andric if (PV.IterCount != 32) 15530b57cec5SDimitry Andric P = B.CreateAnd(P, BMI); 15540b57cec5SDimitry Andric 15550b57cec5SDimitry Andric if (PV.Inv) { 15560b57cec5SDimitry Andric auto *QI = dyn_cast<ConstantInt>(PV.Q); 15570b57cec5SDimitry Andric assert(QI && QI->getBitWidth() <= 32); 15580b57cec5SDimitry Andric 15590b57cec5SDimitry Andric // Again, clearing bits beyond IterCount. 15600b57cec5SDimitry Andric unsigned M = (1 << PV.IterCount) - 1; 15610b57cec5SDimitry Andric unsigned Tmp = (QI->getZExtValue() | 1) & M; 15620b57cec5SDimitry Andric unsigned QV = getInverseMxN(Tmp) & M; 15630b57cec5SDimitry Andric auto *QVI = ConstantInt::get(QI->getType(), QV); 15640b57cec5SDimitry Andric P = B.CreateCall(PMF, {P, QVI}); 15650b57cec5SDimitry Andric P = B.CreateTrunc(P, QI->getType()); 15660b57cec5SDimitry Andric if (IC != 32) 15670b57cec5SDimitry Andric P = B.CreateAnd(P, BMI); 15680b57cec5SDimitry Andric } 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric Value *R = B.CreateCall(PMF, {P, Q}); 15710b57cec5SDimitry Andric 15720b57cec5SDimitry Andric if (PV.M != nullptr) 15730b57cec5SDimitry Andric R = B.CreateXor(R, B.CreateIntCast(P0, R->getType(), false)); 15740b57cec5SDimitry Andric 15750b57cec5SDimitry Andric return R; 15760b57cec5SDimitry Andric } 15770b57cec5SDimitry Andric 15780b57cec5SDimitry Andric static bool hasZeroSignBit(const Value *V) { 15790b57cec5SDimitry Andric if (const auto *CI = dyn_cast<const ConstantInt>(V)) 1580*cb14a3feSDimitry Andric return CI->getValue().isNonNegative(); 15810b57cec5SDimitry Andric const Instruction *I = dyn_cast<const Instruction>(V); 15820b57cec5SDimitry Andric if (!I) 15830b57cec5SDimitry Andric return false; 15840b57cec5SDimitry Andric switch (I->getOpcode()) { 15850b57cec5SDimitry Andric case Instruction::LShr: 15860b57cec5SDimitry Andric if (const auto SI = dyn_cast<const ConstantInt>(I->getOperand(1))) 15870b57cec5SDimitry Andric return SI->getZExtValue() > 0; 15880b57cec5SDimitry Andric return false; 15890b57cec5SDimitry Andric case Instruction::Or: 15900b57cec5SDimitry Andric case Instruction::Xor: 15910b57cec5SDimitry Andric return hasZeroSignBit(I->getOperand(0)) && 15920b57cec5SDimitry Andric hasZeroSignBit(I->getOperand(1)); 15930b57cec5SDimitry Andric case Instruction::And: 15940b57cec5SDimitry Andric return hasZeroSignBit(I->getOperand(0)) || 15950b57cec5SDimitry Andric hasZeroSignBit(I->getOperand(1)); 15960b57cec5SDimitry Andric } 15970b57cec5SDimitry Andric return false; 15980b57cec5SDimitry Andric } 15990b57cec5SDimitry Andric 16000b57cec5SDimitry Andric void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) { 16010b57cec5SDimitry Andric S.addRule("sink-zext", 16020b57cec5SDimitry Andric // Sink zext past bitwise operations. 16030b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 16040b57cec5SDimitry Andric if (I->getOpcode() != Instruction::ZExt) 16050b57cec5SDimitry Andric return nullptr; 16060b57cec5SDimitry Andric Instruction *T = dyn_cast<Instruction>(I->getOperand(0)); 16070b57cec5SDimitry Andric if (!T) 16080b57cec5SDimitry Andric return nullptr; 16090b57cec5SDimitry Andric switch (T->getOpcode()) { 16100b57cec5SDimitry Andric case Instruction::And: 16110b57cec5SDimitry Andric case Instruction::Or: 16120b57cec5SDimitry Andric case Instruction::Xor: 16130b57cec5SDimitry Andric break; 16140b57cec5SDimitry Andric default: 16150b57cec5SDimitry Andric return nullptr; 16160b57cec5SDimitry Andric } 16170b57cec5SDimitry Andric IRBuilder<> B(Ctx); 16180b57cec5SDimitry Andric return B.CreateBinOp(cast<BinaryOperator>(T)->getOpcode(), 16190b57cec5SDimitry Andric B.CreateZExt(T->getOperand(0), I->getType()), 16200b57cec5SDimitry Andric B.CreateZExt(T->getOperand(1), I->getType())); 16210b57cec5SDimitry Andric }); 16220b57cec5SDimitry Andric S.addRule("xor/and -> and/xor", 16230b57cec5SDimitry Andric // (xor (and x a) (and y a)) -> (and (xor x y) a) 16240b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 16250b57cec5SDimitry Andric if (I->getOpcode() != Instruction::Xor) 16260b57cec5SDimitry Andric return nullptr; 16270b57cec5SDimitry Andric Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0)); 16280b57cec5SDimitry Andric Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1)); 16290b57cec5SDimitry Andric if (!And0 || !And1) 16300b57cec5SDimitry Andric return nullptr; 16310b57cec5SDimitry Andric if (And0->getOpcode() != Instruction::And || 16320b57cec5SDimitry Andric And1->getOpcode() != Instruction::And) 16330b57cec5SDimitry Andric return nullptr; 16340b57cec5SDimitry Andric if (And0->getOperand(1) != And1->getOperand(1)) 16350b57cec5SDimitry Andric return nullptr; 16360b57cec5SDimitry Andric IRBuilder<> B(Ctx); 16370b57cec5SDimitry Andric return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1->getOperand(0)), 16380b57cec5SDimitry Andric And0->getOperand(1)); 16390b57cec5SDimitry Andric }); 16400b57cec5SDimitry Andric S.addRule("sink binop into select", 16410b57cec5SDimitry Andric // (Op (select c x y) z) -> (select c (Op x z) (Op y z)) 16420b57cec5SDimitry Andric // (Op x (select c y z)) -> (select c (Op x y) (Op x z)) 16430b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 16440b57cec5SDimitry Andric BinaryOperator *BO = dyn_cast<BinaryOperator>(I); 16450b57cec5SDimitry Andric if (!BO) 16460b57cec5SDimitry Andric return nullptr; 16470b57cec5SDimitry Andric Instruction::BinaryOps Op = BO->getOpcode(); 16480b57cec5SDimitry Andric if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) { 16490b57cec5SDimitry Andric IRBuilder<> B(Ctx); 16500b57cec5SDimitry Andric Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue(); 16510b57cec5SDimitry Andric Value *Z = BO->getOperand(1); 16520b57cec5SDimitry Andric return B.CreateSelect(Sel->getCondition(), 16530b57cec5SDimitry Andric B.CreateBinOp(Op, X, Z), 16540b57cec5SDimitry Andric B.CreateBinOp(Op, Y, Z)); 16550b57cec5SDimitry Andric } 16560b57cec5SDimitry Andric if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) { 16570b57cec5SDimitry Andric IRBuilder<> B(Ctx); 16580b57cec5SDimitry Andric Value *X = BO->getOperand(0); 16590b57cec5SDimitry Andric Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue(); 16600b57cec5SDimitry Andric return B.CreateSelect(Sel->getCondition(), 16610b57cec5SDimitry Andric B.CreateBinOp(Op, X, Y), 16620b57cec5SDimitry Andric B.CreateBinOp(Op, X, Z)); 16630b57cec5SDimitry Andric } 16640b57cec5SDimitry Andric return nullptr; 16650b57cec5SDimitry Andric }); 16660b57cec5SDimitry Andric S.addRule("fold select-select", 16670b57cec5SDimitry Andric // (select c (select c x y) z) -> (select c x z) 16680b57cec5SDimitry Andric // (select c x (select c y z)) -> (select c x z) 16690b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 16700b57cec5SDimitry Andric SelectInst *Sel = dyn_cast<SelectInst>(I); 16710b57cec5SDimitry Andric if (!Sel) 16720b57cec5SDimitry Andric return nullptr; 16730b57cec5SDimitry Andric IRBuilder<> B(Ctx); 16740b57cec5SDimitry Andric Value *C = Sel->getCondition(); 16750b57cec5SDimitry Andric if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) { 16760b57cec5SDimitry Andric if (Sel0->getCondition() == C) 16770b57cec5SDimitry Andric return B.CreateSelect(C, Sel0->getTrueValue(), Sel->getFalseValue()); 16780b57cec5SDimitry Andric } 16790b57cec5SDimitry Andric if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) { 16800b57cec5SDimitry Andric if (Sel1->getCondition() == C) 16810b57cec5SDimitry Andric return B.CreateSelect(C, Sel->getTrueValue(), Sel1->getFalseValue()); 16820b57cec5SDimitry Andric } 16830b57cec5SDimitry Andric return nullptr; 16840b57cec5SDimitry Andric }); 16850b57cec5SDimitry Andric S.addRule("or-signbit -> xor-signbit", 16860b57cec5SDimitry Andric // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0) 16870b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 16880b57cec5SDimitry Andric if (I->getOpcode() != Instruction::Or) 16890b57cec5SDimitry Andric return nullptr; 16900b57cec5SDimitry Andric ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1)); 1691*cb14a3feSDimitry Andric if (!Msb || !Msb->getValue().isSignMask()) 16920b57cec5SDimitry Andric return nullptr; 16930b57cec5SDimitry Andric if (!hasZeroSignBit(I->getOperand(0))) 16940b57cec5SDimitry Andric return nullptr; 16950b57cec5SDimitry Andric return IRBuilder<>(Ctx).CreateXor(I->getOperand(0), Msb); 16960b57cec5SDimitry Andric }); 16970b57cec5SDimitry Andric S.addRule("sink lshr into binop", 16980b57cec5SDimitry Andric // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c)) 16990b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 17000b57cec5SDimitry Andric if (I->getOpcode() != Instruction::LShr) 17010b57cec5SDimitry Andric return nullptr; 17020b57cec5SDimitry Andric BinaryOperator *BitOp = dyn_cast<BinaryOperator>(I->getOperand(0)); 17030b57cec5SDimitry Andric if (!BitOp) 17040b57cec5SDimitry Andric return nullptr; 17050b57cec5SDimitry Andric switch (BitOp->getOpcode()) { 17060b57cec5SDimitry Andric case Instruction::And: 17070b57cec5SDimitry Andric case Instruction::Or: 17080b57cec5SDimitry Andric case Instruction::Xor: 17090b57cec5SDimitry Andric break; 17100b57cec5SDimitry Andric default: 17110b57cec5SDimitry Andric return nullptr; 17120b57cec5SDimitry Andric } 17130b57cec5SDimitry Andric IRBuilder<> B(Ctx); 17140b57cec5SDimitry Andric Value *S = I->getOperand(1); 17150b57cec5SDimitry Andric return B.CreateBinOp(BitOp->getOpcode(), 17160b57cec5SDimitry Andric B.CreateLShr(BitOp->getOperand(0), S), 17170b57cec5SDimitry Andric B.CreateLShr(BitOp->getOperand(1), S)); 17180b57cec5SDimitry Andric }); 17190b57cec5SDimitry Andric S.addRule("expose bitop-const", 17200b57cec5SDimitry Andric // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b)) 17210b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 17220b57cec5SDimitry Andric auto IsBitOp = [](unsigned Op) -> bool { 17230b57cec5SDimitry Andric switch (Op) { 17240b57cec5SDimitry Andric case Instruction::And: 17250b57cec5SDimitry Andric case Instruction::Or: 17260b57cec5SDimitry Andric case Instruction::Xor: 17270b57cec5SDimitry Andric return true; 17280b57cec5SDimitry Andric } 17290b57cec5SDimitry Andric return false; 17300b57cec5SDimitry Andric }; 17310b57cec5SDimitry Andric BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I); 17320b57cec5SDimitry Andric if (!BitOp1 || !IsBitOp(BitOp1->getOpcode())) 17330b57cec5SDimitry Andric return nullptr; 17340b57cec5SDimitry Andric BinaryOperator *BitOp2 = dyn_cast<BinaryOperator>(BitOp1->getOperand(0)); 17350b57cec5SDimitry Andric if (!BitOp2 || !IsBitOp(BitOp2->getOpcode())) 17360b57cec5SDimitry Andric return nullptr; 17370b57cec5SDimitry Andric ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1)); 17380b57cec5SDimitry Andric ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1)); 17390b57cec5SDimitry Andric if (!CA || !CB) 17400b57cec5SDimitry Andric return nullptr; 17410b57cec5SDimitry Andric IRBuilder<> B(Ctx); 17420b57cec5SDimitry Andric Value *X = BitOp2->getOperand(0); 17430b57cec5SDimitry Andric return B.CreateBinOp(BitOp2->getOpcode(), X, 17440b57cec5SDimitry Andric B.CreateBinOp(BitOp1->getOpcode(), CA, CB)); 17450b57cec5SDimitry Andric }); 17460b57cec5SDimitry Andric } 17470b57cec5SDimitry Andric 17480b57cec5SDimitry Andric void PolynomialMultiplyRecognize::setupPostSimplifier(Simplifier &S) { 17490b57cec5SDimitry Andric S.addRule("(and (xor (and x a) y) b) -> (and (xor x y) b), if b == b&a", 17500b57cec5SDimitry Andric [](Instruction *I, LLVMContext &Ctx) -> Value* { 17510b57cec5SDimitry Andric if (I->getOpcode() != Instruction::And) 17520b57cec5SDimitry Andric return nullptr; 17530b57cec5SDimitry Andric Instruction *Xor = dyn_cast<Instruction>(I->getOperand(0)); 17540b57cec5SDimitry Andric ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(1)); 17550b57cec5SDimitry Andric if (!Xor || !C0) 17560b57cec5SDimitry Andric return nullptr; 17570b57cec5SDimitry Andric if (Xor->getOpcode() != Instruction::Xor) 17580b57cec5SDimitry Andric return nullptr; 17590b57cec5SDimitry Andric Instruction *And0 = dyn_cast<Instruction>(Xor->getOperand(0)); 17600b57cec5SDimitry Andric Instruction *And1 = dyn_cast<Instruction>(Xor->getOperand(1)); 17610b57cec5SDimitry Andric // Pick the first non-null and. 17620b57cec5SDimitry Andric if (!And0 || And0->getOpcode() != Instruction::And) 17630b57cec5SDimitry Andric std::swap(And0, And1); 17640b57cec5SDimitry Andric ConstantInt *C1 = dyn_cast<ConstantInt>(And0->getOperand(1)); 17650b57cec5SDimitry Andric if (!C1) 17660b57cec5SDimitry Andric return nullptr; 17670b57cec5SDimitry Andric uint32_t V0 = C0->getZExtValue(); 17680b57cec5SDimitry Andric uint32_t V1 = C1->getZExtValue(); 17690b57cec5SDimitry Andric if (V0 != (V0 & V1)) 17700b57cec5SDimitry Andric return nullptr; 17710b57cec5SDimitry Andric IRBuilder<> B(Ctx); 17720b57cec5SDimitry Andric return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1), C0); 17730b57cec5SDimitry Andric }); 17740b57cec5SDimitry Andric } 17750b57cec5SDimitry Andric 17760b57cec5SDimitry Andric bool PolynomialMultiplyRecognize::recognize() { 17770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Starting PolynomialMultiplyRecognize on loop\n" 17780b57cec5SDimitry Andric << *CurLoop << '\n'); 17790b57cec5SDimitry Andric // Restrictions: 17800b57cec5SDimitry Andric // - The loop must consist of a single block. 17810b57cec5SDimitry Andric // - The iteration count must be known at compile-time. 17820b57cec5SDimitry Andric // - The loop must have an induction variable starting from 0, and 17830b57cec5SDimitry Andric // incremented in each iteration of the loop. 17840b57cec5SDimitry Andric BasicBlock *LoopB = CurLoop->getHeader(); 17850b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Loop header:\n" << *LoopB); 17860b57cec5SDimitry Andric 17870b57cec5SDimitry Andric if (LoopB != CurLoop->getLoopLatch()) 17880b57cec5SDimitry Andric return false; 17890b57cec5SDimitry Andric BasicBlock *ExitB = CurLoop->getExitBlock(); 17900b57cec5SDimitry Andric if (ExitB == nullptr) 17910b57cec5SDimitry Andric return false; 17920b57cec5SDimitry Andric BasicBlock *EntryB = CurLoop->getLoopPreheader(); 17930b57cec5SDimitry Andric if (EntryB == nullptr) 17940b57cec5SDimitry Andric return false; 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric unsigned IterCount = 0; 17970b57cec5SDimitry Andric const SCEV *CT = SE.getBackedgeTakenCount(CurLoop); 17980b57cec5SDimitry Andric if (isa<SCEVCouldNotCompute>(CT)) 17990b57cec5SDimitry Andric return false; 18000b57cec5SDimitry Andric if (auto *CV = dyn_cast<SCEVConstant>(CT)) 18010b57cec5SDimitry Andric IterCount = CV->getValue()->getZExtValue() + 1; 18020b57cec5SDimitry Andric 18030b57cec5SDimitry Andric Value *CIV = getCountIV(LoopB); 18040b57cec5SDimitry Andric ParsedValues PV; 18050b57cec5SDimitry Andric Simplifier PreSimp; 18060b57cec5SDimitry Andric PV.IterCount = IterCount; 18070b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Loop IV: " << *CIV << "\nIterCount: " << IterCount 18080b57cec5SDimitry Andric << '\n'); 18090b57cec5SDimitry Andric 18100b57cec5SDimitry Andric setupPreSimplifier(PreSimp); 18110b57cec5SDimitry Andric 18120b57cec5SDimitry Andric // Perform a preliminary scan of select instructions to see if any of them 18130b57cec5SDimitry Andric // looks like a generator of the polynomial multiply steps. Assume that a 18140b57cec5SDimitry Andric // loop can only contain a single transformable operation, so stop the 18150b57cec5SDimitry Andric // traversal after the first reasonable candidate was found. 18160b57cec5SDimitry Andric // XXX: Currently this approach can modify the loop before being 100% sure 18170b57cec5SDimitry Andric // that the transformation can be carried out. 18180b57cec5SDimitry Andric bool FoundPreScan = false; 18190b57cec5SDimitry Andric auto FeedsPHI = [LoopB](const Value *V) -> bool { 18200b57cec5SDimitry Andric for (const Value *U : V->users()) { 18210b57cec5SDimitry Andric if (const auto *P = dyn_cast<const PHINode>(U)) 18220b57cec5SDimitry Andric if (P->getParent() == LoopB) 18230b57cec5SDimitry Andric return true; 18240b57cec5SDimitry Andric } 18250b57cec5SDimitry Andric return false; 18260b57cec5SDimitry Andric }; 18270b57cec5SDimitry Andric for (Instruction &In : *LoopB) { 18280b57cec5SDimitry Andric SelectInst *SI = dyn_cast<SelectInst>(&In); 18290b57cec5SDimitry Andric if (!SI || !FeedsPHI(SI)) 18300b57cec5SDimitry Andric continue; 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric Simplifier::Context C(SI); 18330b57cec5SDimitry Andric Value *T = PreSimp.simplify(C); 18340b57cec5SDimitry Andric SelectInst *SelI = (T && isa<SelectInst>(T)) ? cast<SelectInst>(T) : SI; 18350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n'); 18360b57cec5SDimitry Andric if (scanSelect(SelI, LoopB, EntryB, CIV, PV, true)) { 18370b57cec5SDimitry Andric FoundPreScan = true; 18380b57cec5SDimitry Andric if (SelI != SI) { 18390b57cec5SDimitry Andric Value *NewSel = C.materialize(LoopB, SI->getIterator()); 18400b57cec5SDimitry Andric SI->replaceAllUsesWith(NewSel); 18410b57cec5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(SI, &TLI); 18420b57cec5SDimitry Andric } 18430b57cec5SDimitry Andric break; 18440b57cec5SDimitry Andric } 18450b57cec5SDimitry Andric } 18460b57cec5SDimitry Andric 18470b57cec5SDimitry Andric if (!FoundPreScan) { 18480b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Have not found candidates for pmpy\n"); 18490b57cec5SDimitry Andric return false; 18500b57cec5SDimitry Andric } 18510b57cec5SDimitry Andric 18520b57cec5SDimitry Andric if (!PV.Left) { 18530b57cec5SDimitry Andric // The right shift version actually only returns the higher bits of 18540b57cec5SDimitry Andric // the result (each iteration discards the LSB). If we want to convert it 18550b57cec5SDimitry Andric // to a left-shifting loop, the working data type must be at least as 18560b57cec5SDimitry Andric // wide as the target's pmpy instruction. 18570b57cec5SDimitry Andric if (!promoteTypes(LoopB, ExitB)) 18580b57cec5SDimitry Andric return false; 18590b57cec5SDimitry Andric // Run post-promotion simplifications. 18600b57cec5SDimitry Andric Simplifier PostSimp; 18610b57cec5SDimitry Andric setupPostSimplifier(PostSimp); 18620b57cec5SDimitry Andric for (Instruction &In : *LoopB) { 18630b57cec5SDimitry Andric SelectInst *SI = dyn_cast<SelectInst>(&In); 18640b57cec5SDimitry Andric if (!SI || !FeedsPHI(SI)) 18650b57cec5SDimitry Andric continue; 18660b57cec5SDimitry Andric Simplifier::Context C(SI); 18670b57cec5SDimitry Andric Value *T = PostSimp.simplify(C); 18680b57cec5SDimitry Andric SelectInst *SelI = dyn_cast_or_null<SelectInst>(T); 18690b57cec5SDimitry Andric if (SelI != SI) { 18700b57cec5SDimitry Andric Value *NewSel = C.materialize(LoopB, SI->getIterator()); 18710b57cec5SDimitry Andric SI->replaceAllUsesWith(NewSel); 18720b57cec5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(SI, &TLI); 18730b57cec5SDimitry Andric } 18740b57cec5SDimitry Andric break; 18750b57cec5SDimitry Andric } 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric if (!convertShiftsToLeft(LoopB, ExitB, IterCount)) 18780b57cec5SDimitry Andric return false; 18790b57cec5SDimitry Andric cleanupLoopBody(LoopB); 18800b57cec5SDimitry Andric } 18810b57cec5SDimitry Andric 18820b57cec5SDimitry Andric // Scan the loop again, find the generating select instruction. 18830b57cec5SDimitry Andric bool FoundScan = false; 18840b57cec5SDimitry Andric for (Instruction &In : *LoopB) { 18850b57cec5SDimitry Andric SelectInst *SelI = dyn_cast<SelectInst>(&In); 18860b57cec5SDimitry Andric if (!SelI) 18870b57cec5SDimitry Andric continue; 18880b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "scanSelect: " << *SelI << '\n'); 18890b57cec5SDimitry Andric FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV, false); 18900b57cec5SDimitry Andric if (FoundScan) 18910b57cec5SDimitry Andric break; 18920b57cec5SDimitry Andric } 18930b57cec5SDimitry Andric assert(FoundScan); 18940b57cec5SDimitry Andric 18950b57cec5SDimitry Andric LLVM_DEBUG({ 18960b57cec5SDimitry Andric StringRef PP = (PV.M ? "(P+M)" : "P"); 18970b57cec5SDimitry Andric if (!PV.Inv) 18980b57cec5SDimitry Andric dbgs() << "Found pmpy idiom: R = " << PP << ".Q\n"; 18990b57cec5SDimitry Andric else 19000b57cec5SDimitry Andric dbgs() << "Found inverse pmpy idiom: R = (" << PP << "/Q).Q) + " 19010b57cec5SDimitry Andric << PP << "\n"; 19020b57cec5SDimitry Andric dbgs() << " Res:" << *PV.Res << "\n P:" << *PV.P << "\n"; 19030b57cec5SDimitry Andric if (PV.M) 19040b57cec5SDimitry Andric dbgs() << " M:" << *PV.M << "\n"; 19050b57cec5SDimitry Andric dbgs() << " Q:" << *PV.Q << "\n"; 19060b57cec5SDimitry Andric dbgs() << " Iteration count:" << PV.IterCount << "\n"; 19070b57cec5SDimitry Andric }); 19080b57cec5SDimitry Andric 19090b57cec5SDimitry Andric BasicBlock::iterator At(EntryB->getTerminator()); 19100b57cec5SDimitry Andric Value *PM = generate(At, PV); 19110b57cec5SDimitry Andric if (PM == nullptr) 19120b57cec5SDimitry Andric return false; 19130b57cec5SDimitry Andric 19140b57cec5SDimitry Andric if (PM->getType() != PV.Res->getType()) 19150b57cec5SDimitry Andric PM = IRBuilder<>(&*At).CreateIntCast(PM, PV.Res->getType(), false); 19160b57cec5SDimitry Andric 19170b57cec5SDimitry Andric PV.Res->replaceAllUsesWith(PM); 19180b57cec5SDimitry Andric PV.Res->eraseFromParent(); 19190b57cec5SDimitry Andric return true; 19200b57cec5SDimitry Andric } 19210b57cec5SDimitry Andric 19220b57cec5SDimitry Andric int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) { 19230b57cec5SDimitry Andric if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(1))) 19240b57cec5SDimitry Andric return SC->getAPInt().getSExtValue(); 19250b57cec5SDimitry Andric return 0; 19260b57cec5SDimitry Andric } 19270b57cec5SDimitry Andric 19280b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::isLegalStore(Loop *CurLoop, StoreInst *SI) { 19290b57cec5SDimitry Andric // Allow volatile stores if HexagonVolatileMemcpy is enabled. 19300b57cec5SDimitry Andric if (!(SI->isVolatile() && HexagonVolatileMemcpy) && !SI->isSimple()) 19310b57cec5SDimitry Andric return false; 19320b57cec5SDimitry Andric 19330b57cec5SDimitry Andric Value *StoredVal = SI->getValueOperand(); 19340b57cec5SDimitry Andric Value *StorePtr = SI->getPointerOperand(); 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric // Reject stores that are so large that they overflow an unsigned. 19370b57cec5SDimitry Andric uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); 19380b57cec5SDimitry Andric if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) 19390b57cec5SDimitry Andric return false; 19400b57cec5SDimitry Andric 19410b57cec5SDimitry Andric // See if the pointer expression is an AddRec like {base,+,1} on the current 19420b57cec5SDimitry Andric // loop, which indicates a strided store. If we have something else, it's a 19430b57cec5SDimitry Andric // random store we can't handle. 19440b57cec5SDimitry Andric auto *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 19450b57cec5SDimitry Andric if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) 19460b57cec5SDimitry Andric return false; 19470b57cec5SDimitry Andric 19480b57cec5SDimitry Andric // Check to see if the stride matches the size of the store. If so, then we 19490b57cec5SDimitry Andric // know that every byte is touched in the loop. 19500b57cec5SDimitry Andric int Stride = getSCEVStride(StoreEv); 19510b57cec5SDimitry Andric if (Stride == 0) 19520b57cec5SDimitry Andric return false; 19530b57cec5SDimitry Andric unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 19540b57cec5SDimitry Andric if (StoreSize != unsigned(std::abs(Stride))) 19550b57cec5SDimitry Andric return false; 19560b57cec5SDimitry Andric 19570b57cec5SDimitry Andric // The store must be feeding a non-volatile load. 19580b57cec5SDimitry Andric LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); 19590b57cec5SDimitry Andric if (!LI || !LI->isSimple()) 19600b57cec5SDimitry Andric return false; 19610b57cec5SDimitry Andric 19620b57cec5SDimitry Andric // See if the pointer expression is an AddRec like {base,+,1} on the current 19630b57cec5SDimitry Andric // loop, which indicates a strided load. If we have something else, it's a 19640b57cec5SDimitry Andric // random load we can't handle. 19650b57cec5SDimitry Andric Value *LoadPtr = LI->getPointerOperand(); 19660b57cec5SDimitry Andric auto *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr)); 19670b57cec5SDimitry Andric if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) 19680b57cec5SDimitry Andric return false; 19690b57cec5SDimitry Andric 19700b57cec5SDimitry Andric // The store and load must share the same stride. 19710b57cec5SDimitry Andric if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) 19720b57cec5SDimitry Andric return false; 19730b57cec5SDimitry Andric 19740b57cec5SDimitry Andric // Success. This store can be converted into a memcpy. 19750b57cec5SDimitry Andric return true; 19760b57cec5SDimitry Andric } 19770b57cec5SDimitry Andric 19780b57cec5SDimitry Andric /// mayLoopAccessLocation - Return true if the specified loop might access the 19790b57cec5SDimitry Andric /// specified pointer location, which is a loop-strided access. The 'Access' 19800b57cec5SDimitry Andric /// argument specifies what the verboten forms of access are (read or write). 19810b57cec5SDimitry Andric static bool 19820b57cec5SDimitry Andric mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, 19830b57cec5SDimitry Andric const SCEV *BECount, unsigned StoreSize, 19840b57cec5SDimitry Andric AliasAnalysis &AA, 19850b57cec5SDimitry Andric SmallPtrSetImpl<Instruction *> &Ignored) { 19860b57cec5SDimitry Andric // Get the location that may be stored across the loop. Since the access 19870b57cec5SDimitry Andric // is strided positively through memory, we say that the modified location 19880b57cec5SDimitry Andric // starts at the pointer and has infinite size. 1989e8d8bef9SDimitry Andric LocationSize AccessSize = LocationSize::afterPointer(); 19900b57cec5SDimitry Andric 19910b57cec5SDimitry Andric // If the loop iterates a fixed number of times, we can refine the access 19920b57cec5SDimitry Andric // size to be exactly the size of the memset, which is (BECount+1)*StoreSize 19930b57cec5SDimitry Andric if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) 19940b57cec5SDimitry Andric AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) * 19950b57cec5SDimitry Andric StoreSize); 19960b57cec5SDimitry Andric 19970b57cec5SDimitry Andric // TODO: For this to be really effective, we have to dive into the pointer 19980b57cec5SDimitry Andric // operand in the store. Store to &A[i] of 100 will always return may alias 19990b57cec5SDimitry Andric // with store of &A[100], we need to StoreLoc to be "A" with size of 100, 20000b57cec5SDimitry Andric // which will then no-alias a store to &A[100]. 20010b57cec5SDimitry Andric MemoryLocation StoreLoc(Ptr, AccessSize); 20020b57cec5SDimitry Andric 20030b57cec5SDimitry Andric for (auto *B : L->blocks()) 20040b57cec5SDimitry Andric for (auto &I : *B) 20050b57cec5SDimitry Andric if (Ignored.count(&I) == 0 && 2006bdd1243dSDimitry Andric isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access)) 20070b57cec5SDimitry Andric return true; 20080b57cec5SDimitry Andric 20090b57cec5SDimitry Andric return false; 20100b57cec5SDimitry Andric } 20110b57cec5SDimitry Andric 20120b57cec5SDimitry Andric void HexagonLoopIdiomRecognize::collectStores(Loop *CurLoop, BasicBlock *BB, 20130b57cec5SDimitry Andric SmallVectorImpl<StoreInst*> &Stores) { 20140b57cec5SDimitry Andric Stores.clear(); 20150b57cec5SDimitry Andric for (Instruction &I : *BB) 20160b57cec5SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 20170b57cec5SDimitry Andric if (isLegalStore(CurLoop, SI)) 20180b57cec5SDimitry Andric Stores.push_back(SI); 20190b57cec5SDimitry Andric } 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::processCopyingStore(Loop *CurLoop, 20220b57cec5SDimitry Andric StoreInst *SI, const SCEV *BECount) { 20230b57cec5SDimitry Andric assert((SI->isSimple() || (SI->isVolatile() && HexagonVolatileMemcpy)) && 20240b57cec5SDimitry Andric "Expected only non-volatile stores, or Hexagon-specific memcpy" 20250b57cec5SDimitry Andric "to volatile destination."); 20260b57cec5SDimitry Andric 20270b57cec5SDimitry Andric Value *StorePtr = SI->getPointerOperand(); 20280b57cec5SDimitry Andric auto *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); 20290b57cec5SDimitry Andric unsigned Stride = getSCEVStride(StoreEv); 20300b57cec5SDimitry Andric unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType()); 20310b57cec5SDimitry Andric if (Stride != StoreSize) 20320b57cec5SDimitry Andric return false; 20330b57cec5SDimitry Andric 20340b57cec5SDimitry Andric // See if the pointer expression is an AddRec like {base,+,1} on the current 20350b57cec5SDimitry Andric // loop, which indicates a strided load. If we have something else, it's a 20360b57cec5SDimitry Andric // random load we can't handle. 20378bcb0991SDimitry Andric auto *LI = cast<LoadInst>(SI->getValueOperand()); 20380b57cec5SDimitry Andric auto *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); 20390b57cec5SDimitry Andric 20400b57cec5SDimitry Andric // The trip count of the loop and the base pointer of the addrec SCEV is 20410b57cec5SDimitry Andric // guaranteed to be loop invariant, which means that it should dominate the 20420b57cec5SDimitry Andric // header. This allows us to insert code for it in the preheader. 20430b57cec5SDimitry Andric BasicBlock *Preheader = CurLoop->getLoopPreheader(); 20440b57cec5SDimitry Andric Instruction *ExpPt = Preheader->getTerminator(); 20450b57cec5SDimitry Andric IRBuilder<> Builder(ExpPt); 20460b57cec5SDimitry Andric SCEVExpander Expander(*SE, *DL, "hexagon-loop-idiom"); 20470b57cec5SDimitry Andric 20480b57cec5SDimitry Andric Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace()); 20490b57cec5SDimitry Andric 20500b57cec5SDimitry Andric // Okay, we have a strided store "p[i]" of a loaded value. We can turn 20510b57cec5SDimitry Andric // this into a memcpy/memmove in the loop preheader now if we want. However, 20520b57cec5SDimitry Andric // this would be unsafe to do if there is anything else in the loop that may 20530b57cec5SDimitry Andric // read or write the memory region we're storing to. For memcpy, this 20540b57cec5SDimitry Andric // includes the load that feeds the stores. Check for an alias by generating 20550b57cec5SDimitry Andric // the base address and checking everything. 20560b57cec5SDimitry Andric Value *StoreBasePtr = Expander.expandCodeFor(StoreEv->getStart(), 20575f757f3fSDimitry Andric Builder.getPtrTy(SI->getPointerAddressSpace()), ExpPt); 20580b57cec5SDimitry Andric Value *LoadBasePtr = nullptr; 20590b57cec5SDimitry Andric 20600b57cec5SDimitry Andric bool Overlap = false; 20610b57cec5SDimitry Andric bool DestVolatile = SI->isVolatile(); 20620b57cec5SDimitry Andric Type *BECountTy = BECount->getType(); 20630b57cec5SDimitry Andric 20640b57cec5SDimitry Andric if (DestVolatile) { 20650b57cec5SDimitry Andric // The trip count must fit in i32, since it is the type of the "num_words" 20660b57cec5SDimitry Andric // argument to hexagon_memcpy_forward_vp4cp4n2. 20670b57cec5SDimitry Andric if (StoreSize != 4 || DL->getTypeSizeInBits(BECountTy) > 32) { 20680b57cec5SDimitry Andric CleanupAndExit: 20690b57cec5SDimitry Andric // If we generated new code for the base pointer, clean up. 20700b57cec5SDimitry Andric Expander.clear(); 20710b57cec5SDimitry Andric if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) { 20720b57cec5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); 20730b57cec5SDimitry Andric StoreBasePtr = nullptr; 20740b57cec5SDimitry Andric } 20750b57cec5SDimitry Andric if (LoadBasePtr) { 20760b57cec5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); 20770b57cec5SDimitry Andric LoadBasePtr = nullptr; 20780b57cec5SDimitry Andric } 20790b57cec5SDimitry Andric return false; 20800b57cec5SDimitry Andric } 20810b57cec5SDimitry Andric } 20820b57cec5SDimitry Andric 20830b57cec5SDimitry Andric SmallPtrSet<Instruction*, 2> Ignore1; 20840b57cec5SDimitry Andric Ignore1.insert(SI); 20850b57cec5SDimitry Andric if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount, 20860b57cec5SDimitry Andric StoreSize, *AA, Ignore1)) { 20870b57cec5SDimitry Andric // Check if the load is the offending instruction. 20880b57cec5SDimitry Andric Ignore1.insert(LI); 20890b57cec5SDimitry Andric if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, 20900b57cec5SDimitry Andric BECount, StoreSize, *AA, Ignore1)) { 20910b57cec5SDimitry Andric // Still bad. Nothing we can do. 20920b57cec5SDimitry Andric goto CleanupAndExit; 20930b57cec5SDimitry Andric } 20940b57cec5SDimitry Andric // It worked with the load ignored. 20950b57cec5SDimitry Andric Overlap = true; 20960b57cec5SDimitry Andric } 20970b57cec5SDimitry Andric 20980b57cec5SDimitry Andric if (!Overlap) { 20990b57cec5SDimitry Andric if (DisableMemcpyIdiom || !HasMemcpy) 21000b57cec5SDimitry Andric goto CleanupAndExit; 21010b57cec5SDimitry Andric } else { 21020b57cec5SDimitry Andric // Don't generate memmove if this function will be inlined. This is 21030b57cec5SDimitry Andric // because the caller will undergo this transformation after inlining. 21040b57cec5SDimitry Andric Function *Func = CurLoop->getHeader()->getParent(); 21050b57cec5SDimitry Andric if (Func->hasFnAttribute(Attribute::AlwaysInline)) 21060b57cec5SDimitry Andric goto CleanupAndExit; 21070b57cec5SDimitry Andric 21080b57cec5SDimitry Andric // In case of a memmove, the call to memmove will be executed instead 21090b57cec5SDimitry Andric // of the loop, so we need to make sure that there is nothing else in 21100b57cec5SDimitry Andric // the loop than the load, store and instructions that these two depend 21110b57cec5SDimitry Andric // on. 21120b57cec5SDimitry Andric SmallVector<Instruction*,2> Insts; 21130b57cec5SDimitry Andric Insts.push_back(SI); 21140b57cec5SDimitry Andric Insts.push_back(LI); 21150b57cec5SDimitry Andric if (!coverLoop(CurLoop, Insts)) 21160b57cec5SDimitry Andric goto CleanupAndExit; 21170b57cec5SDimitry Andric 21180b57cec5SDimitry Andric if (DisableMemmoveIdiom || !HasMemmove) 21190b57cec5SDimitry Andric goto CleanupAndExit; 21200b57cec5SDimitry Andric bool IsNested = CurLoop->getParentLoop() != nullptr; 21210b57cec5SDimitry Andric if (IsNested && OnlyNonNestedMemmove) 21220b57cec5SDimitry Andric goto CleanupAndExit; 21230b57cec5SDimitry Andric } 21240b57cec5SDimitry Andric 21250b57cec5SDimitry Andric // For a memcpy, we have to make sure that the input array is not being 21260b57cec5SDimitry Andric // mutated by the loop. 21270b57cec5SDimitry Andric LoadBasePtr = Expander.expandCodeFor(LoadEv->getStart(), 21285f757f3fSDimitry Andric Builder.getPtrTy(LI->getPointerAddressSpace()), ExpPt); 21290b57cec5SDimitry Andric 21300b57cec5SDimitry Andric SmallPtrSet<Instruction*, 2> Ignore2; 21310b57cec5SDimitry Andric Ignore2.insert(SI); 21320b57cec5SDimitry Andric if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount, 21330b57cec5SDimitry Andric StoreSize, *AA, Ignore2)) 21340b57cec5SDimitry Andric goto CleanupAndExit; 21350b57cec5SDimitry Andric 21360b57cec5SDimitry Andric // Check the stride. 21370b57cec5SDimitry Andric bool StridePos = getSCEVStride(LoadEv) >= 0; 21380b57cec5SDimitry Andric 21390b57cec5SDimitry Andric // Currently, the volatile memcpy only emulates traversing memory forward. 21400b57cec5SDimitry Andric if (!StridePos && DestVolatile) 21410b57cec5SDimitry Andric goto CleanupAndExit; 21420b57cec5SDimitry Andric 21430b57cec5SDimitry Andric bool RuntimeCheck = (Overlap || DestVolatile); 21440b57cec5SDimitry Andric 21450b57cec5SDimitry Andric BasicBlock *ExitB; 21460b57cec5SDimitry Andric if (RuntimeCheck) { 21470b57cec5SDimitry Andric // The runtime check needs a single exit block. 21480b57cec5SDimitry Andric SmallVector<BasicBlock*, 8> ExitBlocks; 21490b57cec5SDimitry Andric CurLoop->getUniqueExitBlocks(ExitBlocks); 21500b57cec5SDimitry Andric if (ExitBlocks.size() != 1) 21510b57cec5SDimitry Andric goto CleanupAndExit; 21520b57cec5SDimitry Andric ExitB = ExitBlocks[0]; 21530b57cec5SDimitry Andric } 21540b57cec5SDimitry Andric 21550b57cec5SDimitry Andric // The # stored bytes is (BECount+1)*Size. Expand the trip count out to 21560b57cec5SDimitry Andric // pointer size if it isn't already. 21570b57cec5SDimitry Andric LLVMContext &Ctx = SI->getContext(); 21580b57cec5SDimitry Andric BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); 21590b57cec5SDimitry Andric DebugLoc DLoc = SI->getDebugLoc(); 21600b57cec5SDimitry Andric 21610b57cec5SDimitry Andric const SCEV *NumBytesS = 21620b57cec5SDimitry Andric SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW); 21630b57cec5SDimitry Andric if (StoreSize != 1) 21640b57cec5SDimitry Andric NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), 21650b57cec5SDimitry Andric SCEV::FlagNUW); 21660b57cec5SDimitry Andric Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt); 21670b57cec5SDimitry Andric if (Instruction *In = dyn_cast<Instruction>(NumBytes)) 216881ad6265SDimitry Andric if (Value *Simp = simplifyInstruction(In, {*DL, TLI, DT})) 21690b57cec5SDimitry Andric NumBytes = Simp; 21700b57cec5SDimitry Andric 21710b57cec5SDimitry Andric CallInst *NewCall; 21720b57cec5SDimitry Andric 21730b57cec5SDimitry Andric if (RuntimeCheck) { 21740b57cec5SDimitry Andric unsigned Threshold = RuntimeMemSizeThreshold; 21750b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) { 21760b57cec5SDimitry Andric uint64_t C = CI->getZExtValue(); 21770b57cec5SDimitry Andric if (Threshold != 0 && C < Threshold) 21780b57cec5SDimitry Andric goto CleanupAndExit; 21790b57cec5SDimitry Andric if (C < CompileTimeMemSizeThreshold) 21800b57cec5SDimitry Andric goto CleanupAndExit; 21810b57cec5SDimitry Andric } 21820b57cec5SDimitry Andric 21830b57cec5SDimitry Andric BasicBlock *Header = CurLoop->getHeader(); 21840b57cec5SDimitry Andric Function *Func = Header->getParent(); 21850b57cec5SDimitry Andric Loop *ParentL = LF->getLoopFor(Preheader); 21860b57cec5SDimitry Andric StringRef HeaderName = Header->getName(); 21870b57cec5SDimitry Andric 21880b57cec5SDimitry Andric // Create a new (empty) preheader, and update the PHI nodes in the 21890b57cec5SDimitry Andric // header to use the new preheader. 21900b57cec5SDimitry Andric BasicBlock *NewPreheader = BasicBlock::Create(Ctx, HeaderName+".rtli.ph", 21910b57cec5SDimitry Andric Func, Header); 21920b57cec5SDimitry Andric if (ParentL) 21930b57cec5SDimitry Andric ParentL->addBasicBlockToLoop(NewPreheader, *LF); 21940b57cec5SDimitry Andric IRBuilder<>(NewPreheader).CreateBr(Header); 21950b57cec5SDimitry Andric for (auto &In : *Header) { 21960b57cec5SDimitry Andric PHINode *PN = dyn_cast<PHINode>(&In); 21970b57cec5SDimitry Andric if (!PN) 21980b57cec5SDimitry Andric break; 21990b57cec5SDimitry Andric int bx = PN->getBasicBlockIndex(Preheader); 22000b57cec5SDimitry Andric if (bx >= 0) 22010b57cec5SDimitry Andric PN->setIncomingBlock(bx, NewPreheader); 22020b57cec5SDimitry Andric } 22030b57cec5SDimitry Andric DT->addNewBlock(NewPreheader, Preheader); 22040b57cec5SDimitry Andric DT->changeImmediateDominator(Header, NewPreheader); 22050b57cec5SDimitry Andric 22060b57cec5SDimitry Andric // Check for safe conditions to execute memmove. 22070b57cec5SDimitry Andric // If stride is positive, copying things from higher to lower addresses 22080b57cec5SDimitry Andric // is equivalent to memmove. For negative stride, it's the other way 22090b57cec5SDimitry Andric // around. Copying forward in memory with positive stride may not be 22100b57cec5SDimitry Andric // same as memmove since we may be copying values that we just stored 22110b57cec5SDimitry Andric // in some previous iteration. 22120b57cec5SDimitry Andric Value *LA = Builder.CreatePtrToInt(LoadBasePtr, IntPtrTy); 22130b57cec5SDimitry Andric Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy); 22140b57cec5SDimitry Andric Value *LowA = StridePos ? SA : LA; 22150b57cec5SDimitry Andric Value *HighA = StridePos ? LA : SA; 22160b57cec5SDimitry Andric Value *CmpA = Builder.CreateICmpULT(LowA, HighA); 22170b57cec5SDimitry Andric Value *Cond = CmpA; 22180b57cec5SDimitry Andric 22190b57cec5SDimitry Andric // Check for distance between pointers. Since the case LowA < HighA 22200b57cec5SDimitry Andric // is checked for above, assume LowA >= HighA. 22210b57cec5SDimitry Andric Value *Dist = Builder.CreateSub(LowA, HighA); 22220b57cec5SDimitry Andric Value *CmpD = Builder.CreateICmpSLE(NumBytes, Dist); 22230b57cec5SDimitry Andric Value *CmpEither = Builder.CreateOr(Cond, CmpD); 22240b57cec5SDimitry Andric Cond = CmpEither; 22250b57cec5SDimitry Andric 22260b57cec5SDimitry Andric if (Threshold != 0) { 22270b57cec5SDimitry Andric Type *Ty = NumBytes->getType(); 22280b57cec5SDimitry Andric Value *Thr = ConstantInt::get(Ty, Threshold); 22290b57cec5SDimitry Andric Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes); 22300b57cec5SDimitry Andric Value *CmpBoth = Builder.CreateAnd(Cond, CmpB); 22310b57cec5SDimitry Andric Cond = CmpBoth; 22320b57cec5SDimitry Andric } 22330b57cec5SDimitry Andric BasicBlock *MemmoveB = BasicBlock::Create(Ctx, Header->getName()+".rtli", 22340b57cec5SDimitry Andric Func, NewPreheader); 22350b57cec5SDimitry Andric if (ParentL) 22360b57cec5SDimitry Andric ParentL->addBasicBlockToLoop(MemmoveB, *LF); 22370b57cec5SDimitry Andric Instruction *OldT = Preheader->getTerminator(); 22380b57cec5SDimitry Andric Builder.CreateCondBr(Cond, MemmoveB, NewPreheader); 22390b57cec5SDimitry Andric OldT->eraseFromParent(); 22400b57cec5SDimitry Andric Preheader->setName(Preheader->getName()+".old"); 22410b57cec5SDimitry Andric DT->addNewBlock(MemmoveB, Preheader); 22420b57cec5SDimitry Andric // Find the new immediate dominator of the exit block. 22430b57cec5SDimitry Andric BasicBlock *ExitD = Preheader; 2244349cc55cSDimitry Andric for (BasicBlock *PB : predecessors(ExitB)) { 22450b57cec5SDimitry Andric ExitD = DT->findNearestCommonDominator(ExitD, PB); 22460b57cec5SDimitry Andric if (!ExitD) 22470b57cec5SDimitry Andric break; 22480b57cec5SDimitry Andric } 22490b57cec5SDimitry Andric // If the prior immediate dominator of ExitB was dominated by the 22500b57cec5SDimitry Andric // old preheader, then the old preheader becomes the new immediate 22510b57cec5SDimitry Andric // dominator. Otherwise don't change anything (because the newly 22520b57cec5SDimitry Andric // added blocks are dominated by the old preheader). 22530b57cec5SDimitry Andric if (ExitD && DT->dominates(Preheader, ExitD)) { 22540b57cec5SDimitry Andric DomTreeNode *BN = DT->getNode(ExitB); 22550b57cec5SDimitry Andric DomTreeNode *DN = DT->getNode(ExitD); 22560b57cec5SDimitry Andric BN->setIDom(DN); 22570b57cec5SDimitry Andric } 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric // Add a call to memmove to the conditional block. 22600b57cec5SDimitry Andric IRBuilder<> CondBuilder(MemmoveB); 22610b57cec5SDimitry Andric CondBuilder.CreateBr(ExitB); 22620b57cec5SDimitry Andric CondBuilder.SetInsertPoint(MemmoveB->getTerminator()); 22630b57cec5SDimitry Andric 22640b57cec5SDimitry Andric if (DestVolatile) { 22650b57cec5SDimitry Andric Type *Int32Ty = Type::getInt32Ty(Ctx); 22665f757f3fSDimitry Andric Type *PtrTy = PointerType::get(Ctx, 0); 22670b57cec5SDimitry Andric Type *VoidTy = Type::getVoidTy(Ctx); 22680b57cec5SDimitry Andric Module *M = Func->getParent(); 22690b57cec5SDimitry Andric FunctionCallee Fn = M->getOrInsertFunction( 22705f757f3fSDimitry Andric HexagonVolatileMemcpyName, VoidTy, PtrTy, PtrTy, Int32Ty); 22710b57cec5SDimitry Andric 22720b57cec5SDimitry Andric const SCEV *OneS = SE->getConstant(Int32Ty, 1); 22730b57cec5SDimitry Andric const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty); 22740b57cec5SDimitry Andric const SCEV *NumWordsS = SE->getAddExpr(BECount32, OneS, SCEV::FlagNUW); 22750b57cec5SDimitry Andric Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty, 22760b57cec5SDimitry Andric MemmoveB->getTerminator()); 22770b57cec5SDimitry Andric if (Instruction *In = dyn_cast<Instruction>(NumWords)) 227881ad6265SDimitry Andric if (Value *Simp = simplifyInstruction(In, {*DL, TLI, DT})) 22790b57cec5SDimitry Andric NumWords = Simp; 22800b57cec5SDimitry Andric 22815f757f3fSDimitry Andric NewCall = CondBuilder.CreateCall(Fn, 22825f757f3fSDimitry Andric {StoreBasePtr, LoadBasePtr, NumWords}); 22830b57cec5SDimitry Andric } else { 2284480093f4SDimitry Andric NewCall = CondBuilder.CreateMemMove( 2285480093f4SDimitry Andric StoreBasePtr, SI->getAlign(), LoadBasePtr, LI->getAlign(), NumBytes); 22860b57cec5SDimitry Andric } 22870b57cec5SDimitry Andric } else { 2288480093f4SDimitry Andric NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlign(), LoadBasePtr, 2289480093f4SDimitry Andric LI->getAlign(), NumBytes); 22900b57cec5SDimitry Andric // Okay, the memcpy has been formed. Zap the original store and 22910b57cec5SDimitry Andric // anything that feeds into it. 22920b57cec5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(SI, TLI); 22930b57cec5SDimitry Andric } 22940b57cec5SDimitry Andric 22950b57cec5SDimitry Andric NewCall->setDebugLoc(DLoc); 22960b57cec5SDimitry Andric 22970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Formed " << (Overlap ? "memmove: " : "memcpy: ") 22980b57cec5SDimitry Andric << *NewCall << "\n" 22990b57cec5SDimitry Andric << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" 23000b57cec5SDimitry Andric << " from store ptr=" << *StoreEv << " at: " << *SI 23010b57cec5SDimitry Andric << "\n"); 23020b57cec5SDimitry Andric 23030b57cec5SDimitry Andric return true; 23040b57cec5SDimitry Andric } 23050b57cec5SDimitry Andric 23060b57cec5SDimitry Andric // Check if the instructions in Insts, together with their dependencies 23070b57cec5SDimitry Andric // cover the loop in the sense that the loop could be safely eliminated once 23080b57cec5SDimitry Andric // the instructions in Insts are removed. 23090b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::coverLoop(Loop *L, 23100b57cec5SDimitry Andric SmallVectorImpl<Instruction*> &Insts) const { 23110b57cec5SDimitry Andric SmallSet<BasicBlock*,8> LoopBlocks; 23120b57cec5SDimitry Andric for (auto *B : L->blocks()) 23130b57cec5SDimitry Andric LoopBlocks.insert(B); 23140b57cec5SDimitry Andric 23150b57cec5SDimitry Andric SetVector<Instruction*> Worklist(Insts.begin(), Insts.end()); 23160b57cec5SDimitry Andric 23170b57cec5SDimitry Andric // Collect all instructions from the loop that the instructions in Insts 23180b57cec5SDimitry Andric // depend on (plus their dependencies, etc.). These instructions will 23190b57cec5SDimitry Andric // constitute the expression trees that feed those in Insts, but the trees 23200b57cec5SDimitry Andric // will be limited only to instructions contained in the loop. 23210b57cec5SDimitry Andric for (unsigned i = 0; i < Worklist.size(); ++i) { 23220b57cec5SDimitry Andric Instruction *In = Worklist[i]; 23230b57cec5SDimitry Andric for (auto I = In->op_begin(), E = In->op_end(); I != E; ++I) { 23240b57cec5SDimitry Andric Instruction *OpI = dyn_cast<Instruction>(I); 23250b57cec5SDimitry Andric if (!OpI) 23260b57cec5SDimitry Andric continue; 23270b57cec5SDimitry Andric BasicBlock *PB = OpI->getParent(); 23280b57cec5SDimitry Andric if (!LoopBlocks.count(PB)) 23290b57cec5SDimitry Andric continue; 23300b57cec5SDimitry Andric Worklist.insert(OpI); 23310b57cec5SDimitry Andric } 23320b57cec5SDimitry Andric } 23330b57cec5SDimitry Andric 23340b57cec5SDimitry Andric // Scan all instructions in the loop, if any of them have a user outside 23350b57cec5SDimitry Andric // of the loop, or outside of the expressions collected above, then either 23360b57cec5SDimitry Andric // the loop has a side-effect visible outside of it, or there are 23370b57cec5SDimitry Andric // instructions in it that are not involved in the original set Insts. 23380b57cec5SDimitry Andric for (auto *B : L->blocks()) { 23390b57cec5SDimitry Andric for (auto &In : *B) { 23400b57cec5SDimitry Andric if (isa<BranchInst>(In) || isa<DbgInfoIntrinsic>(In)) 23410b57cec5SDimitry Andric continue; 23420b57cec5SDimitry Andric if (!Worklist.count(&In) && In.mayHaveSideEffects()) 23430b57cec5SDimitry Andric return false; 2344bdd1243dSDimitry Andric for (auto *K : In.users()) { 23450b57cec5SDimitry Andric Instruction *UseI = dyn_cast<Instruction>(K); 23460b57cec5SDimitry Andric if (!UseI) 23470b57cec5SDimitry Andric continue; 23480b57cec5SDimitry Andric BasicBlock *UseB = UseI->getParent(); 23490b57cec5SDimitry Andric if (LF->getLoopFor(UseB) != L) 23500b57cec5SDimitry Andric return false; 23510b57cec5SDimitry Andric } 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric } 23540b57cec5SDimitry Andric 23550b57cec5SDimitry Andric return true; 23560b57cec5SDimitry Andric } 23570b57cec5SDimitry Andric 23580b57cec5SDimitry Andric /// runOnLoopBlock - Process the specified block, which lives in a counted loop 23590b57cec5SDimitry Andric /// with the specified backedge count. This block is known to be in the current 23600b57cec5SDimitry Andric /// loop and not in any subloops. 23610b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, 23620b57cec5SDimitry Andric const SCEV *BECount, SmallVectorImpl<BasicBlock*> &ExitBlocks) { 23630b57cec5SDimitry Andric // We can only promote stores in this block if they are unconditionally 23640b57cec5SDimitry Andric // executed in the loop. For a block to be unconditionally executed, it has 23650b57cec5SDimitry Andric // to dominate all the exit blocks of the loop. Verify this now. 23660b57cec5SDimitry Andric auto DominatedByBB = [this,BB] (BasicBlock *EB) -> bool { 23670b57cec5SDimitry Andric return DT->dominates(BB, EB); 23680b57cec5SDimitry Andric }; 23690b57cec5SDimitry Andric if (!all_of(ExitBlocks, DominatedByBB)) 23700b57cec5SDimitry Andric return false; 23710b57cec5SDimitry Andric 23720b57cec5SDimitry Andric bool MadeChange = false; 23730b57cec5SDimitry Andric // Look for store instructions, which may be optimized to memset/memcpy. 23740b57cec5SDimitry Andric SmallVector<StoreInst*,8> Stores; 23750b57cec5SDimitry Andric collectStores(CurLoop, BB, Stores); 23760b57cec5SDimitry Andric 23770b57cec5SDimitry Andric // Optimize the store into a memcpy, if it feeds an similarly strided load. 23780b57cec5SDimitry Andric for (auto &SI : Stores) 23790b57cec5SDimitry Andric MadeChange |= processCopyingStore(CurLoop, SI, BECount); 23800b57cec5SDimitry Andric 23810b57cec5SDimitry Andric return MadeChange; 23820b57cec5SDimitry Andric } 23830b57cec5SDimitry Andric 23840b57cec5SDimitry Andric bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) { 23850b57cec5SDimitry Andric PolynomialMultiplyRecognize PMR(L, *DL, *DT, *TLI, *SE); 23860b57cec5SDimitry Andric if (PMR.recognize()) 23870b57cec5SDimitry Andric return true; 23880b57cec5SDimitry Andric 23890b57cec5SDimitry Andric if (!HasMemcpy && !HasMemmove) 23900b57cec5SDimitry Andric return false; 23910b57cec5SDimitry Andric 23920b57cec5SDimitry Andric const SCEV *BECount = SE->getBackedgeTakenCount(L); 23930b57cec5SDimitry Andric assert(!isa<SCEVCouldNotCompute>(BECount) && 23940b57cec5SDimitry Andric "runOnCountableLoop() called on a loop without a predictable" 23950b57cec5SDimitry Andric "backedge-taken count"); 23960b57cec5SDimitry Andric 23970b57cec5SDimitry Andric SmallVector<BasicBlock *, 8> ExitBlocks; 23980b57cec5SDimitry Andric L->getUniqueExitBlocks(ExitBlocks); 23990b57cec5SDimitry Andric 24000b57cec5SDimitry Andric bool Changed = false; 24010b57cec5SDimitry Andric 24020b57cec5SDimitry Andric // Scan all the blocks in the loop that are not in subloops. 24030b57cec5SDimitry Andric for (auto *BB : L->getBlocks()) { 24040b57cec5SDimitry Andric // Ignore blocks in subloops. 24050b57cec5SDimitry Andric if (LF->getLoopFor(BB) != L) 24060b57cec5SDimitry Andric continue; 24070b57cec5SDimitry Andric Changed |= runOnLoopBlock(L, BB, BECount, ExitBlocks); 24080b57cec5SDimitry Andric } 24090b57cec5SDimitry Andric 24100b57cec5SDimitry Andric return Changed; 24110b57cec5SDimitry Andric } 24120b57cec5SDimitry Andric 2413e8d8bef9SDimitry Andric bool HexagonLoopIdiomRecognize::run(Loop *L) { 24140b57cec5SDimitry Andric const Module &M = *L->getHeader()->getParent()->getParent(); 24150b57cec5SDimitry Andric if (Triple(M.getTargetTriple()).getArch() != Triple::hexagon) 24160b57cec5SDimitry Andric return false; 24170b57cec5SDimitry Andric 24180b57cec5SDimitry Andric // If the loop could not be converted to canonical form, it must have an 24190b57cec5SDimitry Andric // indirectbr in it, just give up. 24200b57cec5SDimitry Andric if (!L->getLoopPreheader()) 24210b57cec5SDimitry Andric return false; 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric // Disable loop idiom recognition if the function's name is a common idiom. 24240b57cec5SDimitry Andric StringRef Name = L->getHeader()->getParent()->getName(); 24250b57cec5SDimitry Andric if (Name == "memset" || Name == "memcpy" || Name == "memmove") 24260b57cec5SDimitry Andric return false; 24270b57cec5SDimitry Andric 24280b57cec5SDimitry Andric DL = &L->getHeader()->getModule()->getDataLayout(); 24290b57cec5SDimitry Andric 24300b57cec5SDimitry Andric HasMemcpy = TLI->has(LibFunc_memcpy); 24310b57cec5SDimitry Andric HasMemmove = TLI->has(LibFunc_memmove); 24320b57cec5SDimitry Andric 24330b57cec5SDimitry Andric if (SE->hasLoopInvariantBackedgeTakenCount(L)) 24340b57cec5SDimitry Andric return runOnCountableLoop(L); 24350b57cec5SDimitry Andric return false; 24360b57cec5SDimitry Andric } 24370b57cec5SDimitry Andric 2438e8d8bef9SDimitry Andric bool HexagonLoopIdiomRecognizeLegacyPass::runOnLoop(Loop *L, 2439e8d8bef9SDimitry Andric LPPassManager &LPM) { 2440e8d8bef9SDimitry Andric if (skipLoop(L)) 2441e8d8bef9SDimitry Andric return false; 2442e8d8bef9SDimitry Andric 2443e8d8bef9SDimitry Andric auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 2444e8d8bef9SDimitry Andric auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2445e8d8bef9SDimitry Andric auto *LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2446e8d8bef9SDimitry Andric auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 2447e8d8bef9SDimitry Andric *L->getHeader()->getParent()); 2448e8d8bef9SDimitry Andric auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2449e8d8bef9SDimitry Andric return HexagonLoopIdiomRecognize(AA, DT, LF, TLI, SE).run(L); 2450e8d8bef9SDimitry Andric } 2451e8d8bef9SDimitry Andric 24520b57cec5SDimitry Andric Pass *llvm::createHexagonLoopIdiomPass() { 2453e8d8bef9SDimitry Andric return new HexagonLoopIdiomRecognizeLegacyPass(); 2454e8d8bef9SDimitry Andric } 2455e8d8bef9SDimitry Andric 2456e8d8bef9SDimitry Andric PreservedAnalyses 2457e8d8bef9SDimitry Andric HexagonLoopIdiomRecognitionPass::run(Loop &L, LoopAnalysisManager &AM, 2458e8d8bef9SDimitry Andric LoopStandardAnalysisResults &AR, 2459e8d8bef9SDimitry Andric LPMUpdater &U) { 2460e8d8bef9SDimitry Andric return HexagonLoopIdiomRecognize(&AR.AA, &AR.DT, &AR.LI, &AR.TLI, &AR.SE) 2461e8d8bef9SDimitry Andric .run(&L) 2462e8d8bef9SDimitry Andric ? getLoopPassPreservedAnalyses() 2463e8d8bef9SDimitry Andric : PreservedAnalyses::all(); 24640b57cec5SDimitry Andric } 2465