blob: 624db3ca7c6de52416013b44078e0b0f3d0b96d6 [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"
Adam Nemet12937c32016-07-29 19:29:47 +000020#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000022#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000023#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000024#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000025#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000026#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000027#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000028#include "llvm/IR/PatternMatch.h"
29#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000030#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000031#include "llvm/Support/Debug.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000032
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36#define DEBUG_TYPE "loop-utils"
37
Tyler Nowicki0a913102015-06-16 18:07:34 +000038bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
39 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000040 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
41 if (!Set.count(dyn_cast<Instruction>(*Use)))
42 return false;
43 return true;
44}
45
Chad Rosierc94f8e22015-08-27 14:12:17 +000046bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
47 switch (Kind) {
48 default:
49 break;
50 case RK_IntegerAdd:
51 case RK_IntegerMult:
52 case RK_IntegerOr:
53 case RK_IntegerAnd:
54 case RK_IntegerXor:
55 case RK_IntegerMinMax:
56 return true;
57 }
58 return false;
59}
60
61bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
62 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
63}
64
65bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
66 switch (Kind) {
67 default:
68 break;
69 case RK_IntegerAdd:
70 case RK_IntegerMult:
71 case RK_FloatAdd:
72 case RK_FloatMult:
73 return true;
74 }
75 return false;
76}
77
78Instruction *
79RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
80 SmallPtrSetImpl<Instruction *> &Visited,
81 SmallPtrSetImpl<Instruction *> &CI) {
82 if (!Phi->hasOneUse())
83 return Phi;
84
85 const APInt *M = nullptr;
86 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
87
88 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
89 // with a new integer type of the corresponding bit width.
90 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
91 m_And(m_APInt(M), m_Instruction(I))))) {
92 int32_t Bits = (*M + 1).exactLogBase2();
93 if (Bits > 0) {
94 RT = IntegerType::get(Phi->getContext(), Bits);
95 Visited.insert(Phi);
96 CI.insert(J);
97 return J;
98 }
99 }
100 return Phi;
101}
102
103bool RecurrenceDescriptor::getSourceExtensionKind(
104 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
105 SmallPtrSetImpl<Instruction *> &Visited,
106 SmallPtrSetImpl<Instruction *> &CI) {
107
108 SmallVector<Instruction *, 8> Worklist;
109 bool FoundOneOperand = false;
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000110 unsigned DstSize = RT->getPrimitiveSizeInBits();
Chad Rosierc94f8e22015-08-27 14:12:17 +0000111 Worklist.push_back(Exit);
112
113 // Traverse the instructions in the reduction expression, beginning with the
114 // exit value.
115 while (!Worklist.empty()) {
116 Instruction *I = Worklist.pop_back_val();
117 for (Use &U : I->operands()) {
118
119 // Terminate the traversal if the operand is not an instruction, or we
120 // reach the starting value.
121 Instruction *J = dyn_cast<Instruction>(U.get());
122 if (!J || J == Start)
123 continue;
124
125 // Otherwise, investigate the operation if it is also in the expression.
126 if (Visited.count(J)) {
127 Worklist.push_back(J);
128 continue;
129 }
130
131 // If the operand is not in Visited, it is not a reduction operation, but
132 // it does feed into one. Make sure it is either a single-use sign- or
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000133 // zero-extend instruction.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000134 CastInst *Cast = dyn_cast<CastInst>(J);
135 bool IsSExtInst = isa<SExtInst>(J);
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000136 if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
137 return false;
138
139 // Ensure the source type of the extend is no larger than the reduction
140 // type. It is not necessary for the types to be identical.
141 unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
142 if (SrcSize > DstSize)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000143 return false;
144
145 // Furthermore, ensure that all such extends are of the same kind.
146 if (FoundOneOperand) {
147 if (IsSigned != IsSExtInst)
148 return false;
149 } else {
150 FoundOneOperand = true;
151 IsSigned = IsSExtInst;
152 }
153
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000154 // Lastly, if the source type of the extend matches the reduction type,
155 // add the extend to CI so that we can avoid accounting for it in the
156 // cost model.
157 if (SrcSize == DstSize)
158 CI.insert(Cast);
Chad Rosierc94f8e22015-08-27 14:12:17 +0000159 }
160 }
161 return true;
162}
163
Tyler Nowicki0a913102015-06-16 18:07:34 +0000164bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
165 Loop *TheLoop, bool HasFunNoNaNAttr,
166 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000167 if (Phi->getNumIncomingValues() != 2)
168 return false;
169
170 // Reduction variables are only found in the loop header block.
171 if (Phi->getParent() != TheLoop->getHeader())
172 return false;
173
174 // Obtain the reduction start value from the value that comes from the loop
175 // preheader.
176 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
177
178 // ExitInstruction is the single value which is used outside the loop.
179 // We only allow for a single reduction value to be used outside the loop.
180 // This includes users of the reduction, variables (which form a cycle
181 // which ends in the phi node).
182 Instruction *ExitInstruction = nullptr;
183 // Indicates that we found a reduction operation in our scan.
184 bool FoundReduxOp = false;
185
186 // We start with the PHI node and scan for all of the users of this
187 // instruction. All users must be instructions that can be used as reduction
188 // variables (such as ADD). We must have a single out-of-block user. The cycle
189 // must include the original PHI.
190 bool FoundStartPHI = false;
191
192 // To recognize min/max patterns formed by a icmp select sequence, we store
193 // the number of instruction we saw from the recognized min/max pattern,
194 // to make sure we only see exactly the two instructions.
195 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000196 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000197
Chad Rosierc94f8e22015-08-27 14:12:17 +0000198 // Data used for determining if the recurrence has been type-promoted.
199 Type *RecurrenceType = Phi->getType();
200 SmallPtrSet<Instruction *, 4> CastInsts;
201 Instruction *Start = Phi;
202 bool IsSigned = false;
203
Karthik Bhat76aa6622015-04-20 04:38:33 +0000204 SmallPtrSet<Instruction *, 8> VisitedInsts;
205 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000206
207 // Return early if the recurrence kind does not match the type of Phi. If the
208 // recurrence kind is arithmetic, we attempt to look through AND operations
209 // resulting from the type promotion performed by InstCombine. Vector
210 // operations are not limited to the legal integer widths, so we may be able
211 // to evaluate the reduction in the narrower width.
212 if (RecurrenceType->isFloatingPointTy()) {
213 if (!isFloatingPointRecurrenceKind(Kind))
214 return false;
215 } else {
216 if (!isIntegerRecurrenceKind(Kind))
217 return false;
218 if (isArithmeticRecurrenceKind(Kind))
219 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
220 }
221
222 Worklist.push_back(Start);
223 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000224
225 // A value in the reduction can be used:
226 // - By the reduction:
227 // - Reduction operation:
228 // - One use of reduction value (safe).
229 // - Multiple use of reduction value (not safe).
230 // - PHI:
231 // - All uses of the PHI must be the reduction (safe).
232 // - Otherwise, not safe.
233 // - By one instruction outside of the loop (safe).
234 // - By further instructions outside of the loop (not safe).
235 // - By an instruction that is not part of the reduction (not safe).
236 // This is either:
237 // * An instruction type other than PHI or the reduction operation.
238 // * A PHI in the header other than the initial PHI.
239 while (!Worklist.empty()) {
240 Instruction *Cur = Worklist.back();
241 Worklist.pop_back();
242
243 // No Users.
244 // If the instruction has no users then this is a broken chain and can't be
245 // a reduction variable.
246 if (Cur->use_empty())
247 return false;
248
249 bool IsAPhi = isa<PHINode>(Cur);
250
251 // A header PHI use other than the original PHI.
252 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
253 return false;
254
255 // Reductions of instructions such as Div, and Sub is only possible if the
256 // LHS is the reduction variable.
257 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
258 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
259 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
260 return false;
261
Chad Rosierc94f8e22015-08-27 14:12:17 +0000262 // Any reduction instruction must be of one of the allowed kinds. We ignore
263 // the starting value (the Phi or an AND instruction if the Phi has been
264 // type-promoted).
265 if (Cur != Start) {
266 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
267 if (!ReduxDesc.isRecurrence())
268 return false;
269 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000270
271 // A reduction operation must only have one use of the reduction value.
272 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
273 hasMultipleUsesOf(Cur, VisitedInsts))
274 return false;
275
276 // All inputs to a PHI node must be a reduction value.
277 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
278 return false;
279
280 if (Kind == RK_IntegerMinMax &&
281 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
282 ++NumCmpSelectPatternInst;
283 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
284 ++NumCmpSelectPatternInst;
285
286 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000287 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000288
289 // Process users of current instruction. Push non-PHI nodes after PHI nodes
290 // onto the stack. This way we are going to have seen all inputs to PHI
291 // nodes once we get to them.
292 SmallVector<Instruction *, 8> NonPHIs;
293 SmallVector<Instruction *, 8> PHIs;
294 for (User *U : Cur->users()) {
295 Instruction *UI = cast<Instruction>(U);
296
297 // Check if we found the exit user.
298 BasicBlock *Parent = UI->getParent();
299 if (!TheLoop->contains(Parent)) {
300 // Exit if you find multiple outside users or if the header phi node is
301 // being used. In this case the user uses the value of the previous
302 // iteration, in which case we would loose "VF-1" iterations of the
303 // reduction operation if we vectorize.
304 if (ExitInstruction != nullptr || Cur == Phi)
305 return false;
306
307 // The instruction used by an outside user must be the last instruction
308 // before we feed back to the reduction phi. Otherwise, we loose VF-1
309 // operations on the value.
David Majnemer42531262016-08-12 03:55:06 +0000310 if (!is_contained(Phi->operands(), Cur))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000311 return false;
312
313 ExitInstruction = Cur;
314 continue;
315 }
316
317 // Process instructions only once (termination). Each reduction cycle
318 // value must only be used once, except by phi nodes and min/max
319 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000320 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000321 if (VisitedInsts.insert(UI).second) {
322 if (isa<PHINode>(UI))
323 PHIs.push_back(UI);
324 else
325 NonPHIs.push_back(UI);
326 } else if (!isa<PHINode>(UI) &&
327 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
328 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000329 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000330 return false;
331
332 // Remember that we completed the cycle.
333 if (UI == Phi)
334 FoundStartPHI = true;
335 }
336 Worklist.append(PHIs.begin(), PHIs.end());
337 Worklist.append(NonPHIs.begin(), NonPHIs.end());
338 }
339
340 // This means we have seen one but not the other instruction of the
341 // pattern or more than just a select and cmp.
342 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
343 NumCmpSelectPatternInst != 2)
344 return false;
345
346 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
347 return false;
348
Chad Rosierc94f8e22015-08-27 14:12:17 +0000349 // If we think Phi may have been type-promoted, we also need to ensure that
350 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
351 // so, we will be able to evaluate the reduction in the narrower bit width.
352 if (Start != Phi)
353 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
354 IsSigned, VisitedInsts, CastInsts))
355 return false;
356
Karthik Bhat76aa6622015-04-20 04:38:33 +0000357 // We found a reduction var if we have reached the original phi node and we
358 // only have a single instruction with out-of-loop users.
359
360 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000361 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000362
363 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000364 RecurrenceDescriptor RD(
365 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
366 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000367 RedDes = RD;
368
369 return true;
370}
371
372/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
373/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000374RecurrenceDescriptor::InstDesc
375RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000376
377 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
378 "Expect a select instruction");
379 Instruction *Cmp = nullptr;
380 SelectInst *Select = nullptr;
381
382 // We must handle the select(cmp()) as a single instruction. Advance to the
383 // select.
384 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
385 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000386 return InstDesc(false, I);
387 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000388 }
389
390 // Only handle single use cases for now.
391 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000392 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000393 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
394 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000395 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000396 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000397 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000398
399 Value *CmpLeft;
400 Value *CmpRight;
401
402 // Look for a min/max pattern.
403 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000404 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000405 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000406 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000407 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000408 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000409 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000410 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000411 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000412 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000413 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000414 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000415 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000416 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000417 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000418 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000419
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000420 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000421}
422
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000423RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000424RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000425 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000426 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000427 Instruction *UAI = Prev.getUnsafeAlgebraInst();
428 if (!UAI && FP && !I->hasUnsafeAlgebra())
429 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
430
Karthik Bhat76aa6622015-04-20 04:38:33 +0000431 switch (I->getOpcode()) {
432 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000433 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000434 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000435 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000436 case Instruction::Sub:
437 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000438 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000439 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000440 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000441 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000442 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000443 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000444 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000445 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000446 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000447 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000448 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000449 case Instruction::FSub:
450 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000451 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000452 case Instruction::FCmp:
453 case Instruction::ICmp:
454 case Instruction::Select:
455 if (Kind != RK_IntegerMinMax &&
456 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000457 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000458 return isMinMaxSelectCmpPattern(I, Prev);
459 }
460}
461
Tyler Nowicki0a913102015-06-16 18:07:34 +0000462bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000463 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
464 unsigned NumUses = 0;
465 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
466 ++Use) {
467 if (Insts.count(dyn_cast<Instruction>(*Use)))
468 ++NumUses;
469 if (NumUses > 1)
470 return true;
471 }
472
473 return false;
474}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000475bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
476 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000477
Karthik Bhat76aa6622015-04-20 04:38:33 +0000478 BasicBlock *Header = TheLoop->getHeader();
479 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000480 bool HasFunNoNaNAttr =
481 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000482
483 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
484 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
485 return true;
486 }
487 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
488 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
489 return true;
490 }
491 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
492 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
493 return true;
494 }
495 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
496 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
497 return true;
498 }
499 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
500 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
501 return true;
502 }
503 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
504 RedDes)) {
505 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
506 return true;
507 }
508 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
509 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
510 return true;
511 }
512 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
513 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
514 return true;
515 }
516 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
517 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
518 return true;
519 }
520 // Not a reduction of known type.
521 return false;
522}
523
Matthew Simpson29c997c2016-02-19 17:56:08 +0000524bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
525 DominatorTree *DT) {
526
527 // Ensure the phi node is in the loop header and has two incoming values.
528 if (Phi->getParent() != TheLoop->getHeader() ||
529 Phi->getNumIncomingValues() != 2)
530 return false;
531
532 // Ensure the loop has a preheader and a single latch block. The loop
533 // vectorizer will need the latch to set up the next iteration of the loop.
534 auto *Preheader = TheLoop->getLoopPreheader();
535 auto *Latch = TheLoop->getLoopLatch();
536 if (!Preheader || !Latch)
537 return false;
538
539 // Ensure the phi node's incoming blocks are the loop preheader and latch.
540 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
541 Phi->getBasicBlockIndex(Latch) < 0)
542 return false;
543
544 // Get the previous value. The previous value comes from the latch edge while
545 // the initial value comes form the preheader edge.
546 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Matthew Simpson53207a92016-04-11 19:48:18 +0000547 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
Matthew Simpson29c997c2016-02-19 17:56:08 +0000548 return false;
549
550 // Ensure every user of the phi node is dominated by the previous value. The
551 // dominance requirement ensures the loop vectorizer will not need to
552 // vectorize the initial value prior to the first iteration of the loop.
553 for (User *U : Phi->users())
554 if (auto *I = dyn_cast<Instruction>(U))
555 if (!DT->dominates(Previous, I))
556 return false;
557
558 return true;
559}
560
Karthik Bhat76aa6622015-04-20 04:38:33 +0000561/// This function returns the identity element (or neutral element) for
562/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000563Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
564 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000565 switch (K) {
566 case RK_IntegerXor:
567 case RK_IntegerAdd:
568 case RK_IntegerOr:
569 // Adding, Xoring, Oring zero to a number does not change it.
570 return ConstantInt::get(Tp, 0);
571 case RK_IntegerMult:
572 // Multiplying a number by 1 does not change it.
573 return ConstantInt::get(Tp, 1);
574 case RK_IntegerAnd:
575 // AND-ing a number with an all-1 value does not change it.
576 return ConstantInt::get(Tp, -1, true);
577 case RK_FloatMult:
578 // Multiplying a number by 1 does not change it.
579 return ConstantFP::get(Tp, 1.0L);
580 case RK_FloatAdd:
581 // Adding zero to a number does not change it.
582 return ConstantFP::get(Tp, 0.0L);
583 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000584 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000585 }
586}
587
Tyler Nowicki0a913102015-06-16 18:07:34 +0000588/// This function translates the recurrence kind to an LLVM binary operator.
589unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000590 switch (Kind) {
591 case RK_IntegerAdd:
592 return Instruction::Add;
593 case RK_IntegerMult:
594 return Instruction::Mul;
595 case RK_IntegerOr:
596 return Instruction::Or;
597 case RK_IntegerAnd:
598 return Instruction::And;
599 case RK_IntegerXor:
600 return Instruction::Xor;
601 case RK_FloatMult:
602 return Instruction::FMul;
603 case RK_FloatAdd:
604 return Instruction::FAdd;
605 case RK_IntegerMinMax:
606 return Instruction::ICmp;
607 case RK_FloatMinMax:
608 return Instruction::FCmp;
609 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000610 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000611 }
612}
613
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000614Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
615 MinMaxRecurrenceKind RK,
616 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000617 CmpInst::Predicate P = CmpInst::ICMP_NE;
618 switch (RK) {
619 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000620 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000621 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000622 P = CmpInst::ICMP_ULT;
623 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000624 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000625 P = CmpInst::ICMP_UGT;
626 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000627 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000628 P = CmpInst::ICMP_SLT;
629 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000630 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000631 P = CmpInst::ICMP_SGT;
632 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000633 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000634 P = CmpInst::FCMP_OLT;
635 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000636 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000637 P = CmpInst::FCMP_OGT;
638 break;
639 }
640
James Molloy50a4c272015-09-21 19:41:19 +0000641 // We only match FP sequences with unsafe algebra, so we can unconditionally
642 // set it on any generated instructions.
643 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
644 FastMathFlags FMF;
645 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000646 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000647
Karthik Bhat76aa6622015-04-20 04:38:33 +0000648 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000649 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000650 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
651 else
652 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
653
654 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
655 return Select;
656}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000657
James Molloy1bbf15c2015-08-27 09:53:00 +0000658InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000659 const SCEV *Step, BinaryOperator *BOp)
660 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000661 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000662
663 // Start value type should match the induction kind and the value
664 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000665 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000666 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
667 "StartValue is not a pointer for pointer induction");
668 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
669 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000670
671 // Check the Step Value. It should be non-zero integer value.
672 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
673 "Step value is zero");
674
675 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
676 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000677 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
678 "StepValue is not an integer");
679
680 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
681 "StepValue is not FP for FpInduction");
682 assert((IK != IK_FpInduction || (InductionBinOp &&
683 (InductionBinOp->getOpcode() == Instruction::FAdd ||
684 InductionBinOp->getOpcode() == Instruction::FSub))) &&
685 "Binary opcode should be specified for FP induction");
James Molloy1bbf15c2015-08-27 09:53:00 +0000686}
687
688int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000689 ConstantInt *ConstStep = getConstIntStepValue();
690 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
691 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000692 return 0;
693}
694
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000695ConstantInt *InductionDescriptor::getConstIntStepValue() const {
696 if (isa<SCEVConstant>(Step))
697 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
698 return nullptr;
699}
700
701Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
702 ScalarEvolution *SE,
703 const DataLayout& DL) const {
704
705 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000706 assert(Index->getType() == Step->getType() &&
707 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000708 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000709 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000710 assert(Index->getType() == StartValue->getType() &&
711 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000712
713 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
714 // and calculate (Start + Index * Step) for all cases, without
715 // special handling for "isOne" and "isMinusOne".
716 // But in the real life the result code getting worse. We mix SCEV
717 // expressions and ADD/SUB operations and receive redundant
718 // intermediate values being calculated in different ways and
719 // Instcombine is unable to reduce them all.
720
721 if (getConstIntStepValue() &&
722 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000723 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000724 if (getConstIntStepValue() &&
725 getConstIntStepValue()->isOne())
726 return B.CreateAdd(StartValue, Index);
727 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
728 SE->getMulExpr(Step, SE->getSCEV(Index)));
729 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
730 }
731 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000732 assert(isa<SCEVConstant>(Step) &&
733 "Expected constant step for pointer induction");
734 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
735 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000736 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000737 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000738 case IK_FpInduction: {
739 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
740 assert(InductionBinOp &&
741 (InductionBinOp->getOpcode() == Instruction::FAdd ||
742 InductionBinOp->getOpcode() == Instruction::FSub) &&
743 "Original bin op should be defined for FP induction");
744
745 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
746
747 // Floating point operations had to be 'fast' to enable the induction.
748 FastMathFlags Flags;
749 Flags.setUnsafeAlgebra();
750
751 Value *MulExp = B.CreateFMul(StepValue, Index);
752 if (isa<Instruction>(MulExp))
753 // We have to check, the MulExp may be a constant.
754 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
755
756 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
757 MulExp, "induction");
758 if (isa<Instruction>(BOp))
759 cast<Instruction>(BOp)->setFastMathFlags(Flags);
760
761 return BOp;
762 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000763 case IK_NoInduction:
764 return nullptr;
765 }
766 llvm_unreachable("invalid enum");
767}
768
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000769bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
770 ScalarEvolution *SE,
771 InductionDescriptor &D) {
772
773 // Here we only handle FP induction variables.
774 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
775
776 if (TheLoop->getHeader() != Phi->getParent())
777 return false;
778
779 // The loop may have multiple entrances or multiple exits; we can analyze
780 // this phi if it has a unique entry value and a unique backedge value.
781 if (Phi->getNumIncomingValues() != 2)
782 return false;
783 Value *BEValue = nullptr, *StartValue = nullptr;
784 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
785 BEValue = Phi->getIncomingValue(0);
786 StartValue = Phi->getIncomingValue(1);
787 } else {
788 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
789 "Unexpected Phi node in the loop");
790 BEValue = Phi->getIncomingValue(1);
791 StartValue = Phi->getIncomingValue(0);
792 }
793
794 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
795 if (!BOp)
796 return false;
797
798 Value *Addend = nullptr;
799 if (BOp->getOpcode() == Instruction::FAdd) {
800 if (BOp->getOperand(0) == Phi)
801 Addend = BOp->getOperand(1);
802 else if (BOp->getOperand(1) == Phi)
803 Addend = BOp->getOperand(0);
804 } else if (BOp->getOpcode() == Instruction::FSub)
805 if (BOp->getOperand(0) == Phi)
806 Addend = BOp->getOperand(1);
807
808 if (!Addend)
809 return false;
810
811 // The addend should be loop invariant
812 if (auto *I = dyn_cast<Instruction>(Addend))
813 if (TheLoop->contains(I))
814 return false;
815
816 // FP Step has unknown SCEV
817 const SCEV *Step = SE->getUnknown(Addend);
818 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
819 return true;
820}
821
822bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000823 PredicatedScalarEvolution &PSE,
824 InductionDescriptor &D,
825 bool Assume) {
826 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000827
828 // Handle integer and pointer inductions variables.
829 // Now we handle also FP induction but not trying to make a
830 // recurrent expression from the PHI node in-place.
831
832 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
833 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +0000834 return false;
835
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000836 if (PhiTy->isFloatingPointTy())
837 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
838
Silviu Barangac05bab82016-05-05 15:20:39 +0000839 const SCEV *PhiScev = PSE.getSCEV(Phi);
840 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
841
842 // We need this expression to be an AddRecExpr.
843 if (Assume && !AR)
844 AR = PSE.getAsAddRec(Phi);
845
846 if (!AR) {
847 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
848 return false;
849 }
850
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000851 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +0000852}
853
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000854bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000855 ScalarEvolution *SE,
856 InductionDescriptor &D,
857 const SCEV *Expr) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000858 Type *PhiTy = Phi->getType();
859 // We only handle integer and pointer inductions variables.
860 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
861 return false;
862
863 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +0000864 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000865 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +0000866
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000867 if (!AR) {
868 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
869 return false;
870 }
871
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000872 assert(TheLoop->getHeader() == Phi->getParent() &&
James Molloy1bbf15c2015-08-27 09:53:00 +0000873 "PHI is an AddRec for a different loop?!");
874 Value *StartValue =
875 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000876 const SCEV *Step = AR->getStepRecurrence(*SE);
877 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000878 // The stride may be a constant or a loop invariant integer value.
879 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000880 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000881 return false;
882
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000883 if (PhiTy->isIntegerTy()) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000884 D = InductionDescriptor(StartValue, IK_IntInduction, Step);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000885 return true;
886 }
887
888 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000889 // Pointer induction should be a constant.
890 if (!ConstStep)
891 return false;
892
893 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000894 Type *PointerElementType = PhiTy->getPointerElementType();
895 // The pointer stride cannot be determined if the pointer element type is not
896 // sized.
897 if (!PointerElementType->isSized())
898 return false;
899
900 const DataLayout &DL = Phi->getModule()->getDataLayout();
901 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000902 if (!Size)
903 return false;
904
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000905 int64_t CVSize = CV->getSExtValue();
906 if (CVSize % Size)
907 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000908 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
909 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +0000910 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000911 return true;
912}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000913
914/// \brief Returns the instructions that use values defined in the loop.
915SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
916 SmallVector<Instruction *, 8> UsedOutside;
917
918 for (auto *Block : L->getBlocks())
919 // FIXME: I believe that this could use copy_if if the Inst reference could
920 // be adapted into a pointer.
921 for (auto &Inst : *Block) {
922 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000923 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000924 auto *Use = cast<Instruction>(U);
925 return !L->contains(Use->getParent());
926 }))
927 UsedOutside.push_back(&Inst);
928 }
929
930 return UsedOutside;
931}
Chandler Carruth31088a92016-02-19 10:45:18 +0000932
933void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
934 // By definition, all loop passes need the LoopInfo analysis and the
935 // Dominator tree it depends on. Because they all participate in the loop
936 // pass manager, they must also preserve these.
937 AU.addRequired<DominatorTreeWrapperPass>();
938 AU.addPreserved<DominatorTreeWrapperPass>();
939 AU.addRequired<LoopInfoWrapperPass>();
940 AU.addPreserved<LoopInfoWrapperPass>();
941
942 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
943 // here because users shouldn't directly get them from this header.
944 extern char &LoopSimplifyID;
945 extern char &LCSSAID;
946 AU.addRequiredID(LoopSimplifyID);
947 AU.addPreservedID(LoopSimplifyID);
948 AU.addRequiredID(LCSSAID);
949 AU.addPreservedID(LCSSAID);
950
951 // Loop passes are designed to run inside of a loop pass manager which means
952 // that any function analyses they require must be required by the first loop
953 // pass in the manager (so that it is computed before the loop pass manager
954 // runs) and preserved by all loop pasess in the manager. To make this
955 // reasonably robust, the set needed for most loop passes is maintained here.
956 // If your loop pass requires an analysis not listed here, you will need to
957 // carefully audit the loop pass manager nesting structure that results.
958 AU.addRequired<AAResultsWrapperPass>();
959 AU.addPreserved<AAResultsWrapperPass>();
960 AU.addPreserved<BasicAAWrapperPass>();
961 AU.addPreserved<GlobalsAAWrapperPass>();
962 AU.addPreserved<SCEVAAWrapperPass>();
963 AU.addRequired<ScalarEvolutionWrapperPass>();
964 AU.addPreserved<ScalarEvolutionWrapperPass>();
Adam Nemet12937c32016-07-29 19:29:47 +0000965 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
966 AU.addPreserved<OptimizationRemarkEmitterWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000967}
968
969/// Manually defined generic "LoopPass" dependency initialization. This is used
970/// to initialize the exact set of passes from above in \c
971/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
972/// with:
973///
974/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
975///
976/// As-if "LoopPass" were a pass.
977void llvm::initializeLoopPassPass(PassRegistry &Registry) {
978 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
979 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
980 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000981 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000982 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
983 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
984 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
985 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
986 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet12937c32016-07-29 19:29:47 +0000987 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000988}
Adam Nemet963341c2016-04-21 17:33:17 +0000989
Adam Nemetfe3def72016-04-22 19:10:05 +0000990/// \brief Find string metadata for loop
991///
992/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
993/// operand or null otherwise. If the string metadata is not found return
994/// Optional's not-a-value.
995Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
996 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +0000997 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +0000998 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +0000999 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +00001000 return None;
Adam Nemet293be662016-04-21 17:33:20 +00001001
1002 // First operand should refer to the loop id itself.
1003 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1004 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1005
Adam Nemet963341c2016-04-21 17:33:17 +00001006 // Iterate over LoopID operands and look for MDString Metadata
1007 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1008 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1009 if (!MD)
1010 continue;
1011 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1012 if (!S)
1013 continue;
1014 // Return true if MDString holds expected MetaData.
1015 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001016 switch (MD->getNumOperands()) {
1017 case 1:
1018 return nullptr;
1019 case 2:
1020 return &MD->getOperand(1);
1021 default:
1022 llvm_unreachable("loop metadata has 0 or 1 operand");
1023 }
Adam Nemet963341c2016-04-21 17:33:17 +00001024 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001025 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001026}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001027
1028/// Returns true if the instruction in a loop is guaranteed to execute at least
1029/// once.
1030bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1031 const DominatorTree *DT, const Loop *CurLoop,
1032 const LoopSafetyInfo *SafetyInfo) {
1033 // We have to check to make sure that the instruction dominates all
1034 // of the exit blocks. If it doesn't, then there is a path out of the loop
1035 // which does not execute this instruction, so we can't hoist it.
1036
1037 // If the instruction is in the header block for the loop (which is very
1038 // common), it is always guaranteed to dominate the exit blocks. Since this
1039 // is a common case, and can save some work, check it now.
1040 if (Inst.getParent() == CurLoop->getHeader())
1041 // If there's a throw in the header block, we can't guarantee we'll reach
1042 // Inst.
1043 return !SafetyInfo->HeaderMayThrow;
1044
1045 // Somewhere in this loop there is an instruction which may throw and make us
1046 // exit the loop.
1047 if (SafetyInfo->MayThrow)
1048 return false;
1049
1050 // Get the exit blocks for the current loop.
1051 SmallVector<BasicBlock *, 8> ExitBlocks;
1052 CurLoop->getExitBlocks(ExitBlocks);
1053
1054 // Verify that the block dominates each of the exit blocks of the loop.
1055 for (BasicBlock *ExitBlock : ExitBlocks)
1056 if (!DT->dominates(Inst.getParent(), ExitBlock))
1057 return false;
1058
1059 // As a degenerate case, if the loop is statically infinite then we haven't
1060 // proven anything since there are no exit blocks.
1061 if (ExitBlocks.empty())
1062 return false;
1063
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001064 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1065 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1066 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001067 return true;
1068}