blob: 882f68ffac9876464f312f5d63ee28f30576910d [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
Chandler Carruth31088a92016-02-19 10:45:18 +000014#include "llvm/Analysis/AliasAnalysis.h"
15#include "llvm/Analysis/BasicAliasAnalysis.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000016#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000017#include "llvm/Analysis/GlobalsModRef.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000018#include "llvm/Analysis/ScalarEvolution.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000019#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000020#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000021#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
22#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000023#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000024#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000025#include "llvm/IR/PatternMatch.h"
26#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000027#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Transforms/Utils/LoopUtils.h"
30
31using namespace llvm;
32using namespace llvm::PatternMatch;
33
34#define DEBUG_TYPE "loop-utils"
35
Tyler Nowicki0a913102015-06-16 18:07:34 +000036bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
37 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000038 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
39 if (!Set.count(dyn_cast<Instruction>(*Use)))
40 return false;
41 return true;
42}
43
Chad Rosierc94f8e22015-08-27 14:12:17 +000044bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
45 switch (Kind) {
46 default:
47 break;
48 case RK_IntegerAdd:
49 case RK_IntegerMult:
50 case RK_IntegerOr:
51 case RK_IntegerAnd:
52 case RK_IntegerXor:
53 case RK_IntegerMinMax:
54 return true;
55 }
56 return false;
57}
58
59bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
60 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
61}
62
63bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
64 switch (Kind) {
65 default:
66 break;
67 case RK_IntegerAdd:
68 case RK_IntegerMult:
69 case RK_FloatAdd:
70 case RK_FloatMult:
71 return true;
72 }
73 return false;
74}
75
76Instruction *
77RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
78 SmallPtrSetImpl<Instruction *> &Visited,
79 SmallPtrSetImpl<Instruction *> &CI) {
80 if (!Phi->hasOneUse())
81 return Phi;
82
83 const APInt *M = nullptr;
84 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
85
86 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
87 // with a new integer type of the corresponding bit width.
88 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
89 m_And(m_APInt(M), m_Instruction(I))))) {
90 int32_t Bits = (*M + 1).exactLogBase2();
91 if (Bits > 0) {
92 RT = IntegerType::get(Phi->getContext(), Bits);
93 Visited.insert(Phi);
94 CI.insert(J);
95 return J;
96 }
97 }
98 return Phi;
99}
100
101bool RecurrenceDescriptor::getSourceExtensionKind(
102 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
103 SmallPtrSetImpl<Instruction *> &Visited,
104 SmallPtrSetImpl<Instruction *> &CI) {
105
106 SmallVector<Instruction *, 8> Worklist;
107 bool FoundOneOperand = false;
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000108 unsigned DstSize = RT->getPrimitiveSizeInBits();
Chad Rosierc94f8e22015-08-27 14:12:17 +0000109 Worklist.push_back(Exit);
110
111 // Traverse the instructions in the reduction expression, beginning with the
112 // exit value.
113 while (!Worklist.empty()) {
114 Instruction *I = Worklist.pop_back_val();
115 for (Use &U : I->operands()) {
116
117 // Terminate the traversal if the operand is not an instruction, or we
118 // reach the starting value.
119 Instruction *J = dyn_cast<Instruction>(U.get());
120 if (!J || J == Start)
121 continue;
122
123 // Otherwise, investigate the operation if it is also in the expression.
124 if (Visited.count(J)) {
125 Worklist.push_back(J);
126 continue;
127 }
128
129 // If the operand is not in Visited, it is not a reduction operation, but
130 // it does feed into one. Make sure it is either a single-use sign- or
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000131 // zero-extend instruction.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000132 CastInst *Cast = dyn_cast<CastInst>(J);
133 bool IsSExtInst = isa<SExtInst>(J);
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000134 if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
135 return false;
136
137 // Ensure the source type of the extend is no larger than the reduction
138 // type. It is not necessary for the types to be identical.
139 unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
140 if (SrcSize > DstSize)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000141 return false;
142
143 // Furthermore, ensure that all such extends are of the same kind.
144 if (FoundOneOperand) {
145 if (IsSigned != IsSExtInst)
146 return false;
147 } else {
148 FoundOneOperand = true;
149 IsSigned = IsSExtInst;
150 }
151
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000152 // Lastly, if the source type of the extend matches the reduction type,
153 // add the extend to CI so that we can avoid accounting for it in the
154 // cost model.
155 if (SrcSize == DstSize)
156 CI.insert(Cast);
Chad Rosierc94f8e22015-08-27 14:12:17 +0000157 }
158 }
159 return true;
160}
161
Tyler Nowicki0a913102015-06-16 18:07:34 +0000162bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
163 Loop *TheLoop, bool HasFunNoNaNAttr,
164 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000165 if (Phi->getNumIncomingValues() != 2)
166 return false;
167
168 // Reduction variables are only found in the loop header block.
169 if (Phi->getParent() != TheLoop->getHeader())
170 return false;
171
172 // Obtain the reduction start value from the value that comes from the loop
173 // preheader.
174 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
175
176 // ExitInstruction is the single value which is used outside the loop.
177 // We only allow for a single reduction value to be used outside the loop.
178 // This includes users of the reduction, variables (which form a cycle
179 // which ends in the phi node).
180 Instruction *ExitInstruction = nullptr;
181 // Indicates that we found a reduction operation in our scan.
182 bool FoundReduxOp = false;
183
184 // We start with the PHI node and scan for all of the users of this
185 // instruction. All users must be instructions that can be used as reduction
186 // variables (such as ADD). We must have a single out-of-block user. The cycle
187 // must include the original PHI.
188 bool FoundStartPHI = false;
189
190 // To recognize min/max patterns formed by a icmp select sequence, we store
191 // the number of instruction we saw from the recognized min/max pattern,
192 // to make sure we only see exactly the two instructions.
193 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000194 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000195
Chad Rosierc94f8e22015-08-27 14:12:17 +0000196 // Data used for determining if the recurrence has been type-promoted.
197 Type *RecurrenceType = Phi->getType();
198 SmallPtrSet<Instruction *, 4> CastInsts;
199 Instruction *Start = Phi;
200 bool IsSigned = false;
201
Karthik Bhat76aa6622015-04-20 04:38:33 +0000202 SmallPtrSet<Instruction *, 8> VisitedInsts;
203 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000204
205 // Return early if the recurrence kind does not match the type of Phi. If the
206 // recurrence kind is arithmetic, we attempt to look through AND operations
207 // resulting from the type promotion performed by InstCombine. Vector
208 // operations are not limited to the legal integer widths, so we may be able
209 // to evaluate the reduction in the narrower width.
210 if (RecurrenceType->isFloatingPointTy()) {
211 if (!isFloatingPointRecurrenceKind(Kind))
212 return false;
213 } else {
214 if (!isIntegerRecurrenceKind(Kind))
215 return false;
216 if (isArithmeticRecurrenceKind(Kind))
217 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
218 }
219
220 Worklist.push_back(Start);
221 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000222
223 // A value in the reduction can be used:
224 // - By the reduction:
225 // - Reduction operation:
226 // - One use of reduction value (safe).
227 // - Multiple use of reduction value (not safe).
228 // - PHI:
229 // - All uses of the PHI must be the reduction (safe).
230 // - Otherwise, not safe.
231 // - By one instruction outside of the loop (safe).
232 // - By further instructions outside of the loop (not safe).
233 // - By an instruction that is not part of the reduction (not safe).
234 // This is either:
235 // * An instruction type other than PHI or the reduction operation.
236 // * A PHI in the header other than the initial PHI.
237 while (!Worklist.empty()) {
238 Instruction *Cur = Worklist.back();
239 Worklist.pop_back();
240
241 // No Users.
242 // If the instruction has no users then this is a broken chain and can't be
243 // a reduction variable.
244 if (Cur->use_empty())
245 return false;
246
247 bool IsAPhi = isa<PHINode>(Cur);
248
249 // A header PHI use other than the original PHI.
250 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
251 return false;
252
253 // Reductions of instructions such as Div, and Sub is only possible if the
254 // LHS is the reduction variable.
255 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
256 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
257 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
258 return false;
259
Chad Rosierc94f8e22015-08-27 14:12:17 +0000260 // Any reduction instruction must be of one of the allowed kinds. We ignore
261 // the starting value (the Phi or an AND instruction if the Phi has been
262 // type-promoted).
263 if (Cur != Start) {
264 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
265 if (!ReduxDesc.isRecurrence())
266 return false;
267 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000268
269 // A reduction operation must only have one use of the reduction value.
270 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
271 hasMultipleUsesOf(Cur, VisitedInsts))
272 return false;
273
274 // All inputs to a PHI node must be a reduction value.
275 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
276 return false;
277
278 if (Kind == RK_IntegerMinMax &&
279 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
280 ++NumCmpSelectPatternInst;
281 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
282 ++NumCmpSelectPatternInst;
283
284 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000285 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000286
287 // Process users of current instruction. Push non-PHI nodes after PHI nodes
288 // onto the stack. This way we are going to have seen all inputs to PHI
289 // nodes once we get to them.
290 SmallVector<Instruction *, 8> NonPHIs;
291 SmallVector<Instruction *, 8> PHIs;
292 for (User *U : Cur->users()) {
293 Instruction *UI = cast<Instruction>(U);
294
295 // Check if we found the exit user.
296 BasicBlock *Parent = UI->getParent();
297 if (!TheLoop->contains(Parent)) {
298 // Exit if you find multiple outside users or if the header phi node is
299 // being used. In this case the user uses the value of the previous
300 // iteration, in which case we would loose "VF-1" iterations of the
301 // reduction operation if we vectorize.
302 if (ExitInstruction != nullptr || Cur == Phi)
303 return false;
304
305 // The instruction used by an outside user must be the last instruction
306 // before we feed back to the reduction phi. Otherwise, we loose VF-1
307 // operations on the value.
308 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
309 return false;
310
311 ExitInstruction = Cur;
312 continue;
313 }
314
315 // Process instructions only once (termination). Each reduction cycle
316 // value must only be used once, except by phi nodes and min/max
317 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000318 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000319 if (VisitedInsts.insert(UI).second) {
320 if (isa<PHINode>(UI))
321 PHIs.push_back(UI);
322 else
323 NonPHIs.push_back(UI);
324 } else if (!isa<PHINode>(UI) &&
325 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
326 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000327 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000328 return false;
329
330 // Remember that we completed the cycle.
331 if (UI == Phi)
332 FoundStartPHI = true;
333 }
334 Worklist.append(PHIs.begin(), PHIs.end());
335 Worklist.append(NonPHIs.begin(), NonPHIs.end());
336 }
337
338 // This means we have seen one but not the other instruction of the
339 // pattern or more than just a select and cmp.
340 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
341 NumCmpSelectPatternInst != 2)
342 return false;
343
344 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
345 return false;
346
Chad Rosierc94f8e22015-08-27 14:12:17 +0000347 // If we think Phi may have been type-promoted, we also need to ensure that
348 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
349 // so, we will be able to evaluate the reduction in the narrower bit width.
350 if (Start != Phi)
351 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
352 IsSigned, VisitedInsts, CastInsts))
353 return false;
354
Karthik Bhat76aa6622015-04-20 04:38:33 +0000355 // We found a reduction var if we have reached the original phi node and we
356 // only have a single instruction with out-of-loop users.
357
358 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000359 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000360
361 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000362 RecurrenceDescriptor RD(
363 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
364 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000365 RedDes = RD;
366
367 return true;
368}
369
370/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
371/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000372RecurrenceDescriptor::InstDesc
373RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000374
375 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
376 "Expect a select instruction");
377 Instruction *Cmp = nullptr;
378 SelectInst *Select = nullptr;
379
380 // We must handle the select(cmp()) as a single instruction. Advance to the
381 // select.
382 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
383 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000384 return InstDesc(false, I);
385 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000386 }
387
388 // Only handle single use cases for now.
389 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000390 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000391 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
392 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000393 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000394 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000395 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000396
397 Value *CmpLeft;
398 Value *CmpRight;
399
400 // Look for a min/max pattern.
401 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000402 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000403 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000404 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000405 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000406 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000407 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000408 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000409 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000410 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000411 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000412 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000413 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000414 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000415 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000416 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000417
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000418 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000419}
420
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000421RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000422RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000423 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000424 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000425 Instruction *UAI = Prev.getUnsafeAlgebraInst();
426 if (!UAI && FP && !I->hasUnsafeAlgebra())
427 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
428
Karthik Bhat76aa6622015-04-20 04:38:33 +0000429 switch (I->getOpcode()) {
430 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000431 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000432 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000433 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000434 case Instruction::Sub:
435 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000436 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000437 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000438 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000439 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000440 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000441 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000442 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000443 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000444 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000445 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000446 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000447 case Instruction::FSub:
448 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000449 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000450 case Instruction::FCmp:
451 case Instruction::ICmp:
452 case Instruction::Select:
453 if (Kind != RK_IntegerMinMax &&
454 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000455 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000456 return isMinMaxSelectCmpPattern(I, Prev);
457 }
458}
459
Tyler Nowicki0a913102015-06-16 18:07:34 +0000460bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000461 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
462 unsigned NumUses = 0;
463 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
464 ++Use) {
465 if (Insts.count(dyn_cast<Instruction>(*Use)))
466 ++NumUses;
467 if (NumUses > 1)
468 return true;
469 }
470
471 return false;
472}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000473bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
474 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000475
Karthik Bhat76aa6622015-04-20 04:38:33 +0000476 BasicBlock *Header = TheLoop->getHeader();
477 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000478 bool HasFunNoNaNAttr =
479 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000480
481 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
482 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
483 return true;
484 }
485 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
486 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
487 return true;
488 }
489 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
490 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
491 return true;
492 }
493 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
494 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
495 return true;
496 }
497 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
498 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
499 return true;
500 }
501 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
502 RedDes)) {
503 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
504 return true;
505 }
506 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
507 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
508 return true;
509 }
510 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
511 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
512 return true;
513 }
514 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
515 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
516 return true;
517 }
518 // Not a reduction of known type.
519 return false;
520}
521
Matthew Simpson29c997c2016-02-19 17:56:08 +0000522bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
523 DominatorTree *DT) {
524
525 // Ensure the phi node is in the loop header and has two incoming values.
526 if (Phi->getParent() != TheLoop->getHeader() ||
527 Phi->getNumIncomingValues() != 2)
528 return false;
529
530 // Ensure the loop has a preheader and a single latch block. The loop
531 // vectorizer will need the latch to set up the next iteration of the loop.
532 auto *Preheader = TheLoop->getLoopPreheader();
533 auto *Latch = TheLoop->getLoopLatch();
534 if (!Preheader || !Latch)
535 return false;
536
537 // Ensure the phi node's incoming blocks are the loop preheader and latch.
538 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
539 Phi->getBasicBlockIndex(Latch) < 0)
540 return false;
541
542 // Get the previous value. The previous value comes from the latch edge while
543 // the initial value comes form the preheader edge.
544 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Matthew Simpson53207a92016-04-11 19:48:18 +0000545 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
Matthew Simpson29c997c2016-02-19 17:56:08 +0000546 return false;
547
548 // Ensure every user of the phi node is dominated by the previous value. The
549 // dominance requirement ensures the loop vectorizer will not need to
550 // vectorize the initial value prior to the first iteration of the loop.
551 for (User *U : Phi->users())
552 if (auto *I = dyn_cast<Instruction>(U))
553 if (!DT->dominates(Previous, I))
554 return false;
555
556 return true;
557}
558
Karthik Bhat76aa6622015-04-20 04:38:33 +0000559/// This function returns the identity element (or neutral element) for
560/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000561Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
562 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000563 switch (K) {
564 case RK_IntegerXor:
565 case RK_IntegerAdd:
566 case RK_IntegerOr:
567 // Adding, Xoring, Oring zero to a number does not change it.
568 return ConstantInt::get(Tp, 0);
569 case RK_IntegerMult:
570 // Multiplying a number by 1 does not change it.
571 return ConstantInt::get(Tp, 1);
572 case RK_IntegerAnd:
573 // AND-ing a number with an all-1 value does not change it.
574 return ConstantInt::get(Tp, -1, true);
575 case RK_FloatMult:
576 // Multiplying a number by 1 does not change it.
577 return ConstantFP::get(Tp, 1.0L);
578 case RK_FloatAdd:
579 // Adding zero to a number does not change it.
580 return ConstantFP::get(Tp, 0.0L);
581 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000582 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000583 }
584}
585
Tyler Nowicki0a913102015-06-16 18:07:34 +0000586/// This function translates the recurrence kind to an LLVM binary operator.
587unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000588 switch (Kind) {
589 case RK_IntegerAdd:
590 return Instruction::Add;
591 case RK_IntegerMult:
592 return Instruction::Mul;
593 case RK_IntegerOr:
594 return Instruction::Or;
595 case RK_IntegerAnd:
596 return Instruction::And;
597 case RK_IntegerXor:
598 return Instruction::Xor;
599 case RK_FloatMult:
600 return Instruction::FMul;
601 case RK_FloatAdd:
602 return Instruction::FAdd;
603 case RK_IntegerMinMax:
604 return Instruction::ICmp;
605 case RK_FloatMinMax:
606 return Instruction::FCmp;
607 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000608 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000609 }
610}
611
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000612Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
613 MinMaxRecurrenceKind RK,
614 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000615 CmpInst::Predicate P = CmpInst::ICMP_NE;
616 switch (RK) {
617 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000618 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000619 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000620 P = CmpInst::ICMP_ULT;
621 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000622 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000623 P = CmpInst::ICMP_UGT;
624 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000625 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000626 P = CmpInst::ICMP_SLT;
627 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000628 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000629 P = CmpInst::ICMP_SGT;
630 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000631 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000632 P = CmpInst::FCMP_OLT;
633 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000634 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000635 P = CmpInst::FCMP_OGT;
636 break;
637 }
638
James Molloy50a4c272015-09-21 19:41:19 +0000639 // We only match FP sequences with unsafe algebra, so we can unconditionally
640 // set it on any generated instructions.
641 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
642 FastMathFlags FMF;
643 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000644 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000645
Karthik Bhat76aa6622015-04-20 04:38:33 +0000646 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000647 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000648 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
649 else
650 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
651
652 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
653 return Select;
654}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000655
James Molloy1bbf15c2015-08-27 09:53:00 +0000656InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000657 const SCEV *Step, BinaryOperator *BOp)
658 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000659 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000660
661 // Start value type should match the induction kind and the value
662 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000663 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000664 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
665 "StartValue is not a pointer for pointer induction");
666 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
667 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000668
669 // Check the Step Value. It should be non-zero integer value.
670 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
671 "Step value is zero");
672
673 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
674 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000675 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
676 "StepValue is not an integer");
677
678 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
679 "StepValue is not FP for FpInduction");
680 assert((IK != IK_FpInduction || (InductionBinOp &&
681 (InductionBinOp->getOpcode() == Instruction::FAdd ||
682 InductionBinOp->getOpcode() == Instruction::FSub))) &&
683 "Binary opcode should be specified for FP induction");
James Molloy1bbf15c2015-08-27 09:53:00 +0000684}
685
686int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000687 ConstantInt *ConstStep = getConstIntStepValue();
688 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
689 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000690 return 0;
691}
692
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000693ConstantInt *InductionDescriptor::getConstIntStepValue() const {
694 if (isa<SCEVConstant>(Step))
695 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
696 return nullptr;
697}
698
699Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
700 ScalarEvolution *SE,
701 const DataLayout& DL) const {
702
703 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000704 assert(Index->getType() == Step->getType() &&
705 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000706 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000707 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000708 assert(Index->getType() == StartValue->getType() &&
709 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000710
711 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
712 // and calculate (Start + Index * Step) for all cases, without
713 // special handling for "isOne" and "isMinusOne".
714 // But in the real life the result code getting worse. We mix SCEV
715 // expressions and ADD/SUB operations and receive redundant
716 // intermediate values being calculated in different ways and
717 // Instcombine is unable to reduce them all.
718
719 if (getConstIntStepValue() &&
720 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000721 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000722 if (getConstIntStepValue() &&
723 getConstIntStepValue()->isOne())
724 return B.CreateAdd(StartValue, Index);
725 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
726 SE->getMulExpr(Step, SE->getSCEV(Index)));
727 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
728 }
729 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000730 assert(isa<SCEVConstant>(Step) &&
731 "Expected constant step for pointer induction");
732 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
733 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000734 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000735 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000736 case IK_FpInduction: {
737 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
738 assert(InductionBinOp &&
739 (InductionBinOp->getOpcode() == Instruction::FAdd ||
740 InductionBinOp->getOpcode() == Instruction::FSub) &&
741 "Original bin op should be defined for FP induction");
742
743 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
744
745 // Floating point operations had to be 'fast' to enable the induction.
746 FastMathFlags Flags;
747 Flags.setUnsafeAlgebra();
748
749 Value *MulExp = B.CreateFMul(StepValue, Index);
750 if (isa<Instruction>(MulExp))
751 // We have to check, the MulExp may be a constant.
752 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
753
754 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
755 MulExp, "induction");
756 if (isa<Instruction>(BOp))
757 cast<Instruction>(BOp)->setFastMathFlags(Flags);
758
759 return BOp;
760 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000761 case IK_NoInduction:
762 return nullptr;
763 }
764 llvm_unreachable("invalid enum");
765}
766
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000767bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
768 ScalarEvolution *SE,
769 InductionDescriptor &D) {
770
771 // Here we only handle FP induction variables.
772 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
773
774 if (TheLoop->getHeader() != Phi->getParent())
775 return false;
776
777 // The loop may have multiple entrances or multiple exits; we can analyze
778 // this phi if it has a unique entry value and a unique backedge value.
779 if (Phi->getNumIncomingValues() != 2)
780 return false;
781 Value *BEValue = nullptr, *StartValue = nullptr;
782 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
783 BEValue = Phi->getIncomingValue(0);
784 StartValue = Phi->getIncomingValue(1);
785 } else {
786 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
787 "Unexpected Phi node in the loop");
788 BEValue = Phi->getIncomingValue(1);
789 StartValue = Phi->getIncomingValue(0);
790 }
791
792 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
793 if (!BOp)
794 return false;
795
796 Value *Addend = nullptr;
797 if (BOp->getOpcode() == Instruction::FAdd) {
798 if (BOp->getOperand(0) == Phi)
799 Addend = BOp->getOperand(1);
800 else if (BOp->getOperand(1) == Phi)
801 Addend = BOp->getOperand(0);
802 } else if (BOp->getOpcode() == Instruction::FSub)
803 if (BOp->getOperand(0) == Phi)
804 Addend = BOp->getOperand(1);
805
806 if (!Addend)
807 return false;
808
809 // The addend should be loop invariant
810 if (auto *I = dyn_cast<Instruction>(Addend))
811 if (TheLoop->contains(I))
812 return false;
813
814 // FP Step has unknown SCEV
815 const SCEV *Step = SE->getUnknown(Addend);
816 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
817 return true;
818}
819
820bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000821 PredicatedScalarEvolution &PSE,
822 InductionDescriptor &D,
823 bool Assume) {
824 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000825
826 // Handle integer and pointer inductions variables.
827 // Now we handle also FP induction but not trying to make a
828 // recurrent expression from the PHI node in-place.
829
830 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
831 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +0000832 return false;
833
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000834 if (PhiTy->isFloatingPointTy())
835 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
836
Silviu Barangac05bab82016-05-05 15:20:39 +0000837 const SCEV *PhiScev = PSE.getSCEV(Phi);
838 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
839
840 // We need this expression to be an AddRecExpr.
841 if (Assume && !AR)
842 AR = PSE.getAsAddRec(Phi);
843
844 if (!AR) {
845 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
846 return false;
847 }
848
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000849 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +0000850}
851
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000852bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000853 ScalarEvolution *SE,
854 InductionDescriptor &D,
855 const SCEV *Expr) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000856 Type *PhiTy = Phi->getType();
857 // We only handle integer and pointer inductions variables.
858 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
859 return false;
860
861 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +0000862 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000863 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +0000864
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000865 if (!AR) {
866 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
867 return false;
868 }
869
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000870 assert(TheLoop->getHeader() == Phi->getParent() &&
James Molloy1bbf15c2015-08-27 09:53:00 +0000871 "PHI is an AddRec for a different loop?!");
872 Value *StartValue =
873 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000874 const SCEV *Step = AR->getStepRecurrence(*SE);
875 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000876 // The stride may be a constant or a loop invariant integer value.
877 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000878 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000879 return false;
880
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000881 if (PhiTy->isIntegerTy()) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000882 D = InductionDescriptor(StartValue, IK_IntInduction, Step);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000883 return true;
884 }
885
886 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000887 // Pointer induction should be a constant.
888 if (!ConstStep)
889 return false;
890
891 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000892 Type *PointerElementType = PhiTy->getPointerElementType();
893 // The pointer stride cannot be determined if the pointer element type is not
894 // sized.
895 if (!PointerElementType->isSized())
896 return false;
897
898 const DataLayout &DL = Phi->getModule()->getDataLayout();
899 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000900 if (!Size)
901 return false;
902
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000903 int64_t CVSize = CV->getSExtValue();
904 if (CVSize % Size)
905 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000906 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
907 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +0000908 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000909 return true;
910}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000911
912/// \brief Returns the instructions that use values defined in the loop.
913SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
914 SmallVector<Instruction *, 8> UsedOutside;
915
916 for (auto *Block : L->getBlocks())
917 // FIXME: I believe that this could use copy_if if the Inst reference could
918 // be adapted into a pointer.
919 for (auto &Inst : *Block) {
920 auto Users = Inst.users();
921 if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
922 auto *Use = cast<Instruction>(U);
923 return !L->contains(Use->getParent());
924 }))
925 UsedOutside.push_back(&Inst);
926 }
927
928 return UsedOutside;
929}
Chandler Carruth31088a92016-02-19 10:45:18 +0000930
931void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
932 // By definition, all loop passes need the LoopInfo analysis and the
933 // Dominator tree it depends on. Because they all participate in the loop
934 // pass manager, they must also preserve these.
935 AU.addRequired<DominatorTreeWrapperPass>();
936 AU.addPreserved<DominatorTreeWrapperPass>();
937 AU.addRequired<LoopInfoWrapperPass>();
938 AU.addPreserved<LoopInfoWrapperPass>();
939
940 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
941 // here because users shouldn't directly get them from this header.
942 extern char &LoopSimplifyID;
943 extern char &LCSSAID;
944 AU.addRequiredID(LoopSimplifyID);
945 AU.addPreservedID(LoopSimplifyID);
946 AU.addRequiredID(LCSSAID);
947 AU.addPreservedID(LCSSAID);
948
949 // Loop passes are designed to run inside of a loop pass manager which means
950 // that any function analyses they require must be required by the first loop
951 // pass in the manager (so that it is computed before the loop pass manager
952 // runs) and preserved by all loop pasess in the manager. To make this
953 // reasonably robust, the set needed for most loop passes is maintained here.
954 // If your loop pass requires an analysis not listed here, you will need to
955 // carefully audit the loop pass manager nesting structure that results.
956 AU.addRequired<AAResultsWrapperPass>();
957 AU.addPreserved<AAResultsWrapperPass>();
958 AU.addPreserved<BasicAAWrapperPass>();
959 AU.addPreserved<GlobalsAAWrapperPass>();
960 AU.addPreserved<SCEVAAWrapperPass>();
961 AU.addRequired<ScalarEvolutionWrapperPass>();
962 AU.addPreserved<ScalarEvolutionWrapperPass>();
963}
964
965/// Manually defined generic "LoopPass" dependency initialization. This is used
966/// to initialize the exact set of passes from above in \c
967/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
968/// with:
969///
970/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
971///
972/// As-if "LoopPass" were a pass.
973void llvm::initializeLoopPassPass(PassRegistry &Registry) {
974 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
975 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
976 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000977 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000978 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
979 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
980 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
981 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
982 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
983}
Adam Nemet963341c2016-04-21 17:33:17 +0000984
Adam Nemetfe3def72016-04-22 19:10:05 +0000985/// \brief Find string metadata for loop
986///
987/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
988/// operand or null otherwise. If the string metadata is not found return
989/// Optional's not-a-value.
990Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
991 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +0000992 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +0000993 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +0000994 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +0000995 return None;
Adam Nemet293be662016-04-21 17:33:20 +0000996
997 // First operand should refer to the loop id itself.
998 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
999 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1000
Adam Nemet963341c2016-04-21 17:33:17 +00001001 // Iterate over LoopID operands and look for MDString Metadata
1002 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1003 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1004 if (!MD)
1005 continue;
1006 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1007 if (!S)
1008 continue;
1009 // Return true if MDString holds expected MetaData.
1010 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001011 switch (MD->getNumOperands()) {
1012 case 1:
1013 return nullptr;
1014 case 2:
1015 return &MD->getOperand(1);
1016 default:
1017 llvm_unreachable("loop metadata has 0 or 1 operand");
1018 }
Adam Nemet963341c2016-04-21 17:33:17 +00001019 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001020 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001021}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001022
1023/// Returns true if the instruction in a loop is guaranteed to execute at least
1024/// once.
1025bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1026 const DominatorTree *DT, const Loop *CurLoop,
1027 const LoopSafetyInfo *SafetyInfo) {
1028 // We have to check to make sure that the instruction dominates all
1029 // of the exit blocks. If it doesn't, then there is a path out of the loop
1030 // which does not execute this instruction, so we can't hoist it.
1031
1032 // If the instruction is in the header block for the loop (which is very
1033 // common), it is always guaranteed to dominate the exit blocks. Since this
1034 // is a common case, and can save some work, check it now.
1035 if (Inst.getParent() == CurLoop->getHeader())
1036 // If there's a throw in the header block, we can't guarantee we'll reach
1037 // Inst.
1038 return !SafetyInfo->HeaderMayThrow;
1039
1040 // Somewhere in this loop there is an instruction which may throw and make us
1041 // exit the loop.
1042 if (SafetyInfo->MayThrow)
1043 return false;
1044
1045 // Get the exit blocks for the current loop.
1046 SmallVector<BasicBlock *, 8> ExitBlocks;
1047 CurLoop->getExitBlocks(ExitBlocks);
1048
1049 // Verify that the block dominates each of the exit blocks of the loop.
1050 for (BasicBlock *ExitBlock : ExitBlocks)
1051 if (!DT->dominates(Inst.getParent(), ExitBlock))
1052 return false;
1053
1054 // As a degenerate case, if the loop is statically infinite then we haven't
1055 // proven anything since there are no exit blocks.
1056 if (ExitBlocks.empty())
1057 return false;
1058
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001059 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1060 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1061 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001062 return true;
1063}