blob: 4e150e8f0e15863930c138b0d6a63889c78b1cdd [file] [log] [blame]
Karthik Bhat76aa6622015-04-20 04:38:33 +00001//===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines common loop utility functions.
11//
12//===----------------------------------------------------------------------===//
13
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000014#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000015#include "llvm/Analysis/AliasAnalysis.h"
16#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000017#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000018#include "llvm/Analysis/GlobalsModRef.h"
19#include "llvm/Analysis/LoopInfo.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000020#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000021#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000022#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000024#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000025#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000026#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000027#include "llvm/IR/PatternMatch.h"
28#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000029#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000030#include "llvm/Support/Debug.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000031
32using namespace llvm;
33using namespace llvm::PatternMatch;
34
35#define DEBUG_TYPE "loop-utils"
36
Tyler Nowicki0a913102015-06-16 18:07:34 +000037bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
38 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000039 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
40 if (!Set.count(dyn_cast<Instruction>(*Use)))
41 return false;
42 return true;
43}
44
Chad Rosierc94f8e22015-08-27 14:12:17 +000045bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
46 switch (Kind) {
47 default:
48 break;
49 case RK_IntegerAdd:
50 case RK_IntegerMult:
51 case RK_IntegerOr:
52 case RK_IntegerAnd:
53 case RK_IntegerXor:
54 case RK_IntegerMinMax:
55 return true;
56 }
57 return false;
58}
59
60bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
61 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
62}
63
64bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
65 switch (Kind) {
66 default:
67 break;
68 case RK_IntegerAdd:
69 case RK_IntegerMult:
70 case RK_FloatAdd:
71 case RK_FloatMult:
72 return true;
73 }
74 return false;
75}
76
77Instruction *
78RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
79 SmallPtrSetImpl<Instruction *> &Visited,
80 SmallPtrSetImpl<Instruction *> &CI) {
81 if (!Phi->hasOneUse())
82 return Phi;
83
84 const APInt *M = nullptr;
85 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
86
87 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
88 // with a new integer type of the corresponding bit width.
89 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
90 m_And(m_APInt(M), m_Instruction(I))))) {
91 int32_t Bits = (*M + 1).exactLogBase2();
92 if (Bits > 0) {
93 RT = IntegerType::get(Phi->getContext(), Bits);
94 Visited.insert(Phi);
95 CI.insert(J);
96 return J;
97 }
98 }
99 return Phi;
100}
101
102bool RecurrenceDescriptor::getSourceExtensionKind(
103 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
104 SmallPtrSetImpl<Instruction *> &Visited,
105 SmallPtrSetImpl<Instruction *> &CI) {
106
107 SmallVector<Instruction *, 8> Worklist;
108 bool FoundOneOperand = false;
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000109 unsigned DstSize = RT->getPrimitiveSizeInBits();
Chad Rosierc94f8e22015-08-27 14:12:17 +0000110 Worklist.push_back(Exit);
111
112 // Traverse the instructions in the reduction expression, beginning with the
113 // exit value.
114 while (!Worklist.empty()) {
115 Instruction *I = Worklist.pop_back_val();
116 for (Use &U : I->operands()) {
117
118 // Terminate the traversal if the operand is not an instruction, or we
119 // reach the starting value.
120 Instruction *J = dyn_cast<Instruction>(U.get());
121 if (!J || J == Start)
122 continue;
123
124 // Otherwise, investigate the operation if it is also in the expression.
125 if (Visited.count(J)) {
126 Worklist.push_back(J);
127 continue;
128 }
129
130 // If the operand is not in Visited, it is not a reduction operation, but
131 // it does feed into one. Make sure it is either a single-use sign- or
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000132 // zero-extend instruction.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000133 CastInst *Cast = dyn_cast<CastInst>(J);
134 bool IsSExtInst = isa<SExtInst>(J);
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000135 if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
136 return false;
137
138 // Ensure the source type of the extend is no larger than the reduction
139 // type. It is not necessary for the types to be identical.
140 unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
141 if (SrcSize > DstSize)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000142 return false;
143
144 // Furthermore, ensure that all such extends are of the same kind.
145 if (FoundOneOperand) {
146 if (IsSigned != IsSExtInst)
147 return false;
148 } else {
149 FoundOneOperand = true;
150 IsSigned = IsSExtInst;
151 }
152
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000153 // Lastly, if the source type of the extend matches the reduction type,
154 // add the extend to CI so that we can avoid accounting for it in the
155 // cost model.
156 if (SrcSize == DstSize)
157 CI.insert(Cast);
Chad Rosierc94f8e22015-08-27 14:12:17 +0000158 }
159 }
160 return true;
161}
162
Tyler Nowicki0a913102015-06-16 18:07:34 +0000163bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
164 Loop *TheLoop, bool HasFunNoNaNAttr,
165 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000166 if (Phi->getNumIncomingValues() != 2)
167 return false;
168
169 // Reduction variables are only found in the loop header block.
170 if (Phi->getParent() != TheLoop->getHeader())
171 return false;
172
173 // Obtain the reduction start value from the value that comes from the loop
174 // preheader.
175 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
176
177 // ExitInstruction is the single value which is used outside the loop.
178 // We only allow for a single reduction value to be used outside the loop.
179 // This includes users of the reduction, variables (which form a cycle
180 // which ends in the phi node).
181 Instruction *ExitInstruction = nullptr;
182 // Indicates that we found a reduction operation in our scan.
183 bool FoundReduxOp = false;
184
185 // We start with the PHI node and scan for all of the users of this
186 // instruction. All users must be instructions that can be used as reduction
187 // variables (such as ADD). We must have a single out-of-block user. The cycle
188 // must include the original PHI.
189 bool FoundStartPHI = false;
190
191 // To recognize min/max patterns formed by a icmp select sequence, we store
192 // the number of instruction we saw from the recognized min/max pattern,
193 // to make sure we only see exactly the two instructions.
194 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000195 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000196
Chad Rosierc94f8e22015-08-27 14:12:17 +0000197 // Data used for determining if the recurrence has been type-promoted.
198 Type *RecurrenceType = Phi->getType();
199 SmallPtrSet<Instruction *, 4> CastInsts;
200 Instruction *Start = Phi;
201 bool IsSigned = false;
202
Karthik Bhat76aa6622015-04-20 04:38:33 +0000203 SmallPtrSet<Instruction *, 8> VisitedInsts;
204 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000205
206 // Return early if the recurrence kind does not match the type of Phi. If the
207 // recurrence kind is arithmetic, we attempt to look through AND operations
208 // resulting from the type promotion performed by InstCombine. Vector
209 // operations are not limited to the legal integer widths, so we may be able
210 // to evaluate the reduction in the narrower width.
211 if (RecurrenceType->isFloatingPointTy()) {
212 if (!isFloatingPointRecurrenceKind(Kind))
213 return false;
214 } else {
215 if (!isIntegerRecurrenceKind(Kind))
216 return false;
217 if (isArithmeticRecurrenceKind(Kind))
218 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
219 }
220
221 Worklist.push_back(Start);
222 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000223
224 // A value in the reduction can be used:
225 // - By the reduction:
226 // - Reduction operation:
227 // - One use of reduction value (safe).
228 // - Multiple use of reduction value (not safe).
229 // - PHI:
230 // - All uses of the PHI must be the reduction (safe).
231 // - Otherwise, not safe.
232 // - By one instruction outside of the loop (safe).
233 // - By further instructions outside of the loop (not safe).
234 // - By an instruction that is not part of the reduction (not safe).
235 // This is either:
236 // * An instruction type other than PHI or the reduction operation.
237 // * A PHI in the header other than the initial PHI.
238 while (!Worklist.empty()) {
239 Instruction *Cur = Worklist.back();
240 Worklist.pop_back();
241
242 // No Users.
243 // If the instruction has no users then this is a broken chain and can't be
244 // a reduction variable.
245 if (Cur->use_empty())
246 return false;
247
248 bool IsAPhi = isa<PHINode>(Cur);
249
250 // A header PHI use other than the original PHI.
251 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
252 return false;
253
254 // Reductions of instructions such as Div, and Sub is only possible if the
255 // LHS is the reduction variable.
256 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
257 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
258 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
259 return false;
260
Chad Rosierc94f8e22015-08-27 14:12:17 +0000261 // Any reduction instruction must be of one of the allowed kinds. We ignore
262 // the starting value (the Phi or an AND instruction if the Phi has been
263 // type-promoted).
264 if (Cur != Start) {
265 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
266 if (!ReduxDesc.isRecurrence())
267 return false;
268 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000269
270 // A reduction operation must only have one use of the reduction value.
271 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
272 hasMultipleUsesOf(Cur, VisitedInsts))
273 return false;
274
275 // All inputs to a PHI node must be a reduction value.
276 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
277 return false;
278
279 if (Kind == RK_IntegerMinMax &&
280 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
281 ++NumCmpSelectPatternInst;
282 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
283 ++NumCmpSelectPatternInst;
284
285 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000286 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000287
288 // Process users of current instruction. Push non-PHI nodes after PHI nodes
289 // onto the stack. This way we are going to have seen all inputs to PHI
290 // nodes once we get to them.
291 SmallVector<Instruction *, 8> NonPHIs;
292 SmallVector<Instruction *, 8> PHIs;
293 for (User *U : Cur->users()) {
294 Instruction *UI = cast<Instruction>(U);
295
296 // Check if we found the exit user.
297 BasicBlock *Parent = UI->getParent();
298 if (!TheLoop->contains(Parent)) {
299 // Exit if you find multiple outside users or if the header phi node is
300 // being used. In this case the user uses the value of the previous
301 // iteration, in which case we would loose "VF-1" iterations of the
302 // reduction operation if we vectorize.
303 if (ExitInstruction != nullptr || Cur == Phi)
304 return false;
305
306 // The instruction used by an outside user must be the last instruction
307 // before we feed back to the reduction phi. Otherwise, we loose VF-1
308 // operations on the value.
309 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
310 return false;
311
312 ExitInstruction = Cur;
313 continue;
314 }
315
316 // Process instructions only once (termination). Each reduction cycle
317 // value must only be used once, except by phi nodes and min/max
318 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000319 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000320 if (VisitedInsts.insert(UI).second) {
321 if (isa<PHINode>(UI))
322 PHIs.push_back(UI);
323 else
324 NonPHIs.push_back(UI);
325 } else if (!isa<PHINode>(UI) &&
326 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
327 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000328 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000329 return false;
330
331 // Remember that we completed the cycle.
332 if (UI == Phi)
333 FoundStartPHI = true;
334 }
335 Worklist.append(PHIs.begin(), PHIs.end());
336 Worklist.append(NonPHIs.begin(), NonPHIs.end());
337 }
338
339 // This means we have seen one but not the other instruction of the
340 // pattern or more than just a select and cmp.
341 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
342 NumCmpSelectPatternInst != 2)
343 return false;
344
345 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
346 return false;
347
Chad Rosierc94f8e22015-08-27 14:12:17 +0000348 // If we think Phi may have been type-promoted, we also need to ensure that
349 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
350 // so, we will be able to evaluate the reduction in the narrower bit width.
351 if (Start != Phi)
352 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
353 IsSigned, VisitedInsts, CastInsts))
354 return false;
355
Karthik Bhat76aa6622015-04-20 04:38:33 +0000356 // We found a reduction var if we have reached the original phi node and we
357 // only have a single instruction with out-of-loop users.
358
359 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000360 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000361
362 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000363 RecurrenceDescriptor RD(
364 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
365 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000366 RedDes = RD;
367
368 return true;
369}
370
371/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
372/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000373RecurrenceDescriptor::InstDesc
374RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000375
376 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
377 "Expect a select instruction");
378 Instruction *Cmp = nullptr;
379 SelectInst *Select = nullptr;
380
381 // We must handle the select(cmp()) as a single instruction. Advance to the
382 // select.
383 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
384 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000385 return InstDesc(false, I);
386 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000387 }
388
389 // Only handle single use cases for now.
390 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000391 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000392 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
393 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000394 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000395 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000396 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000397
398 Value *CmpLeft;
399 Value *CmpRight;
400
401 // Look for a min/max pattern.
402 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000403 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000404 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000405 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000406 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000407 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000408 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000409 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000410 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000411 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000412 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000413 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000414 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000415 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000416 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000417 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000418
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000419 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000420}
421
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000422RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000423RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000424 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000425 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000426 Instruction *UAI = Prev.getUnsafeAlgebraInst();
427 if (!UAI && FP && !I->hasUnsafeAlgebra())
428 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
429
Karthik Bhat76aa6622015-04-20 04:38:33 +0000430 switch (I->getOpcode()) {
431 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000432 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000433 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000434 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000435 case Instruction::Sub:
436 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000437 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000438 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000439 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000440 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000441 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000442 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000443 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000444 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000445 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000446 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000447 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000448 case Instruction::FSub:
449 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000450 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000451 case Instruction::FCmp:
452 case Instruction::ICmp:
453 case Instruction::Select:
454 if (Kind != RK_IntegerMinMax &&
455 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000456 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000457 return isMinMaxSelectCmpPattern(I, Prev);
458 }
459}
460
Tyler Nowicki0a913102015-06-16 18:07:34 +0000461bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000462 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
463 unsigned NumUses = 0;
464 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
465 ++Use) {
466 if (Insts.count(dyn_cast<Instruction>(*Use)))
467 ++NumUses;
468 if (NumUses > 1)
469 return true;
470 }
471
472 return false;
473}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000474bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
475 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000476
Karthik Bhat76aa6622015-04-20 04:38:33 +0000477 BasicBlock *Header = TheLoop->getHeader();
478 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000479 bool HasFunNoNaNAttr =
480 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000481
482 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
483 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
484 return true;
485 }
486 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
487 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
488 return true;
489 }
490 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
491 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
492 return true;
493 }
494 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
495 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
496 return true;
497 }
498 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
499 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
500 return true;
501 }
502 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
503 RedDes)) {
504 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
505 return true;
506 }
507 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
508 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
509 return true;
510 }
511 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
512 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
513 return true;
514 }
515 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
516 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
517 return true;
518 }
519 // Not a reduction of known type.
520 return false;
521}
522
Matthew Simpson29c997c2016-02-19 17:56:08 +0000523bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
524 DominatorTree *DT) {
525
526 // Ensure the phi node is in the loop header and has two incoming values.
527 if (Phi->getParent() != TheLoop->getHeader() ||
528 Phi->getNumIncomingValues() != 2)
529 return false;
530
531 // Ensure the loop has a preheader and a single latch block. The loop
532 // vectorizer will need the latch to set up the next iteration of the loop.
533 auto *Preheader = TheLoop->getLoopPreheader();
534 auto *Latch = TheLoop->getLoopLatch();
535 if (!Preheader || !Latch)
536 return false;
537
538 // Ensure the phi node's incoming blocks are the loop preheader and latch.
539 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
540 Phi->getBasicBlockIndex(Latch) < 0)
541 return false;
542
543 // Get the previous value. The previous value comes from the latch edge while
544 // the initial value comes form the preheader edge.
545 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Matthew Simpson53207a92016-04-11 19:48:18 +0000546 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
Matthew Simpson29c997c2016-02-19 17:56:08 +0000547 return false;
548
549 // Ensure every user of the phi node is dominated by the previous value. The
550 // dominance requirement ensures the loop vectorizer will not need to
551 // vectorize the initial value prior to the first iteration of the loop.
552 for (User *U : Phi->users())
553 if (auto *I = dyn_cast<Instruction>(U))
554 if (!DT->dominates(Previous, I))
555 return false;
556
557 return true;
558}
559
Karthik Bhat76aa6622015-04-20 04:38:33 +0000560/// This function returns the identity element (or neutral element) for
561/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000562Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
563 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000564 switch (K) {
565 case RK_IntegerXor:
566 case RK_IntegerAdd:
567 case RK_IntegerOr:
568 // Adding, Xoring, Oring zero to a number does not change it.
569 return ConstantInt::get(Tp, 0);
570 case RK_IntegerMult:
571 // Multiplying a number by 1 does not change it.
572 return ConstantInt::get(Tp, 1);
573 case RK_IntegerAnd:
574 // AND-ing a number with an all-1 value does not change it.
575 return ConstantInt::get(Tp, -1, true);
576 case RK_FloatMult:
577 // Multiplying a number by 1 does not change it.
578 return ConstantFP::get(Tp, 1.0L);
579 case RK_FloatAdd:
580 // Adding zero to a number does not change it.
581 return ConstantFP::get(Tp, 0.0L);
582 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000583 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000584 }
585}
586
Tyler Nowicki0a913102015-06-16 18:07:34 +0000587/// This function translates the recurrence kind to an LLVM binary operator.
588unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000589 switch (Kind) {
590 case RK_IntegerAdd:
591 return Instruction::Add;
592 case RK_IntegerMult:
593 return Instruction::Mul;
594 case RK_IntegerOr:
595 return Instruction::Or;
596 case RK_IntegerAnd:
597 return Instruction::And;
598 case RK_IntegerXor:
599 return Instruction::Xor;
600 case RK_FloatMult:
601 return Instruction::FMul;
602 case RK_FloatAdd:
603 return Instruction::FAdd;
604 case RK_IntegerMinMax:
605 return Instruction::ICmp;
606 case RK_FloatMinMax:
607 return Instruction::FCmp;
608 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000609 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000610 }
611}
612
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000613Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
614 MinMaxRecurrenceKind RK,
615 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000616 CmpInst::Predicate P = CmpInst::ICMP_NE;
617 switch (RK) {
618 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000619 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000620 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000621 P = CmpInst::ICMP_ULT;
622 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000623 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000624 P = CmpInst::ICMP_UGT;
625 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000626 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000627 P = CmpInst::ICMP_SLT;
628 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000629 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000630 P = CmpInst::ICMP_SGT;
631 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000632 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000633 P = CmpInst::FCMP_OLT;
634 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000635 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000636 P = CmpInst::FCMP_OGT;
637 break;
638 }
639
James Molloy50a4c272015-09-21 19:41:19 +0000640 // We only match FP sequences with unsafe algebra, so we can unconditionally
641 // set it on any generated instructions.
642 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
643 FastMathFlags FMF;
644 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000645 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000646
Karthik Bhat76aa6622015-04-20 04:38:33 +0000647 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000648 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000649 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
650 else
651 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
652
653 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
654 return Select;
655}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000656
James Molloy1bbf15c2015-08-27 09:53:00 +0000657InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000658 const SCEV *Step, BinaryOperator *BOp)
659 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000660 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000661
662 // Start value type should match the induction kind and the value
663 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000664 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000665 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
666 "StartValue is not a pointer for pointer induction");
667 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
668 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000669
670 // Check the Step Value. It should be non-zero integer value.
671 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
672 "Step value is zero");
673
674 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
675 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000676 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
677 "StepValue is not an integer");
678
679 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
680 "StepValue is not FP for FpInduction");
681 assert((IK != IK_FpInduction || (InductionBinOp &&
682 (InductionBinOp->getOpcode() == Instruction::FAdd ||
683 InductionBinOp->getOpcode() == Instruction::FSub))) &&
684 "Binary opcode should be specified for FP induction");
James Molloy1bbf15c2015-08-27 09:53:00 +0000685}
686
687int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000688 ConstantInt *ConstStep = getConstIntStepValue();
689 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
690 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000691 return 0;
692}
693
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000694ConstantInt *InductionDescriptor::getConstIntStepValue() const {
695 if (isa<SCEVConstant>(Step))
696 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
697 return nullptr;
698}
699
700Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
701 ScalarEvolution *SE,
702 const DataLayout& DL) const {
703
704 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000705 assert(Index->getType() == Step->getType() &&
706 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000707 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000708 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000709 assert(Index->getType() == StartValue->getType() &&
710 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000711
712 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
713 // and calculate (Start + Index * Step) for all cases, without
714 // special handling for "isOne" and "isMinusOne".
715 // But in the real life the result code getting worse. We mix SCEV
716 // expressions and ADD/SUB operations and receive redundant
717 // intermediate values being calculated in different ways and
718 // Instcombine is unable to reduce them all.
719
720 if (getConstIntStepValue() &&
721 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000722 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000723 if (getConstIntStepValue() &&
724 getConstIntStepValue()->isOne())
725 return B.CreateAdd(StartValue, Index);
726 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
727 SE->getMulExpr(Step, SE->getSCEV(Index)));
728 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
729 }
730 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000731 assert(isa<SCEVConstant>(Step) &&
732 "Expected constant step for pointer induction");
733 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
734 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000735 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000736 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000737 case IK_FpInduction: {
738 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
739 assert(InductionBinOp &&
740 (InductionBinOp->getOpcode() == Instruction::FAdd ||
741 InductionBinOp->getOpcode() == Instruction::FSub) &&
742 "Original bin op should be defined for FP induction");
743
744 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
745
746 // Floating point operations had to be 'fast' to enable the induction.
747 FastMathFlags Flags;
748 Flags.setUnsafeAlgebra();
749
750 Value *MulExp = B.CreateFMul(StepValue, Index);
751 if (isa<Instruction>(MulExp))
752 // We have to check, the MulExp may be a constant.
753 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
754
755 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
756 MulExp, "induction");
757 if (isa<Instruction>(BOp))
758 cast<Instruction>(BOp)->setFastMathFlags(Flags);
759
760 return BOp;
761 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000762 case IK_NoInduction:
763 return nullptr;
764 }
765 llvm_unreachable("invalid enum");
766}
767
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000768bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
769 ScalarEvolution *SE,
770 InductionDescriptor &D) {
771
772 // Here we only handle FP induction variables.
773 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
774
775 if (TheLoop->getHeader() != Phi->getParent())
776 return false;
777
778 // The loop may have multiple entrances or multiple exits; we can analyze
779 // this phi if it has a unique entry value and a unique backedge value.
780 if (Phi->getNumIncomingValues() != 2)
781 return false;
782 Value *BEValue = nullptr, *StartValue = nullptr;
783 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
784 BEValue = Phi->getIncomingValue(0);
785 StartValue = Phi->getIncomingValue(1);
786 } else {
787 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
788 "Unexpected Phi node in the loop");
789 BEValue = Phi->getIncomingValue(1);
790 StartValue = Phi->getIncomingValue(0);
791 }
792
793 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
794 if (!BOp)
795 return false;
796
797 Value *Addend = nullptr;
798 if (BOp->getOpcode() == Instruction::FAdd) {
799 if (BOp->getOperand(0) == Phi)
800 Addend = BOp->getOperand(1);
801 else if (BOp->getOperand(1) == Phi)
802 Addend = BOp->getOperand(0);
803 } else if (BOp->getOpcode() == Instruction::FSub)
804 if (BOp->getOperand(0) == Phi)
805 Addend = BOp->getOperand(1);
806
807 if (!Addend)
808 return false;
809
810 // The addend should be loop invariant
811 if (auto *I = dyn_cast<Instruction>(Addend))
812 if (TheLoop->contains(I))
813 return false;
814
815 // FP Step has unknown SCEV
816 const SCEV *Step = SE->getUnknown(Addend);
817 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
818 return true;
819}
820
821bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000822 PredicatedScalarEvolution &PSE,
823 InductionDescriptor &D,
824 bool Assume) {
825 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000826
827 // Handle integer and pointer inductions variables.
828 // Now we handle also FP induction but not trying to make a
829 // recurrent expression from the PHI node in-place.
830
831 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
832 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +0000833 return false;
834
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000835 if (PhiTy->isFloatingPointTy())
836 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
837
Silviu Barangac05bab82016-05-05 15:20:39 +0000838 const SCEV *PhiScev = PSE.getSCEV(Phi);
839 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
840
841 // We need this expression to be an AddRecExpr.
842 if (Assume && !AR)
843 AR = PSE.getAsAddRec(Phi);
844
845 if (!AR) {
846 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
847 return false;
848 }
849
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000850 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +0000851}
852
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000853bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000854 ScalarEvolution *SE,
855 InductionDescriptor &D,
856 const SCEV *Expr) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000857 Type *PhiTy = Phi->getType();
858 // We only handle integer and pointer inductions variables.
859 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
860 return false;
861
862 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +0000863 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000864 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +0000865
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000866 if (!AR) {
867 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
868 return false;
869 }
870
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000871 assert(TheLoop->getHeader() == Phi->getParent() &&
James Molloy1bbf15c2015-08-27 09:53:00 +0000872 "PHI is an AddRec for a different loop?!");
873 Value *StartValue =
874 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000875 const SCEV *Step = AR->getStepRecurrence(*SE);
876 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000877 // The stride may be a constant or a loop invariant integer value.
878 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000879 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000880 return false;
881
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000882 if (PhiTy->isIntegerTy()) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000883 D = InductionDescriptor(StartValue, IK_IntInduction, Step);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000884 return true;
885 }
886
887 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000888 // Pointer induction should be a constant.
889 if (!ConstStep)
890 return false;
891
892 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000893 Type *PointerElementType = PhiTy->getPointerElementType();
894 // The pointer stride cannot be determined if the pointer element type is not
895 // sized.
896 if (!PointerElementType->isSized())
897 return false;
898
899 const DataLayout &DL = Phi->getModule()->getDataLayout();
900 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000901 if (!Size)
902 return false;
903
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000904 int64_t CVSize = CV->getSExtValue();
905 if (CVSize % Size)
906 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000907 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
908 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +0000909 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000910 return true;
911}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000912
913/// \brief Returns the instructions that use values defined in the loop.
914SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
915 SmallVector<Instruction *, 8> UsedOutside;
916
917 for (auto *Block : L->getBlocks())
918 // FIXME: I believe that this could use copy_if if the Inst reference could
919 // be adapted into a pointer.
920 for (auto &Inst : *Block) {
921 auto Users = Inst.users();
922 if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
923 auto *Use = cast<Instruction>(U);
924 return !L->contains(Use->getParent());
925 }))
926 UsedOutside.push_back(&Inst);
927 }
928
929 return UsedOutside;
930}
Chandler Carruth31088a92016-02-19 10:45:18 +0000931
932void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
933 // By definition, all loop passes need the LoopInfo analysis and the
934 // Dominator tree it depends on. Because they all participate in the loop
935 // pass manager, they must also preserve these.
936 AU.addRequired<DominatorTreeWrapperPass>();
937 AU.addPreserved<DominatorTreeWrapperPass>();
938 AU.addRequired<LoopInfoWrapperPass>();
939 AU.addPreserved<LoopInfoWrapperPass>();
940
941 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
942 // here because users shouldn't directly get them from this header.
943 extern char &LoopSimplifyID;
944 extern char &LCSSAID;
945 AU.addRequiredID(LoopSimplifyID);
946 AU.addPreservedID(LoopSimplifyID);
947 AU.addRequiredID(LCSSAID);
948 AU.addPreservedID(LCSSAID);
949
950 // Loop passes are designed to run inside of a loop pass manager which means
951 // that any function analyses they require must be required by the first loop
952 // pass in the manager (so that it is computed before the loop pass manager
953 // runs) and preserved by all loop pasess in the manager. To make this
954 // reasonably robust, the set needed for most loop passes is maintained here.
955 // If your loop pass requires an analysis not listed here, you will need to
956 // carefully audit the loop pass manager nesting structure that results.
957 AU.addRequired<AAResultsWrapperPass>();
958 AU.addPreserved<AAResultsWrapperPass>();
959 AU.addPreserved<BasicAAWrapperPass>();
960 AU.addPreserved<GlobalsAAWrapperPass>();
961 AU.addPreserved<SCEVAAWrapperPass>();
962 AU.addRequired<ScalarEvolutionWrapperPass>();
963 AU.addPreserved<ScalarEvolutionWrapperPass>();
964}
965
966/// Manually defined generic "LoopPass" dependency initialization. This is used
967/// to initialize the exact set of passes from above in \c
968/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
969/// with:
970///
971/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
972///
973/// As-if "LoopPass" were a pass.
974void llvm::initializeLoopPassPass(PassRegistry &Registry) {
975 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
976 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
977 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000978 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000979 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
980 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
981 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
982 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
983 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
984}
Adam Nemet963341c2016-04-21 17:33:17 +0000985
Adam Nemetfe3def72016-04-22 19:10:05 +0000986/// \brief Find string metadata for loop
987///
988/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
989/// operand or null otherwise. If the string metadata is not found return
990/// Optional's not-a-value.
991Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
992 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +0000993 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +0000994 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +0000995 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +0000996 return None;
Adam Nemet293be662016-04-21 17:33:20 +0000997
998 // First operand should refer to the loop id itself.
999 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1000 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1001
Adam Nemet963341c2016-04-21 17:33:17 +00001002 // Iterate over LoopID operands and look for MDString Metadata
1003 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1004 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1005 if (!MD)
1006 continue;
1007 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1008 if (!S)
1009 continue;
1010 // Return true if MDString holds expected MetaData.
1011 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001012 switch (MD->getNumOperands()) {
1013 case 1:
1014 return nullptr;
1015 case 2:
1016 return &MD->getOperand(1);
1017 default:
1018 llvm_unreachable("loop metadata has 0 or 1 operand");
1019 }
Adam Nemet963341c2016-04-21 17:33:17 +00001020 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001021 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001022}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001023
1024/// Returns true if the instruction in a loop is guaranteed to execute at least
1025/// once.
1026bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1027 const DominatorTree *DT, const Loop *CurLoop,
1028 const LoopSafetyInfo *SafetyInfo) {
1029 // We have to check to make sure that the instruction dominates all
1030 // of the exit blocks. If it doesn't, then there is a path out of the loop
1031 // which does not execute this instruction, so we can't hoist it.
1032
1033 // If the instruction is in the header block for the loop (which is very
1034 // common), it is always guaranteed to dominate the exit blocks. Since this
1035 // is a common case, and can save some work, check it now.
1036 if (Inst.getParent() == CurLoop->getHeader())
1037 // If there's a throw in the header block, we can't guarantee we'll reach
1038 // Inst.
1039 return !SafetyInfo->HeaderMayThrow;
1040
1041 // Somewhere in this loop there is an instruction which may throw and make us
1042 // exit the loop.
1043 if (SafetyInfo->MayThrow)
1044 return false;
1045
1046 // Get the exit blocks for the current loop.
1047 SmallVector<BasicBlock *, 8> ExitBlocks;
1048 CurLoop->getExitBlocks(ExitBlocks);
1049
1050 // Verify that the block dominates each of the exit blocks of the loop.
1051 for (BasicBlock *ExitBlock : ExitBlocks)
1052 if (!DT->dominates(Inst.getParent(), ExitBlock))
1053 return false;
1054
1055 // As a degenerate case, if the loop is statically infinite then we haven't
1056 // proven anything since there are no exit blocks.
1057 if (ExitBlocks.empty())
1058 return false;
1059
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001060 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1061 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1062 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001063 return true;
1064}