176aa662cSKarthik Bhat //===-- LoopUtils.cpp - Loop Utility functions -------------------------===// 276aa662cSKarthik Bhat // 376aa662cSKarthik Bhat // The LLVM Compiler Infrastructure 476aa662cSKarthik Bhat // 576aa662cSKarthik Bhat // This file is distributed under the University of Illinois Open Source 676aa662cSKarthik Bhat // License. See LICENSE.TXT for details. 776aa662cSKarthik Bhat // 876aa662cSKarthik Bhat //===----------------------------------------------------------------------===// 976aa662cSKarthik Bhat // 1076aa662cSKarthik Bhat // This file defines common loop utility functions. 1176aa662cSKarthik Bhat // 1276aa662cSKarthik Bhat //===----------------------------------------------------------------------===// 1376aa662cSKarthik Bhat 1431088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h" 1531088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h" 1676aa662cSKarthik Bhat #include "llvm/Analysis/LoopInfo.h" 1731088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h" 1845d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h" 1945d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h" 2031088a9dSChandler Carruth #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 2131088a9dSChandler Carruth #include "llvm/IR/Dominators.h" 2276aa662cSKarthik Bhat #include "llvm/IR/Instructions.h" 2345d4cb9aSWeiming Zhao #include "llvm/IR/Module.h" 2476aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h" 2576aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h" 2631088a9dSChandler Carruth #include "llvm/Pass.h" 2776aa662cSKarthik Bhat #include "llvm/Support/Debug.h" 2876aa662cSKarthik Bhat #include "llvm/Transforms/Utils/LoopUtils.h" 2976aa662cSKarthik Bhat 3076aa662cSKarthik Bhat using namespace llvm; 3176aa662cSKarthik Bhat using namespace llvm::PatternMatch; 3276aa662cSKarthik Bhat 3376aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils" 3476aa662cSKarthik Bhat 350a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I, 3676aa662cSKarthik Bhat SmallPtrSetImpl<Instruction *> &Set) { 3776aa662cSKarthik Bhat for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) 3876aa662cSKarthik Bhat if (!Set.count(dyn_cast<Instruction>(*Use))) 3976aa662cSKarthik Bhat return false; 4076aa662cSKarthik Bhat return true; 4176aa662cSKarthik Bhat } 4276aa662cSKarthik Bhat 43c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) { 44c94f8e29SChad Rosier switch (Kind) { 45c94f8e29SChad Rosier default: 46c94f8e29SChad Rosier break; 47c94f8e29SChad Rosier case RK_IntegerAdd: 48c94f8e29SChad Rosier case RK_IntegerMult: 49c94f8e29SChad Rosier case RK_IntegerOr: 50c94f8e29SChad Rosier case RK_IntegerAnd: 51c94f8e29SChad Rosier case RK_IntegerXor: 52c94f8e29SChad Rosier case RK_IntegerMinMax: 53c94f8e29SChad Rosier return true; 54c94f8e29SChad Rosier } 55c94f8e29SChad Rosier return false; 56c94f8e29SChad Rosier } 57c94f8e29SChad Rosier 58c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) { 59c94f8e29SChad Rosier return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind); 60c94f8e29SChad Rosier } 61c94f8e29SChad Rosier 62c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) { 63c94f8e29SChad Rosier switch (Kind) { 64c94f8e29SChad Rosier default: 65c94f8e29SChad Rosier break; 66c94f8e29SChad Rosier case RK_IntegerAdd: 67c94f8e29SChad Rosier case RK_IntegerMult: 68c94f8e29SChad Rosier case RK_FloatAdd: 69c94f8e29SChad Rosier case RK_FloatMult: 70c94f8e29SChad Rosier return true; 71c94f8e29SChad Rosier } 72c94f8e29SChad Rosier return false; 73c94f8e29SChad Rosier } 74c94f8e29SChad Rosier 75c94f8e29SChad Rosier Instruction * 76c94f8e29SChad Rosier RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT, 77c94f8e29SChad Rosier SmallPtrSetImpl<Instruction *> &Visited, 78c94f8e29SChad Rosier SmallPtrSetImpl<Instruction *> &CI) { 79c94f8e29SChad Rosier if (!Phi->hasOneUse()) 80c94f8e29SChad Rosier return Phi; 81c94f8e29SChad Rosier 82c94f8e29SChad Rosier const APInt *M = nullptr; 83c94f8e29SChad Rosier Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser()); 84c94f8e29SChad Rosier 85c94f8e29SChad Rosier // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT 86c94f8e29SChad Rosier // with a new integer type of the corresponding bit width. 87c94f8e29SChad Rosier if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)), 88c94f8e29SChad Rosier m_And(m_APInt(M), m_Instruction(I))))) { 89c94f8e29SChad Rosier int32_t Bits = (*M + 1).exactLogBase2(); 90c94f8e29SChad Rosier if (Bits > 0) { 91c94f8e29SChad Rosier RT = IntegerType::get(Phi->getContext(), Bits); 92c94f8e29SChad Rosier Visited.insert(Phi); 93c94f8e29SChad Rosier CI.insert(J); 94c94f8e29SChad Rosier return J; 95c94f8e29SChad Rosier } 96c94f8e29SChad Rosier } 97c94f8e29SChad Rosier return Phi; 98c94f8e29SChad Rosier } 99c94f8e29SChad Rosier 100c94f8e29SChad Rosier bool RecurrenceDescriptor::getSourceExtensionKind( 101c94f8e29SChad Rosier Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned, 102c94f8e29SChad Rosier SmallPtrSetImpl<Instruction *> &Visited, 103c94f8e29SChad Rosier SmallPtrSetImpl<Instruction *> &CI) { 104c94f8e29SChad Rosier 105c94f8e29SChad Rosier SmallVector<Instruction *, 8> Worklist; 106c94f8e29SChad Rosier bool FoundOneOperand = false; 10729dc0f70SMatthew Simpson unsigned DstSize = RT->getPrimitiveSizeInBits(); 108c94f8e29SChad Rosier Worklist.push_back(Exit); 109c94f8e29SChad Rosier 110c94f8e29SChad Rosier // Traverse the instructions in the reduction expression, beginning with the 111c94f8e29SChad Rosier // exit value. 112c94f8e29SChad Rosier while (!Worklist.empty()) { 113c94f8e29SChad Rosier Instruction *I = Worklist.pop_back_val(); 114c94f8e29SChad Rosier for (Use &U : I->operands()) { 115c94f8e29SChad Rosier 116c94f8e29SChad Rosier // Terminate the traversal if the operand is not an instruction, or we 117c94f8e29SChad Rosier // reach the starting value. 118c94f8e29SChad Rosier Instruction *J = dyn_cast<Instruction>(U.get()); 119c94f8e29SChad Rosier if (!J || J == Start) 120c94f8e29SChad Rosier continue; 121c94f8e29SChad Rosier 122c94f8e29SChad Rosier // Otherwise, investigate the operation if it is also in the expression. 123c94f8e29SChad Rosier if (Visited.count(J)) { 124c94f8e29SChad Rosier Worklist.push_back(J); 125c94f8e29SChad Rosier continue; 126c94f8e29SChad Rosier } 127c94f8e29SChad Rosier 128c94f8e29SChad Rosier // If the operand is not in Visited, it is not a reduction operation, but 129c94f8e29SChad Rosier // it does feed into one. Make sure it is either a single-use sign- or 13029dc0f70SMatthew Simpson // zero-extend instruction. 131c94f8e29SChad Rosier CastInst *Cast = dyn_cast<CastInst>(J); 132c94f8e29SChad Rosier bool IsSExtInst = isa<SExtInst>(J); 13329dc0f70SMatthew Simpson if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst)) 13429dc0f70SMatthew Simpson return false; 13529dc0f70SMatthew Simpson 13629dc0f70SMatthew Simpson // Ensure the source type of the extend is no larger than the reduction 13729dc0f70SMatthew Simpson // type. It is not necessary for the types to be identical. 13829dc0f70SMatthew Simpson unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 13929dc0f70SMatthew Simpson if (SrcSize > DstSize) 140c94f8e29SChad Rosier return false; 141c94f8e29SChad Rosier 142c94f8e29SChad Rosier // Furthermore, ensure that all such extends are of the same kind. 143c94f8e29SChad Rosier if (FoundOneOperand) { 144c94f8e29SChad Rosier if (IsSigned != IsSExtInst) 145c94f8e29SChad Rosier return false; 146c94f8e29SChad Rosier } else { 147c94f8e29SChad Rosier FoundOneOperand = true; 148c94f8e29SChad Rosier IsSigned = IsSExtInst; 149c94f8e29SChad Rosier } 150c94f8e29SChad Rosier 15129dc0f70SMatthew Simpson // Lastly, if the source type of the extend matches the reduction type, 15229dc0f70SMatthew Simpson // add the extend to CI so that we can avoid accounting for it in the 15329dc0f70SMatthew Simpson // cost model. 15429dc0f70SMatthew Simpson if (SrcSize == DstSize) 155c94f8e29SChad Rosier CI.insert(Cast); 156c94f8e29SChad Rosier } 157c94f8e29SChad Rosier } 158c94f8e29SChad Rosier return true; 159c94f8e29SChad Rosier } 160c94f8e29SChad Rosier 1610a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind, 16276aa662cSKarthik Bhat Loop *TheLoop, bool HasFunNoNaNAttr, 1630a91310cSTyler Nowicki RecurrenceDescriptor &RedDes) { 16476aa662cSKarthik Bhat if (Phi->getNumIncomingValues() != 2) 16576aa662cSKarthik Bhat return false; 16676aa662cSKarthik Bhat 16776aa662cSKarthik Bhat // Reduction variables are only found in the loop header block. 16876aa662cSKarthik Bhat if (Phi->getParent() != TheLoop->getHeader()) 16976aa662cSKarthik Bhat return false; 17076aa662cSKarthik Bhat 17176aa662cSKarthik Bhat // Obtain the reduction start value from the value that comes from the loop 17276aa662cSKarthik Bhat // preheader. 17376aa662cSKarthik Bhat Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 17476aa662cSKarthik Bhat 17576aa662cSKarthik Bhat // ExitInstruction is the single value which is used outside the loop. 17676aa662cSKarthik Bhat // We only allow for a single reduction value to be used outside the loop. 17776aa662cSKarthik Bhat // This includes users of the reduction, variables (which form a cycle 17876aa662cSKarthik Bhat // which ends in the phi node). 17976aa662cSKarthik Bhat Instruction *ExitInstruction = nullptr; 18076aa662cSKarthik Bhat // Indicates that we found a reduction operation in our scan. 18176aa662cSKarthik Bhat bool FoundReduxOp = false; 18276aa662cSKarthik Bhat 18376aa662cSKarthik Bhat // We start with the PHI node and scan for all of the users of this 18476aa662cSKarthik Bhat // instruction. All users must be instructions that can be used as reduction 18576aa662cSKarthik Bhat // variables (such as ADD). We must have a single out-of-block user. The cycle 18676aa662cSKarthik Bhat // must include the original PHI. 18776aa662cSKarthik Bhat bool FoundStartPHI = false; 18876aa662cSKarthik Bhat 18976aa662cSKarthik Bhat // To recognize min/max patterns formed by a icmp select sequence, we store 19076aa662cSKarthik Bhat // the number of instruction we saw from the recognized min/max pattern, 19176aa662cSKarthik Bhat // to make sure we only see exactly the two instructions. 19276aa662cSKarthik Bhat unsigned NumCmpSelectPatternInst = 0; 19327b2c39eSTyler Nowicki InstDesc ReduxDesc(false, nullptr); 19476aa662cSKarthik Bhat 195c94f8e29SChad Rosier // Data used for determining if the recurrence has been type-promoted. 196c94f8e29SChad Rosier Type *RecurrenceType = Phi->getType(); 197c94f8e29SChad Rosier SmallPtrSet<Instruction *, 4> CastInsts; 198c94f8e29SChad Rosier Instruction *Start = Phi; 199c94f8e29SChad Rosier bool IsSigned = false; 200c94f8e29SChad Rosier 20176aa662cSKarthik Bhat SmallPtrSet<Instruction *, 8> VisitedInsts; 20276aa662cSKarthik Bhat SmallVector<Instruction *, 8> Worklist; 203c94f8e29SChad Rosier 204c94f8e29SChad Rosier // Return early if the recurrence kind does not match the type of Phi. If the 205c94f8e29SChad Rosier // recurrence kind is arithmetic, we attempt to look through AND operations 206c94f8e29SChad Rosier // resulting from the type promotion performed by InstCombine. Vector 207c94f8e29SChad Rosier // operations are not limited to the legal integer widths, so we may be able 208c94f8e29SChad Rosier // to evaluate the reduction in the narrower width. 209c94f8e29SChad Rosier if (RecurrenceType->isFloatingPointTy()) { 210c94f8e29SChad Rosier if (!isFloatingPointRecurrenceKind(Kind)) 211c94f8e29SChad Rosier return false; 212c94f8e29SChad Rosier } else { 213c94f8e29SChad Rosier if (!isIntegerRecurrenceKind(Kind)) 214c94f8e29SChad Rosier return false; 215c94f8e29SChad Rosier if (isArithmeticRecurrenceKind(Kind)) 216c94f8e29SChad Rosier Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts); 217c94f8e29SChad Rosier } 218c94f8e29SChad Rosier 219c94f8e29SChad Rosier Worklist.push_back(Start); 220c94f8e29SChad Rosier VisitedInsts.insert(Start); 22176aa662cSKarthik Bhat 22276aa662cSKarthik Bhat // A value in the reduction can be used: 22376aa662cSKarthik Bhat // - By the reduction: 22476aa662cSKarthik Bhat // - Reduction operation: 22576aa662cSKarthik Bhat // - One use of reduction value (safe). 22676aa662cSKarthik Bhat // - Multiple use of reduction value (not safe). 22776aa662cSKarthik Bhat // - PHI: 22876aa662cSKarthik Bhat // - All uses of the PHI must be the reduction (safe). 22976aa662cSKarthik Bhat // - Otherwise, not safe. 23076aa662cSKarthik Bhat // - By one instruction outside of the loop (safe). 23176aa662cSKarthik Bhat // - By further instructions outside of the loop (not safe). 23276aa662cSKarthik Bhat // - By an instruction that is not part of the reduction (not safe). 23376aa662cSKarthik Bhat // This is either: 23476aa662cSKarthik Bhat // * An instruction type other than PHI or the reduction operation. 23576aa662cSKarthik Bhat // * A PHI in the header other than the initial PHI. 23676aa662cSKarthik Bhat while (!Worklist.empty()) { 23776aa662cSKarthik Bhat Instruction *Cur = Worklist.back(); 23876aa662cSKarthik Bhat Worklist.pop_back(); 23976aa662cSKarthik Bhat 24076aa662cSKarthik Bhat // No Users. 24176aa662cSKarthik Bhat // If the instruction has no users then this is a broken chain and can't be 24276aa662cSKarthik Bhat // a reduction variable. 24376aa662cSKarthik Bhat if (Cur->use_empty()) 24476aa662cSKarthik Bhat return false; 24576aa662cSKarthik Bhat 24676aa662cSKarthik Bhat bool IsAPhi = isa<PHINode>(Cur); 24776aa662cSKarthik Bhat 24876aa662cSKarthik Bhat // A header PHI use other than the original PHI. 24976aa662cSKarthik Bhat if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent()) 25076aa662cSKarthik Bhat return false; 25176aa662cSKarthik Bhat 25276aa662cSKarthik Bhat // Reductions of instructions such as Div, and Sub is only possible if the 25376aa662cSKarthik Bhat // LHS is the reduction variable. 25476aa662cSKarthik Bhat if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) && 25576aa662cSKarthik Bhat !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) && 25676aa662cSKarthik Bhat !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0)))) 25776aa662cSKarthik Bhat return false; 25876aa662cSKarthik Bhat 259c94f8e29SChad Rosier // Any reduction instruction must be of one of the allowed kinds. We ignore 260c94f8e29SChad Rosier // the starting value (the Phi or an AND instruction if the Phi has been 261c94f8e29SChad Rosier // type-promoted). 262c94f8e29SChad Rosier if (Cur != Start) { 2630a91310cSTyler Nowicki ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr); 2640a91310cSTyler Nowicki if (!ReduxDesc.isRecurrence()) 26576aa662cSKarthik Bhat return false; 266c94f8e29SChad Rosier } 26776aa662cSKarthik Bhat 26876aa662cSKarthik Bhat // A reduction operation must only have one use of the reduction value. 26976aa662cSKarthik Bhat if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax && 27076aa662cSKarthik Bhat hasMultipleUsesOf(Cur, VisitedInsts)) 27176aa662cSKarthik Bhat return false; 27276aa662cSKarthik Bhat 27376aa662cSKarthik Bhat // All inputs to a PHI node must be a reduction value. 27476aa662cSKarthik Bhat if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts)) 27576aa662cSKarthik Bhat return false; 27676aa662cSKarthik Bhat 27776aa662cSKarthik Bhat if (Kind == RK_IntegerMinMax && 27876aa662cSKarthik Bhat (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur))) 27976aa662cSKarthik Bhat ++NumCmpSelectPatternInst; 28076aa662cSKarthik Bhat if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur))) 28176aa662cSKarthik Bhat ++NumCmpSelectPatternInst; 28276aa662cSKarthik Bhat 28376aa662cSKarthik Bhat // Check whether we found a reduction operator. 284c94f8e29SChad Rosier FoundReduxOp |= !IsAPhi && Cur != Start; 28576aa662cSKarthik Bhat 28676aa662cSKarthik Bhat // Process users of current instruction. Push non-PHI nodes after PHI nodes 28776aa662cSKarthik Bhat // onto the stack. This way we are going to have seen all inputs to PHI 28876aa662cSKarthik Bhat // nodes once we get to them. 28976aa662cSKarthik Bhat SmallVector<Instruction *, 8> NonPHIs; 29076aa662cSKarthik Bhat SmallVector<Instruction *, 8> PHIs; 29176aa662cSKarthik Bhat for (User *U : Cur->users()) { 29276aa662cSKarthik Bhat Instruction *UI = cast<Instruction>(U); 29376aa662cSKarthik Bhat 29476aa662cSKarthik Bhat // Check if we found the exit user. 29576aa662cSKarthik Bhat BasicBlock *Parent = UI->getParent(); 29676aa662cSKarthik Bhat if (!TheLoop->contains(Parent)) { 29776aa662cSKarthik Bhat // Exit if you find multiple outside users or if the header phi node is 29876aa662cSKarthik Bhat // being used. In this case the user uses the value of the previous 29976aa662cSKarthik Bhat // iteration, in which case we would loose "VF-1" iterations of the 30076aa662cSKarthik Bhat // reduction operation if we vectorize. 30176aa662cSKarthik Bhat if (ExitInstruction != nullptr || Cur == Phi) 30276aa662cSKarthik Bhat return false; 30376aa662cSKarthik Bhat 30476aa662cSKarthik Bhat // The instruction used by an outside user must be the last instruction 30576aa662cSKarthik Bhat // before we feed back to the reduction phi. Otherwise, we loose VF-1 30676aa662cSKarthik Bhat // operations on the value. 30776aa662cSKarthik Bhat if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end()) 30876aa662cSKarthik Bhat return false; 30976aa662cSKarthik Bhat 31076aa662cSKarthik Bhat ExitInstruction = Cur; 31176aa662cSKarthik Bhat continue; 31276aa662cSKarthik Bhat } 31376aa662cSKarthik Bhat 31476aa662cSKarthik Bhat // Process instructions only once (termination). Each reduction cycle 31576aa662cSKarthik Bhat // value must only be used once, except by phi nodes and min/max 31676aa662cSKarthik Bhat // reductions which are represented as a cmp followed by a select. 31727b2c39eSTyler Nowicki InstDesc IgnoredVal(false, nullptr); 31876aa662cSKarthik Bhat if (VisitedInsts.insert(UI).second) { 31976aa662cSKarthik Bhat if (isa<PHINode>(UI)) 32076aa662cSKarthik Bhat PHIs.push_back(UI); 32176aa662cSKarthik Bhat else 32276aa662cSKarthik Bhat NonPHIs.push_back(UI); 32376aa662cSKarthik Bhat } else if (!isa<PHINode>(UI) && 32476aa662cSKarthik Bhat ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) && 32576aa662cSKarthik Bhat !isa<SelectInst>(UI)) || 3260a91310cSTyler Nowicki !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence())) 32776aa662cSKarthik Bhat return false; 32876aa662cSKarthik Bhat 32976aa662cSKarthik Bhat // Remember that we completed the cycle. 33076aa662cSKarthik Bhat if (UI == Phi) 33176aa662cSKarthik Bhat FoundStartPHI = true; 33276aa662cSKarthik Bhat } 33376aa662cSKarthik Bhat Worklist.append(PHIs.begin(), PHIs.end()); 33476aa662cSKarthik Bhat Worklist.append(NonPHIs.begin(), NonPHIs.end()); 33576aa662cSKarthik Bhat } 33676aa662cSKarthik Bhat 33776aa662cSKarthik Bhat // This means we have seen one but not the other instruction of the 33876aa662cSKarthik Bhat // pattern or more than just a select and cmp. 33976aa662cSKarthik Bhat if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) && 34076aa662cSKarthik Bhat NumCmpSelectPatternInst != 2) 34176aa662cSKarthik Bhat return false; 34276aa662cSKarthik Bhat 34376aa662cSKarthik Bhat if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction) 34476aa662cSKarthik Bhat return false; 34576aa662cSKarthik Bhat 346c94f8e29SChad Rosier // If we think Phi may have been type-promoted, we also need to ensure that 347c94f8e29SChad Rosier // all source operands of the reduction are either SExtInsts or ZEstInsts. If 348c94f8e29SChad Rosier // so, we will be able to evaluate the reduction in the narrower bit width. 349c94f8e29SChad Rosier if (Start != Phi) 350c94f8e29SChad Rosier if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType, 351c94f8e29SChad Rosier IsSigned, VisitedInsts, CastInsts)) 352c94f8e29SChad Rosier return false; 353c94f8e29SChad Rosier 35476aa662cSKarthik Bhat // We found a reduction var if we have reached the original phi node and we 35576aa662cSKarthik Bhat // only have a single instruction with out-of-loop users. 35676aa662cSKarthik Bhat 35776aa662cSKarthik Bhat // The ExitInstruction(Instruction which is allowed to have out-of-loop users) 3580a91310cSTyler Nowicki // is saved as part of the RecurrenceDescriptor. 35976aa662cSKarthik Bhat 36076aa662cSKarthik Bhat // Save the description of this reduction variable. 361c94f8e29SChad Rosier RecurrenceDescriptor RD( 362c94f8e29SChad Rosier RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(), 363c94f8e29SChad Rosier ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts); 36476aa662cSKarthik Bhat RedDes = RD; 36576aa662cSKarthik Bhat 36676aa662cSKarthik Bhat return true; 36776aa662cSKarthik Bhat } 36876aa662cSKarthik Bhat 36976aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 37076aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y). 37127b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc 37227b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) { 37376aa662cSKarthik Bhat 37476aa662cSKarthik Bhat assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) && 37576aa662cSKarthik Bhat "Expect a select instruction"); 37676aa662cSKarthik Bhat Instruction *Cmp = nullptr; 37776aa662cSKarthik Bhat SelectInst *Select = nullptr; 37876aa662cSKarthik Bhat 37976aa662cSKarthik Bhat // We must handle the select(cmp()) as a single instruction. Advance to the 38076aa662cSKarthik Bhat // select. 38176aa662cSKarthik Bhat if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) { 38276aa662cSKarthik Bhat if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin()))) 38327b2c39eSTyler Nowicki return InstDesc(false, I); 38427b2c39eSTyler Nowicki return InstDesc(Select, Prev.getMinMaxKind()); 38576aa662cSKarthik Bhat } 38676aa662cSKarthik Bhat 38776aa662cSKarthik Bhat // Only handle single use cases for now. 38876aa662cSKarthik Bhat if (!(Select = dyn_cast<SelectInst>(I))) 38927b2c39eSTyler Nowicki return InstDesc(false, I); 39076aa662cSKarthik Bhat if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) && 39176aa662cSKarthik Bhat !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0)))) 39227b2c39eSTyler Nowicki return InstDesc(false, I); 39376aa662cSKarthik Bhat if (!Cmp->hasOneUse()) 39427b2c39eSTyler Nowicki return InstDesc(false, I); 39576aa662cSKarthik Bhat 39676aa662cSKarthik Bhat Value *CmpLeft; 39776aa662cSKarthik Bhat Value *CmpRight; 39876aa662cSKarthik Bhat 39976aa662cSKarthik Bhat // Look for a min/max pattern. 40076aa662cSKarthik Bhat if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 40127b2c39eSTyler Nowicki return InstDesc(Select, MRK_UIntMin); 40276aa662cSKarthik Bhat else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 40327b2c39eSTyler Nowicki return InstDesc(Select, MRK_UIntMax); 40476aa662cSKarthik Bhat else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 40527b2c39eSTyler Nowicki return InstDesc(Select, MRK_SIntMax); 40676aa662cSKarthik Bhat else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 40727b2c39eSTyler Nowicki return InstDesc(Select, MRK_SIntMin); 40876aa662cSKarthik Bhat else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 40927b2c39eSTyler Nowicki return InstDesc(Select, MRK_FloatMin); 41076aa662cSKarthik Bhat else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 41127b2c39eSTyler Nowicki return InstDesc(Select, MRK_FloatMax); 41276aa662cSKarthik Bhat else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 41327b2c39eSTyler Nowicki return InstDesc(Select, MRK_FloatMin); 41476aa662cSKarthik Bhat else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 41527b2c39eSTyler Nowicki return InstDesc(Select, MRK_FloatMax); 41676aa662cSKarthik Bhat 41727b2c39eSTyler Nowicki return InstDesc(false, I); 41876aa662cSKarthik Bhat } 41976aa662cSKarthik Bhat 42027b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc 4210a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind, 42227b2c39eSTyler Nowicki InstDesc &Prev, bool HasFunNoNaNAttr) { 42376aa662cSKarthik Bhat bool FP = I->getType()->isFloatingPointTy(); 424c1a86f58STyler Nowicki Instruction *UAI = Prev.getUnsafeAlgebraInst(); 425c1a86f58STyler Nowicki if (!UAI && FP && !I->hasUnsafeAlgebra()) 426c1a86f58STyler Nowicki UAI = I; // Found an unsafe (unvectorizable) algebra instruction. 427c1a86f58STyler Nowicki 42876aa662cSKarthik Bhat switch (I->getOpcode()) { 42976aa662cSKarthik Bhat default: 43027b2c39eSTyler Nowicki return InstDesc(false, I); 43176aa662cSKarthik Bhat case Instruction::PHI: 43227b2c39eSTyler Nowicki return InstDesc(I, Prev.getMinMaxKind()); 43376aa662cSKarthik Bhat case Instruction::Sub: 43476aa662cSKarthik Bhat case Instruction::Add: 43527b2c39eSTyler Nowicki return InstDesc(Kind == RK_IntegerAdd, I); 43676aa662cSKarthik Bhat case Instruction::Mul: 43727b2c39eSTyler Nowicki return InstDesc(Kind == RK_IntegerMult, I); 43876aa662cSKarthik Bhat case Instruction::And: 43927b2c39eSTyler Nowicki return InstDesc(Kind == RK_IntegerAnd, I); 44076aa662cSKarthik Bhat case Instruction::Or: 44127b2c39eSTyler Nowicki return InstDesc(Kind == RK_IntegerOr, I); 44276aa662cSKarthik Bhat case Instruction::Xor: 44327b2c39eSTyler Nowicki return InstDesc(Kind == RK_IntegerXor, I); 44476aa662cSKarthik Bhat case Instruction::FMul: 445c1a86f58STyler Nowicki return InstDesc(Kind == RK_FloatMult, I, UAI); 44676aa662cSKarthik Bhat case Instruction::FSub: 44776aa662cSKarthik Bhat case Instruction::FAdd: 448c1a86f58STyler Nowicki return InstDesc(Kind == RK_FloatAdd, I, UAI); 44976aa662cSKarthik Bhat case Instruction::FCmp: 45076aa662cSKarthik Bhat case Instruction::ICmp: 45176aa662cSKarthik Bhat case Instruction::Select: 45276aa662cSKarthik Bhat if (Kind != RK_IntegerMinMax && 45376aa662cSKarthik Bhat (!HasFunNoNaNAttr || Kind != RK_FloatMinMax)) 45427b2c39eSTyler Nowicki return InstDesc(false, I); 45576aa662cSKarthik Bhat return isMinMaxSelectCmpPattern(I, Prev); 45676aa662cSKarthik Bhat } 45776aa662cSKarthik Bhat } 45876aa662cSKarthik Bhat 4590a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf( 46076aa662cSKarthik Bhat Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) { 46176aa662cSKarthik Bhat unsigned NumUses = 0; 46276aa662cSKarthik Bhat for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; 46376aa662cSKarthik Bhat ++Use) { 46476aa662cSKarthik Bhat if (Insts.count(dyn_cast<Instruction>(*Use))) 46576aa662cSKarthik Bhat ++NumUses; 46676aa662cSKarthik Bhat if (NumUses > 1) 46776aa662cSKarthik Bhat return true; 46876aa662cSKarthik Bhat } 46976aa662cSKarthik Bhat 47076aa662cSKarthik Bhat return false; 47176aa662cSKarthik Bhat } 4720a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop, 4730a91310cSTyler Nowicki RecurrenceDescriptor &RedDes) { 47476aa662cSKarthik Bhat 47576aa662cSKarthik Bhat BasicBlock *Header = TheLoop->getHeader(); 47676aa662cSKarthik Bhat Function &F = *Header->getParent(); 4778dd66e57SNirav Dave bool HasFunNoNaNAttr = 47876aa662cSKarthik Bhat F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 47976aa662cSKarthik Bhat 48076aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) { 48176aa662cSKarthik Bhat DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n"); 48276aa662cSKarthik Bhat return true; 48376aa662cSKarthik Bhat } 48476aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) { 48576aa662cSKarthik Bhat DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n"); 48676aa662cSKarthik Bhat return true; 48776aa662cSKarthik Bhat } 48876aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) { 48976aa662cSKarthik Bhat DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n"); 49076aa662cSKarthik Bhat return true; 49176aa662cSKarthik Bhat } 49276aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) { 49376aa662cSKarthik Bhat DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n"); 49476aa662cSKarthik Bhat return true; 49576aa662cSKarthik Bhat } 49676aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) { 49776aa662cSKarthik Bhat DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n"); 49876aa662cSKarthik Bhat return true; 49976aa662cSKarthik Bhat } 50076aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, 50176aa662cSKarthik Bhat RedDes)) { 50276aa662cSKarthik Bhat DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n"); 50376aa662cSKarthik Bhat return true; 50476aa662cSKarthik Bhat } 50576aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) { 50676aa662cSKarthik Bhat DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n"); 50776aa662cSKarthik Bhat return true; 50876aa662cSKarthik Bhat } 50976aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) { 51076aa662cSKarthik Bhat DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n"); 51176aa662cSKarthik Bhat return true; 51276aa662cSKarthik Bhat } 51376aa662cSKarthik Bhat if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) { 51476aa662cSKarthik Bhat DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n"); 51576aa662cSKarthik Bhat return true; 51676aa662cSKarthik Bhat } 51776aa662cSKarthik Bhat // Not a reduction of known type. 51876aa662cSKarthik Bhat return false; 51976aa662cSKarthik Bhat } 52076aa662cSKarthik Bhat 52129c997c1SMatthew Simpson bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, 52229c997c1SMatthew Simpson DominatorTree *DT) { 52329c997c1SMatthew Simpson 52429c997c1SMatthew Simpson // Ensure the phi node is in the loop header and has two incoming values. 52529c997c1SMatthew Simpson if (Phi->getParent() != TheLoop->getHeader() || 52629c997c1SMatthew Simpson Phi->getNumIncomingValues() != 2) 52729c997c1SMatthew Simpson return false; 52829c997c1SMatthew Simpson 52929c997c1SMatthew Simpson // Ensure the loop has a preheader and a single latch block. The loop 53029c997c1SMatthew Simpson // vectorizer will need the latch to set up the next iteration of the loop. 53129c997c1SMatthew Simpson auto *Preheader = TheLoop->getLoopPreheader(); 53229c997c1SMatthew Simpson auto *Latch = TheLoop->getLoopLatch(); 53329c997c1SMatthew Simpson if (!Preheader || !Latch) 53429c997c1SMatthew Simpson return false; 53529c997c1SMatthew Simpson 53629c997c1SMatthew Simpson // Ensure the phi node's incoming blocks are the loop preheader and latch. 53729c997c1SMatthew Simpson if (Phi->getBasicBlockIndex(Preheader) < 0 || 53829c997c1SMatthew Simpson Phi->getBasicBlockIndex(Latch) < 0) 53929c997c1SMatthew Simpson return false; 54029c997c1SMatthew Simpson 54129c997c1SMatthew Simpson // Get the previous value. The previous value comes from the latch edge while 54229c997c1SMatthew Simpson // the initial value comes form the preheader edge. 54329c997c1SMatthew Simpson auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch)); 54453207a99SMatthew Simpson if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous)) 54529c997c1SMatthew Simpson return false; 54629c997c1SMatthew Simpson 54729c997c1SMatthew Simpson // Ensure every user of the phi node is dominated by the previous value. The 54829c997c1SMatthew Simpson // dominance requirement ensures the loop vectorizer will not need to 54929c997c1SMatthew Simpson // vectorize the initial value prior to the first iteration of the loop. 55029c997c1SMatthew Simpson for (User *U : Phi->users()) 55129c997c1SMatthew Simpson if (auto *I = dyn_cast<Instruction>(U)) 55229c997c1SMatthew Simpson if (!DT->dominates(Previous, I)) 55329c997c1SMatthew Simpson return false; 55429c997c1SMatthew Simpson 55529c997c1SMatthew Simpson return true; 55629c997c1SMatthew Simpson } 55729c997c1SMatthew Simpson 55876aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for 55976aa662cSKarthik Bhat /// the operation K. 5600a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K, 5610a91310cSTyler Nowicki Type *Tp) { 56276aa662cSKarthik Bhat switch (K) { 56376aa662cSKarthik Bhat case RK_IntegerXor: 56476aa662cSKarthik Bhat case RK_IntegerAdd: 56576aa662cSKarthik Bhat case RK_IntegerOr: 56676aa662cSKarthik Bhat // Adding, Xoring, Oring zero to a number does not change it. 56776aa662cSKarthik Bhat return ConstantInt::get(Tp, 0); 56876aa662cSKarthik Bhat case RK_IntegerMult: 56976aa662cSKarthik Bhat // Multiplying a number by 1 does not change it. 57076aa662cSKarthik Bhat return ConstantInt::get(Tp, 1); 57176aa662cSKarthik Bhat case RK_IntegerAnd: 57276aa662cSKarthik Bhat // AND-ing a number with an all-1 value does not change it. 57376aa662cSKarthik Bhat return ConstantInt::get(Tp, -1, true); 57476aa662cSKarthik Bhat case RK_FloatMult: 57576aa662cSKarthik Bhat // Multiplying a number by 1 does not change it. 57676aa662cSKarthik Bhat return ConstantFP::get(Tp, 1.0L); 57776aa662cSKarthik Bhat case RK_FloatAdd: 57876aa662cSKarthik Bhat // Adding zero to a number does not change it. 57976aa662cSKarthik Bhat return ConstantFP::get(Tp, 0.0L); 58076aa662cSKarthik Bhat default: 5810a91310cSTyler Nowicki llvm_unreachable("Unknown recurrence kind"); 58276aa662cSKarthik Bhat } 58376aa662cSKarthik Bhat } 58476aa662cSKarthik Bhat 5850a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator. 5860a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) { 58776aa662cSKarthik Bhat switch (Kind) { 58876aa662cSKarthik Bhat case RK_IntegerAdd: 58976aa662cSKarthik Bhat return Instruction::Add; 59076aa662cSKarthik Bhat case RK_IntegerMult: 59176aa662cSKarthik Bhat return Instruction::Mul; 59276aa662cSKarthik Bhat case RK_IntegerOr: 59376aa662cSKarthik Bhat return Instruction::Or; 59476aa662cSKarthik Bhat case RK_IntegerAnd: 59576aa662cSKarthik Bhat return Instruction::And; 59676aa662cSKarthik Bhat case RK_IntegerXor: 59776aa662cSKarthik Bhat return Instruction::Xor; 59876aa662cSKarthik Bhat case RK_FloatMult: 59976aa662cSKarthik Bhat return Instruction::FMul; 60076aa662cSKarthik Bhat case RK_FloatAdd: 60176aa662cSKarthik Bhat return Instruction::FAdd; 60276aa662cSKarthik Bhat case RK_IntegerMinMax: 60376aa662cSKarthik Bhat return Instruction::ICmp; 60476aa662cSKarthik Bhat case RK_FloatMinMax: 60576aa662cSKarthik Bhat return Instruction::FCmp; 60676aa662cSKarthik Bhat default: 6070a91310cSTyler Nowicki llvm_unreachable("Unknown recurrence operation"); 60876aa662cSKarthik Bhat } 60976aa662cSKarthik Bhat } 61076aa662cSKarthik Bhat 61127b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder, 61227b2c39eSTyler Nowicki MinMaxRecurrenceKind RK, 61376aa662cSKarthik Bhat Value *Left, Value *Right) { 61476aa662cSKarthik Bhat CmpInst::Predicate P = CmpInst::ICMP_NE; 61576aa662cSKarthik Bhat switch (RK) { 61676aa662cSKarthik Bhat default: 6170a91310cSTyler Nowicki llvm_unreachable("Unknown min/max recurrence kind"); 61827b2c39eSTyler Nowicki case MRK_UIntMin: 61976aa662cSKarthik Bhat P = CmpInst::ICMP_ULT; 62076aa662cSKarthik Bhat break; 62127b2c39eSTyler Nowicki case MRK_UIntMax: 62276aa662cSKarthik Bhat P = CmpInst::ICMP_UGT; 62376aa662cSKarthik Bhat break; 62427b2c39eSTyler Nowicki case MRK_SIntMin: 62576aa662cSKarthik Bhat P = CmpInst::ICMP_SLT; 62676aa662cSKarthik Bhat break; 62727b2c39eSTyler Nowicki case MRK_SIntMax: 62876aa662cSKarthik Bhat P = CmpInst::ICMP_SGT; 62976aa662cSKarthik Bhat break; 63027b2c39eSTyler Nowicki case MRK_FloatMin: 63176aa662cSKarthik Bhat P = CmpInst::FCMP_OLT; 63276aa662cSKarthik Bhat break; 63327b2c39eSTyler Nowicki case MRK_FloatMax: 63476aa662cSKarthik Bhat P = CmpInst::FCMP_OGT; 63576aa662cSKarthik Bhat break; 63676aa662cSKarthik Bhat } 63776aa662cSKarthik Bhat 63850a4c27fSJames Molloy // We only match FP sequences with unsafe algebra, so we can unconditionally 63950a4c27fSJames Molloy // set it on any generated instructions. 64050a4c27fSJames Molloy IRBuilder<>::FastMathFlagGuard FMFG(Builder); 64150a4c27fSJames Molloy FastMathFlags FMF; 64250a4c27fSJames Molloy FMF.setUnsafeAlgebra(); 643a252815bSSanjay Patel Builder.setFastMathFlags(FMF); 64450a4c27fSJames Molloy 64576aa662cSKarthik Bhat Value *Cmp; 64627b2c39eSTyler Nowicki if (RK == MRK_FloatMin || RK == MRK_FloatMax) 64776aa662cSKarthik Bhat Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 64876aa662cSKarthik Bhat else 64976aa662cSKarthik Bhat Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 65076aa662cSKarthik Bhat 65176aa662cSKarthik Bhat Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 65276aa662cSKarthik Bhat return Select; 65376aa662cSKarthik Bhat } 65424e6cc2dSKarthik Bhat 6551bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K, 6561bbf15c5SJames Molloy ConstantInt *Step) 6571bbf15c5SJames Molloy : StartValue(Start), IK(K), StepValue(Step) { 6581bbf15c5SJames Molloy assert(IK != IK_NoInduction && "Not an induction"); 6591bbf15c5SJames Molloy assert(StartValue && "StartValue is null"); 6601bbf15c5SJames Molloy assert(StepValue && !StepValue->isZero() && "StepValue is zero"); 6611bbf15c5SJames Molloy assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) && 6621bbf15c5SJames Molloy "StartValue is not a pointer for pointer induction"); 6631bbf15c5SJames Molloy assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) && 6641bbf15c5SJames Molloy "StartValue is not an integer for integer induction"); 6651bbf15c5SJames Molloy assert(StepValue->getType()->isIntegerTy() && 6661bbf15c5SJames Molloy "StepValue is not an integer"); 6671bbf15c5SJames Molloy } 6681bbf15c5SJames Molloy 6691bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const { 6701bbf15c5SJames Molloy if (StepValue && (StepValue->isOne() || StepValue->isMinusOne())) 6711bbf15c5SJames Molloy return StepValue->getSExtValue(); 6721bbf15c5SJames Molloy return 0; 6731bbf15c5SJames Molloy } 6741bbf15c5SJames Molloy 6751bbf15c5SJames Molloy Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const { 6761bbf15c5SJames Molloy switch (IK) { 6771bbf15c5SJames Molloy case IK_IntInduction: 6781bbf15c5SJames Molloy assert(Index->getType() == StartValue->getType() && 6791bbf15c5SJames Molloy "Index type does not match StartValue type"); 6801bbf15c5SJames Molloy if (StepValue->isMinusOne()) 6811bbf15c5SJames Molloy return B.CreateSub(StartValue, Index); 6821bbf15c5SJames Molloy if (!StepValue->isOne()) 6831bbf15c5SJames Molloy Index = B.CreateMul(Index, StepValue); 6841bbf15c5SJames Molloy return B.CreateAdd(StartValue, Index); 6851bbf15c5SJames Molloy 6861bbf15c5SJames Molloy case IK_PtrInduction: 6871bbf15c5SJames Molloy assert(Index->getType() == StepValue->getType() && 6881bbf15c5SJames Molloy "Index type does not match StepValue type"); 6891bbf15c5SJames Molloy if (StepValue->isMinusOne()) 6901bbf15c5SJames Molloy Index = B.CreateNeg(Index); 6911bbf15c5SJames Molloy else if (!StepValue->isOne()) 6921bbf15c5SJames Molloy Index = B.CreateMul(Index, StepValue); 6931bbf15c5SJames Molloy return B.CreateGEP(nullptr, StartValue, Index); 6941bbf15c5SJames Molloy 6951bbf15c5SJames Molloy case IK_NoInduction: 6961bbf15c5SJames Molloy return nullptr; 6971bbf15c5SJames Molloy } 6981bbf15c5SJames Molloy llvm_unreachable("invalid enum"); 6991bbf15c5SJames Molloy } 7001bbf15c5SJames Molloy 701*c05bab8aSSilviu Baranga bool InductionDescriptor::isInductionPHI(PHINode *Phi, 702*c05bab8aSSilviu Baranga PredicatedScalarEvolution &PSE, 703*c05bab8aSSilviu Baranga InductionDescriptor &D, 704*c05bab8aSSilviu Baranga bool Assume) { 705*c05bab8aSSilviu Baranga Type *PhiTy = Phi->getType(); 706*c05bab8aSSilviu Baranga // We only handle integer and pointer inductions variables. 707*c05bab8aSSilviu Baranga if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 708*c05bab8aSSilviu Baranga return false; 709*c05bab8aSSilviu Baranga 710*c05bab8aSSilviu Baranga const SCEV *PhiScev = PSE.getSCEV(Phi); 711*c05bab8aSSilviu Baranga const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 712*c05bab8aSSilviu Baranga 713*c05bab8aSSilviu Baranga // We need this expression to be an AddRecExpr. 714*c05bab8aSSilviu Baranga if (Assume && !AR) 715*c05bab8aSSilviu Baranga AR = PSE.getAsAddRec(Phi); 716*c05bab8aSSilviu Baranga 717*c05bab8aSSilviu Baranga if (!AR) { 718*c05bab8aSSilviu Baranga DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 719*c05bab8aSSilviu Baranga return false; 720*c05bab8aSSilviu Baranga } 721*c05bab8aSSilviu Baranga 722*c05bab8aSSilviu Baranga return isInductionPHI(Phi, PSE.getSE(), D, AR); 723*c05bab8aSSilviu Baranga } 724*c05bab8aSSilviu Baranga 725*c05bab8aSSilviu Baranga bool InductionDescriptor::isInductionPHI(PHINode *Phi, 726*c05bab8aSSilviu Baranga ScalarEvolution *SE, 727*c05bab8aSSilviu Baranga InductionDescriptor &D, 728*c05bab8aSSilviu Baranga const SCEV *Expr) { 72924e6cc2dSKarthik Bhat Type *PhiTy = Phi->getType(); 73024e6cc2dSKarthik Bhat // We only handle integer and pointer inductions variables. 73124e6cc2dSKarthik Bhat if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 73224e6cc2dSKarthik Bhat return false; 73324e6cc2dSKarthik Bhat 73424e6cc2dSKarthik Bhat // Check that the PHI is consecutive. 735*c05bab8aSSilviu Baranga const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi); 73624e6cc2dSKarthik Bhat const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 737*c05bab8aSSilviu Baranga 73824e6cc2dSKarthik Bhat if (!AR) { 73924e6cc2dSKarthik Bhat DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 74024e6cc2dSKarthik Bhat return false; 74124e6cc2dSKarthik Bhat } 74224e6cc2dSKarthik Bhat 7431bbf15c5SJames Molloy assert(AR->getLoop()->getHeader() == Phi->getParent() && 7441bbf15c5SJames Molloy "PHI is an AddRec for a different loop?!"); 7451bbf15c5SJames Molloy Value *StartValue = 7461bbf15c5SJames Molloy Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader()); 74724e6cc2dSKarthik Bhat const SCEV *Step = AR->getStepRecurrence(*SE); 74824e6cc2dSKarthik Bhat // Calculate the pointer stride and check if it is consecutive. 74924e6cc2dSKarthik Bhat const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 75024e6cc2dSKarthik Bhat if (!C) 75124e6cc2dSKarthik Bhat return false; 75224e6cc2dSKarthik Bhat 75324e6cc2dSKarthik Bhat ConstantInt *CV = C->getValue(); 75424e6cc2dSKarthik Bhat if (PhiTy->isIntegerTy()) { 7551bbf15c5SJames Molloy D = InductionDescriptor(StartValue, IK_IntInduction, CV); 75624e6cc2dSKarthik Bhat return true; 75724e6cc2dSKarthik Bhat } 75824e6cc2dSKarthik Bhat 75924e6cc2dSKarthik Bhat assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 76024e6cc2dSKarthik Bhat Type *PointerElementType = PhiTy->getPointerElementType(); 76124e6cc2dSKarthik Bhat // The pointer stride cannot be determined if the pointer element type is not 76224e6cc2dSKarthik Bhat // sized. 76324e6cc2dSKarthik Bhat if (!PointerElementType->isSized()) 76424e6cc2dSKarthik Bhat return false; 76524e6cc2dSKarthik Bhat 76624e6cc2dSKarthik Bhat const DataLayout &DL = Phi->getModule()->getDataLayout(); 76724e6cc2dSKarthik Bhat int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType)); 768b58f32f7SDavid Majnemer if (!Size) 769b58f32f7SDavid Majnemer return false; 770b58f32f7SDavid Majnemer 77124e6cc2dSKarthik Bhat int64_t CVSize = CV->getSExtValue(); 77224e6cc2dSKarthik Bhat if (CVSize % Size) 77324e6cc2dSKarthik Bhat return false; 7741bbf15c5SJames Molloy auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size); 7751bbf15c5SJames Molloy 7761bbf15c5SJames Molloy D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue); 77724e6cc2dSKarthik Bhat return true; 77824e6cc2dSKarthik Bhat } 779c5b7b555SAshutosh Nema 780c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop. 781c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) { 782c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> UsedOutside; 783c5b7b555SAshutosh Nema 784c5b7b555SAshutosh Nema for (auto *Block : L->getBlocks()) 785c5b7b555SAshutosh Nema // FIXME: I believe that this could use copy_if if the Inst reference could 786c5b7b555SAshutosh Nema // be adapted into a pointer. 787c5b7b555SAshutosh Nema for (auto &Inst : *Block) { 788c5b7b555SAshutosh Nema auto Users = Inst.users(); 789c5b7b555SAshutosh Nema if (std::any_of(Users.begin(), Users.end(), [&](User *U) { 790c5b7b555SAshutosh Nema auto *Use = cast<Instruction>(U); 791c5b7b555SAshutosh Nema return !L->contains(Use->getParent()); 792c5b7b555SAshutosh Nema })) 793c5b7b555SAshutosh Nema UsedOutside.push_back(&Inst); 794c5b7b555SAshutosh Nema } 795c5b7b555SAshutosh Nema 796c5b7b555SAshutosh Nema return UsedOutside; 797c5b7b555SAshutosh Nema } 79831088a9dSChandler Carruth 79931088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) { 80031088a9dSChandler Carruth // By definition, all loop passes need the LoopInfo analysis and the 80131088a9dSChandler Carruth // Dominator tree it depends on. Because they all participate in the loop 80231088a9dSChandler Carruth // pass manager, they must also preserve these. 80331088a9dSChandler Carruth AU.addRequired<DominatorTreeWrapperPass>(); 80431088a9dSChandler Carruth AU.addPreserved<DominatorTreeWrapperPass>(); 80531088a9dSChandler Carruth AU.addRequired<LoopInfoWrapperPass>(); 80631088a9dSChandler Carruth AU.addPreserved<LoopInfoWrapperPass>(); 80731088a9dSChandler Carruth 80831088a9dSChandler Carruth // We must also preserve LoopSimplify and LCSSA. We locally access their IDs 80931088a9dSChandler Carruth // here because users shouldn't directly get them from this header. 81031088a9dSChandler Carruth extern char &LoopSimplifyID; 81131088a9dSChandler Carruth extern char &LCSSAID; 81231088a9dSChandler Carruth AU.addRequiredID(LoopSimplifyID); 81331088a9dSChandler Carruth AU.addPreservedID(LoopSimplifyID); 81431088a9dSChandler Carruth AU.addRequiredID(LCSSAID); 81531088a9dSChandler Carruth AU.addPreservedID(LCSSAID); 81631088a9dSChandler Carruth 81731088a9dSChandler Carruth // Loop passes are designed to run inside of a loop pass manager which means 81831088a9dSChandler Carruth // that any function analyses they require must be required by the first loop 81931088a9dSChandler Carruth // pass in the manager (so that it is computed before the loop pass manager 82031088a9dSChandler Carruth // runs) and preserved by all loop pasess in the manager. To make this 82131088a9dSChandler Carruth // reasonably robust, the set needed for most loop passes is maintained here. 82231088a9dSChandler Carruth // If your loop pass requires an analysis not listed here, you will need to 82331088a9dSChandler Carruth // carefully audit the loop pass manager nesting structure that results. 82431088a9dSChandler Carruth AU.addRequired<AAResultsWrapperPass>(); 82531088a9dSChandler Carruth AU.addPreserved<AAResultsWrapperPass>(); 82631088a9dSChandler Carruth AU.addPreserved<BasicAAWrapperPass>(); 82731088a9dSChandler Carruth AU.addPreserved<GlobalsAAWrapperPass>(); 82831088a9dSChandler Carruth AU.addPreserved<SCEVAAWrapperPass>(); 82931088a9dSChandler Carruth AU.addRequired<ScalarEvolutionWrapperPass>(); 83031088a9dSChandler Carruth AU.addPreserved<ScalarEvolutionWrapperPass>(); 83131088a9dSChandler Carruth } 83231088a9dSChandler Carruth 83331088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used 83431088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c 83531088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization 83631088a9dSChandler Carruth /// with: 83731088a9dSChandler Carruth /// 83831088a9dSChandler Carruth /// INITIALIZE_PASS_DEPENDENCY(LoopPass) 83931088a9dSChandler Carruth /// 84031088a9dSChandler Carruth /// As-if "LoopPass" were a pass. 84131088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) { 84231088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 84331088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 84431088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 84531088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(LCSSA) 84631088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 84731088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 84831088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 84931088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 85031088a9dSChandler Carruth INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 85131088a9dSChandler Carruth } 852963341c8SAdam Nemet 853fe3def7cSAdam Nemet /// \brief Find string metadata for loop 854fe3def7cSAdam Nemet /// 855fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 856fe3def7cSAdam Nemet /// operand or null otherwise. If the string metadata is not found return 857fe3def7cSAdam Nemet /// Optional's not-a-value. 858fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop, 859fe3def7cSAdam Nemet StringRef Name) { 860963341c8SAdam Nemet MDNode *LoopID = TheLoop->getLoopID(); 861fe3def7cSAdam Nemet // Return none if LoopID is false. 862963341c8SAdam Nemet if (!LoopID) 863fe3def7cSAdam Nemet return None; 864293be666SAdam Nemet 865293be666SAdam Nemet // First operand should refer to the loop id itself. 866293be666SAdam Nemet assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 867293be666SAdam Nemet assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 868293be666SAdam Nemet 869963341c8SAdam Nemet // Iterate over LoopID operands and look for MDString Metadata 870963341c8SAdam Nemet for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 871963341c8SAdam Nemet MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 872963341c8SAdam Nemet if (!MD) 873963341c8SAdam Nemet continue; 874963341c8SAdam Nemet MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 875963341c8SAdam Nemet if (!S) 876963341c8SAdam Nemet continue; 877963341c8SAdam Nemet // Return true if MDString holds expected MetaData. 878963341c8SAdam Nemet if (Name.equals(S->getString())) 879fe3def7cSAdam Nemet switch (MD->getNumOperands()) { 880fe3def7cSAdam Nemet case 1: 881fe3def7cSAdam Nemet return nullptr; 882fe3def7cSAdam Nemet case 2: 883fe3def7cSAdam Nemet return &MD->getOperand(1); 884fe3def7cSAdam Nemet default: 885fe3def7cSAdam Nemet llvm_unreachable("loop metadata has 0 or 1 operand"); 886963341c8SAdam Nemet } 887fe3def7cSAdam Nemet } 888fe3def7cSAdam Nemet return None; 889963341c8SAdam Nemet } 890