blob: be151a3e50805057fe228c5d84ca3ca28b2b64ea [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/LoopInfo.h"
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000019#include "llvm/Analysis/LoopPass.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000020#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000021#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000022#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/Analysis/TargetTransformInfo.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"
Chandler Carruth4ab0f492017-06-23 04:03:04 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000033
34using namespace llvm;
35using namespace llvm::PatternMatch;
36
37#define DEBUG_TYPE "loop-utils"
38
Tyler Nowicki0a913102015-06-16 18:07:34 +000039bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
40 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000041 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
42 if (!Set.count(dyn_cast<Instruction>(*Use)))
43 return false;
44 return true;
45}
46
Chad Rosierc94f8e22015-08-27 14:12:17 +000047bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
48 switch (Kind) {
49 default:
50 break;
51 case RK_IntegerAdd:
52 case RK_IntegerMult:
53 case RK_IntegerOr:
54 case RK_IntegerAnd:
55 case RK_IntegerXor:
56 case RK_IntegerMinMax:
57 return true;
58 }
59 return false;
60}
61
62bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
63 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
64}
65
66bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
67 switch (Kind) {
68 default:
69 break;
70 case RK_IntegerAdd:
71 case RK_IntegerMult:
72 case RK_FloatAdd:
73 case RK_FloatMult:
74 return true;
75 }
76 return false;
77}
78
79Instruction *
80RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
81 SmallPtrSetImpl<Instruction *> &Visited,
82 SmallPtrSetImpl<Instruction *> &CI) {
83 if (!Phi->hasOneUse())
84 return Phi;
85
86 const APInt *M = nullptr;
87 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
88
89 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
90 // with a new integer type of the corresponding bit width.
91 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
92 m_And(m_APInt(M), m_Instruction(I))))) {
93 int32_t Bits = (*M + 1).exactLogBase2();
94 if (Bits > 0) {
95 RT = IntegerType::get(Phi->getContext(), Bits);
96 Visited.insert(Phi);
97 CI.insert(J);
98 return J;
99 }
100 }
101 return Phi;
102}
103
104bool RecurrenceDescriptor::getSourceExtensionKind(
105 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
106 SmallPtrSetImpl<Instruction *> &Visited,
107 SmallPtrSetImpl<Instruction *> &CI) {
108
109 SmallVector<Instruction *, 8> Worklist;
110 bool FoundOneOperand = false;
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000111 unsigned DstSize = RT->getPrimitiveSizeInBits();
Chad Rosierc94f8e22015-08-27 14:12:17 +0000112 Worklist.push_back(Exit);
113
114 // Traverse the instructions in the reduction expression, beginning with the
115 // exit value.
116 while (!Worklist.empty()) {
117 Instruction *I = Worklist.pop_back_val();
118 for (Use &U : I->operands()) {
119
120 // Terminate the traversal if the operand is not an instruction, or we
121 // reach the starting value.
122 Instruction *J = dyn_cast<Instruction>(U.get());
123 if (!J || J == Start)
124 continue;
125
126 // Otherwise, investigate the operation if it is also in the expression.
127 if (Visited.count(J)) {
128 Worklist.push_back(J);
129 continue;
130 }
131
132 // If the operand is not in Visited, it is not a reduction operation, but
133 // it does feed into one. Make sure it is either a single-use sign- or
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000134 // zero-extend instruction.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000135 CastInst *Cast = dyn_cast<CastInst>(J);
136 bool IsSExtInst = isa<SExtInst>(J);
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000137 if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
138 return false;
139
140 // Ensure the source type of the extend is no larger than the reduction
141 // type. It is not necessary for the types to be identical.
142 unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
143 if (SrcSize > DstSize)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000144 return false;
145
146 // Furthermore, ensure that all such extends are of the same kind.
147 if (FoundOneOperand) {
148 if (IsSigned != IsSExtInst)
149 return false;
150 } else {
151 FoundOneOperand = true;
152 IsSigned = IsSExtInst;
153 }
154
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000155 // Lastly, if the source type of the extend matches the reduction type,
156 // add the extend to CI so that we can avoid accounting for it in the
157 // cost model.
158 if (SrcSize == DstSize)
159 CI.insert(Cast);
Chad Rosierc94f8e22015-08-27 14:12:17 +0000160 }
161 }
162 return true;
163}
164
Tyler Nowicki0a913102015-06-16 18:07:34 +0000165bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
166 Loop *TheLoop, bool HasFunNoNaNAttr,
167 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000168 if (Phi->getNumIncomingValues() != 2)
169 return false;
170
171 // Reduction variables are only found in the loop header block.
172 if (Phi->getParent() != TheLoop->getHeader())
173 return false;
174
175 // Obtain the reduction start value from the value that comes from the loop
176 // preheader.
177 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
178
179 // ExitInstruction is the single value which is used outside the loop.
180 // We only allow for a single reduction value to be used outside the loop.
181 // This includes users of the reduction, variables (which form a cycle
182 // which ends in the phi node).
183 Instruction *ExitInstruction = nullptr;
184 // Indicates that we found a reduction operation in our scan.
185 bool FoundReduxOp = false;
186
187 // We start with the PHI node and scan for all of the users of this
188 // instruction. All users must be instructions that can be used as reduction
189 // variables (such as ADD). We must have a single out-of-block user. The cycle
190 // must include the original PHI.
191 bool FoundStartPHI = false;
192
193 // To recognize min/max patterns formed by a icmp select sequence, we store
194 // the number of instruction we saw from the recognized min/max pattern,
195 // to make sure we only see exactly the two instructions.
196 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000197 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000198
Chad Rosierc94f8e22015-08-27 14:12:17 +0000199 // Data used for determining if the recurrence has been type-promoted.
200 Type *RecurrenceType = Phi->getType();
201 SmallPtrSet<Instruction *, 4> CastInsts;
202 Instruction *Start = Phi;
203 bool IsSigned = false;
204
Karthik Bhat76aa6622015-04-20 04:38:33 +0000205 SmallPtrSet<Instruction *, 8> VisitedInsts;
206 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000207
208 // Return early if the recurrence kind does not match the type of Phi. If the
209 // recurrence kind is arithmetic, we attempt to look through AND operations
210 // resulting from the type promotion performed by InstCombine. Vector
211 // operations are not limited to the legal integer widths, so we may be able
212 // to evaluate the reduction in the narrower width.
213 if (RecurrenceType->isFloatingPointTy()) {
214 if (!isFloatingPointRecurrenceKind(Kind))
215 return false;
216 } else {
217 if (!isIntegerRecurrenceKind(Kind))
218 return false;
219 if (isArithmeticRecurrenceKind(Kind))
220 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
221 }
222
223 Worklist.push_back(Start);
224 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000225
226 // A value in the reduction can be used:
227 // - By the reduction:
228 // - Reduction operation:
229 // - One use of reduction value (safe).
230 // - Multiple use of reduction value (not safe).
231 // - PHI:
232 // - All uses of the PHI must be the reduction (safe).
233 // - Otherwise, not safe.
Michael Kuperstein7cefb402017-01-18 19:02:52 +0000234 // - By instructions outside of the loop (safe).
235 // * One value may have several outside users, but all outside
236 // uses must be of the same value.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000237 // - By an instruction that is not part of the reduction (not safe).
238 // This is either:
239 // * An instruction type other than PHI or the reduction operation.
240 // * A PHI in the header other than the initial PHI.
241 while (!Worklist.empty()) {
242 Instruction *Cur = Worklist.back();
243 Worklist.pop_back();
244
245 // No Users.
246 // If the instruction has no users then this is a broken chain and can't be
247 // a reduction variable.
248 if (Cur->use_empty())
249 return false;
250
251 bool IsAPhi = isa<PHINode>(Cur);
252
253 // A header PHI use other than the original PHI.
254 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
255 return false;
256
257 // Reductions of instructions such as Div, and Sub is only possible if the
258 // LHS is the reduction variable.
259 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
260 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
261 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
262 return false;
263
Chad Rosierc94f8e22015-08-27 14:12:17 +0000264 // Any reduction instruction must be of one of the allowed kinds. We ignore
265 // the starting value (the Phi or an AND instruction if the Phi has been
266 // type-promoted).
267 if (Cur != Start) {
268 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
269 if (!ReduxDesc.isRecurrence())
270 return false;
271 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000272
273 // A reduction operation must only have one use of the reduction value.
274 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
275 hasMultipleUsesOf(Cur, VisitedInsts))
276 return false;
277
278 // All inputs to a PHI node must be a reduction value.
279 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
280 return false;
281
282 if (Kind == RK_IntegerMinMax &&
283 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
284 ++NumCmpSelectPatternInst;
285 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
286 ++NumCmpSelectPatternInst;
287
288 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000289 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000290
291 // Process users of current instruction. Push non-PHI nodes after PHI nodes
292 // onto the stack. This way we are going to have seen all inputs to PHI
293 // nodes once we get to them.
294 SmallVector<Instruction *, 8> NonPHIs;
295 SmallVector<Instruction *, 8> PHIs;
296 for (User *U : Cur->users()) {
297 Instruction *UI = cast<Instruction>(U);
298
299 // Check if we found the exit user.
300 BasicBlock *Parent = UI->getParent();
301 if (!TheLoop->contains(Parent)) {
Michael Kuperstein7cefb402017-01-18 19:02:52 +0000302 // If we already know this instruction is used externally, move on to
303 // the next user.
304 if (ExitInstruction == Cur)
305 continue;
306
307 // Exit if you find multiple values used outside or if the header phi
308 // node is being used. In this case the user uses the value of the
309 // previous iteration, in which case we would loose "VF-1" iterations of
310 // the reduction operation if we vectorize.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000311 if (ExitInstruction != nullptr || Cur == Phi)
312 return false;
313
314 // The instruction used by an outside user must be the last instruction
315 // before we feed back to the reduction phi. Otherwise, we loose VF-1
316 // operations on the value.
David Majnemer42531262016-08-12 03:55:06 +0000317 if (!is_contained(Phi->operands(), Cur))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000318 return false;
319
320 ExitInstruction = Cur;
321 continue;
322 }
323
324 // Process instructions only once (termination). Each reduction cycle
325 // value must only be used once, except by phi nodes and min/max
326 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000327 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000328 if (VisitedInsts.insert(UI).second) {
329 if (isa<PHINode>(UI))
330 PHIs.push_back(UI);
331 else
332 NonPHIs.push_back(UI);
333 } else if (!isa<PHINode>(UI) &&
334 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
335 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000336 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000337 return false;
338
339 // Remember that we completed the cycle.
340 if (UI == Phi)
341 FoundStartPHI = true;
342 }
343 Worklist.append(PHIs.begin(), PHIs.end());
344 Worklist.append(NonPHIs.begin(), NonPHIs.end());
345 }
346
347 // This means we have seen one but not the other instruction of the
348 // pattern or more than just a select and cmp.
349 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
350 NumCmpSelectPatternInst != 2)
351 return false;
352
353 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
354 return false;
355
Chad Rosierc94f8e22015-08-27 14:12:17 +0000356 // If we think Phi may have been type-promoted, we also need to ensure that
357 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
358 // so, we will be able to evaluate the reduction in the narrower bit width.
359 if (Start != Phi)
360 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
361 IsSigned, VisitedInsts, CastInsts))
362 return false;
363
Karthik Bhat76aa6622015-04-20 04:38:33 +0000364 // We found a reduction var if we have reached the original phi node and we
365 // only have a single instruction with out-of-loop users.
366
367 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000368 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000369
370 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000371 RecurrenceDescriptor RD(
372 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
373 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000374 RedDes = RD;
375
376 return true;
377}
378
379/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
380/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000381RecurrenceDescriptor::InstDesc
382RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000383
384 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
385 "Expect a select instruction");
386 Instruction *Cmp = nullptr;
387 SelectInst *Select = nullptr;
388
389 // We must handle the select(cmp()) as a single instruction. Advance to the
390 // select.
391 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
392 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000393 return InstDesc(false, I);
394 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000395 }
396
397 // Only handle single use cases for now.
398 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000399 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000400 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
401 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000402 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000403 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000404 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000405
406 Value *CmpLeft;
407 Value *CmpRight;
408
409 // Look for a min/max pattern.
410 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000411 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000412 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000413 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000414 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000415 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000416 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000417 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000418 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000419 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000420 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000421 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000422 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000423 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000424 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000425 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000426
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000427 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000428}
429
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000430RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000431RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000432 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000433 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000434 Instruction *UAI = Prev.getUnsafeAlgebraInst();
435 if (!UAI && FP && !I->hasUnsafeAlgebra())
436 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
437
Karthik Bhat76aa6622015-04-20 04:38:33 +0000438 switch (I->getOpcode()) {
439 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000440 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000441 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000442 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000443 case Instruction::Sub:
444 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000445 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000446 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000447 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000448 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000449 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000450 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000451 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000452 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000453 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000454 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000455 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000456 case Instruction::FSub:
457 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000458 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000459 case Instruction::FCmp:
460 case Instruction::ICmp:
461 case Instruction::Select:
462 if (Kind != RK_IntegerMinMax &&
463 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000464 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000465 return isMinMaxSelectCmpPattern(I, Prev);
466 }
467}
468
Tyler Nowicki0a913102015-06-16 18:07:34 +0000469bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000470 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
471 unsigned NumUses = 0;
472 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
473 ++Use) {
474 if (Insts.count(dyn_cast<Instruction>(*Use)))
475 ++NumUses;
476 if (NumUses > 1)
477 return true;
478 }
479
480 return false;
481}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000482bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
483 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000484
Karthik Bhat76aa6622015-04-20 04:38:33 +0000485 BasicBlock *Header = TheLoop->getHeader();
486 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000487 bool HasFunNoNaNAttr =
488 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000489
490 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
491 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
492 return true;
493 }
494 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
495 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
496 return true;
497 }
498 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
499 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
500 return true;
501 }
502 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
503 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
504 return true;
505 }
506 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
507 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
508 return true;
509 }
510 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
511 RedDes)) {
512 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
513 return true;
514 }
515 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
516 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
517 return true;
518 }
519 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
520 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
521 return true;
522 }
523 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
524 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
525 return true;
526 }
527 // Not a reduction of known type.
528 return false;
529}
530
Matthew Simpson29c997c2016-02-19 17:56:08 +0000531bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
532 DominatorTree *DT) {
533
534 // Ensure the phi node is in the loop header and has two incoming values.
535 if (Phi->getParent() != TheLoop->getHeader() ||
536 Phi->getNumIncomingValues() != 2)
537 return false;
538
539 // Ensure the loop has a preheader and a single latch block. The loop
540 // vectorizer will need the latch to set up the next iteration of the loop.
541 auto *Preheader = TheLoop->getLoopPreheader();
542 auto *Latch = TheLoop->getLoopLatch();
543 if (!Preheader || !Latch)
544 return false;
545
546 // Ensure the phi node's incoming blocks are the loop preheader and latch.
547 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
548 Phi->getBasicBlockIndex(Latch) < 0)
549 return false;
550
551 // Get the previous value. The previous value comes from the latch edge while
552 // the initial value comes form the preheader edge.
553 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Matthew Simpson53207a92016-04-11 19:48:18 +0000554 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
Matthew Simpson29c997c2016-02-19 17:56:08 +0000555 return false;
556
Anna Thomasdcdb3252017-04-13 18:59:25 +0000557 // Ensure every user of the phi node is dominated by the previous value.
558 // The dominance requirement ensures the loop vectorizer will not need to
559 // vectorize the initial value prior to the first iteration of the loop.
Matthew Simpson29c997c2016-02-19 17:56:08 +0000560 for (User *U : Phi->users())
Anna Thomas00dc1b72017-04-11 21:02:00 +0000561 if (auto *I = dyn_cast<Instruction>(U)) {
Matthew Simpson29c997c2016-02-19 17:56:08 +0000562 if (!DT->dominates(Previous, I))
563 return false;
Anna Thomas00dc1b72017-04-11 21:02:00 +0000564 }
Matthew Simpson29c997c2016-02-19 17:56:08 +0000565
566 return true;
567}
568
Karthik Bhat76aa6622015-04-20 04:38:33 +0000569/// This function returns the identity element (or neutral element) for
570/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000571Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
572 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000573 switch (K) {
574 case RK_IntegerXor:
575 case RK_IntegerAdd:
576 case RK_IntegerOr:
577 // Adding, Xoring, Oring zero to a number does not change it.
578 return ConstantInt::get(Tp, 0);
579 case RK_IntegerMult:
580 // Multiplying a number by 1 does not change it.
581 return ConstantInt::get(Tp, 1);
582 case RK_IntegerAnd:
583 // AND-ing a number with an all-1 value does not change it.
584 return ConstantInt::get(Tp, -1, true);
585 case RK_FloatMult:
586 // Multiplying a number by 1 does not change it.
587 return ConstantFP::get(Tp, 1.0L);
588 case RK_FloatAdd:
589 // Adding zero to a number does not change it.
590 return ConstantFP::get(Tp, 0.0L);
591 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000592 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000593 }
594}
595
Tyler Nowicki0a913102015-06-16 18:07:34 +0000596/// This function translates the recurrence kind to an LLVM binary operator.
597unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000598 switch (Kind) {
599 case RK_IntegerAdd:
600 return Instruction::Add;
601 case RK_IntegerMult:
602 return Instruction::Mul;
603 case RK_IntegerOr:
604 return Instruction::Or;
605 case RK_IntegerAnd:
606 return Instruction::And;
607 case RK_IntegerXor:
608 return Instruction::Xor;
609 case RK_FloatMult:
610 return Instruction::FMul;
611 case RK_FloatAdd:
612 return Instruction::FAdd;
613 case RK_IntegerMinMax:
614 return Instruction::ICmp;
615 case RK_FloatMinMax:
616 return Instruction::FCmp;
617 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000618 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000619 }
620}
621
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000622Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
623 MinMaxRecurrenceKind RK,
624 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000625 CmpInst::Predicate P = CmpInst::ICMP_NE;
626 switch (RK) {
627 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000628 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000629 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000630 P = CmpInst::ICMP_ULT;
631 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000632 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000633 P = CmpInst::ICMP_UGT;
634 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000635 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000636 P = CmpInst::ICMP_SLT;
637 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000638 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000639 P = CmpInst::ICMP_SGT;
640 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000641 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000642 P = CmpInst::FCMP_OLT;
643 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000644 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000645 P = CmpInst::FCMP_OGT;
646 break;
647 }
648
James Molloy50a4c272015-09-21 19:41:19 +0000649 // We only match FP sequences with unsafe algebra, so we can unconditionally
650 // set it on any generated instructions.
651 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
652 FastMathFlags FMF;
653 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000654 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000655
Karthik Bhat76aa6622015-04-20 04:38:33 +0000656 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000657 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000658 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
659 else
660 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
661
662 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
663 return Select;
664}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000665
James Molloy1bbf15c2015-08-27 09:53:00 +0000666InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000667 const SCEV *Step, BinaryOperator *BOp)
668 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000669 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000670
671 // Start value type should match the induction kind and the value
672 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000673 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000674 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
675 "StartValue is not a pointer for pointer induction");
676 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
677 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000678
679 // Check the Step Value. It should be non-zero integer value.
680 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
681 "Step value is zero");
682
683 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
684 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000685 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
686 "StepValue is not an integer");
687
688 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
689 "StepValue is not FP for FpInduction");
690 assert((IK != IK_FpInduction || (InductionBinOp &&
691 (InductionBinOp->getOpcode() == Instruction::FAdd ||
692 InductionBinOp->getOpcode() == Instruction::FSub))) &&
693 "Binary opcode should be specified for FP induction");
James Molloy1bbf15c2015-08-27 09:53:00 +0000694}
695
696int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000697 ConstantInt *ConstStep = getConstIntStepValue();
698 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
699 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000700 return 0;
701}
702
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000703ConstantInt *InductionDescriptor::getConstIntStepValue() const {
704 if (isa<SCEVConstant>(Step))
705 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
706 return nullptr;
707}
708
709Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
710 ScalarEvolution *SE,
711 const DataLayout& DL) const {
712
713 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000714 assert(Index->getType() == Step->getType() &&
715 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000716 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000717 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000718 assert(Index->getType() == StartValue->getType() &&
719 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000720
721 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
722 // and calculate (Start + Index * Step) for all cases, without
723 // special handling for "isOne" and "isMinusOne".
724 // But in the real life the result code getting worse. We mix SCEV
725 // expressions and ADD/SUB operations and receive redundant
726 // intermediate values being calculated in different ways and
727 // Instcombine is unable to reduce them all.
728
729 if (getConstIntStepValue() &&
730 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000731 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000732 if (getConstIntStepValue() &&
733 getConstIntStepValue()->isOne())
734 return B.CreateAdd(StartValue, Index);
735 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
736 SE->getMulExpr(Step, SE->getSCEV(Index)));
737 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
738 }
739 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000740 assert(isa<SCEVConstant>(Step) &&
741 "Expected constant step for pointer induction");
742 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
743 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000744 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000745 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000746 case IK_FpInduction: {
747 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
748 assert(InductionBinOp &&
749 (InductionBinOp->getOpcode() == Instruction::FAdd ||
750 InductionBinOp->getOpcode() == Instruction::FSub) &&
751 "Original bin op should be defined for FP induction");
752
753 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
754
755 // Floating point operations had to be 'fast' to enable the induction.
756 FastMathFlags Flags;
757 Flags.setUnsafeAlgebra();
758
759 Value *MulExp = B.CreateFMul(StepValue, Index);
760 if (isa<Instruction>(MulExp))
761 // We have to check, the MulExp may be a constant.
762 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
763
764 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
765 MulExp, "induction");
766 if (isa<Instruction>(BOp))
767 cast<Instruction>(BOp)->setFastMathFlags(Flags);
768
769 return BOp;
770 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000771 case IK_NoInduction:
772 return nullptr;
773 }
774 llvm_unreachable("invalid enum");
775}
776
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000777bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
778 ScalarEvolution *SE,
779 InductionDescriptor &D) {
780
781 // Here we only handle FP induction variables.
782 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
783
784 if (TheLoop->getHeader() != Phi->getParent())
785 return false;
786
787 // The loop may have multiple entrances or multiple exits; we can analyze
788 // this phi if it has a unique entry value and a unique backedge value.
789 if (Phi->getNumIncomingValues() != 2)
790 return false;
791 Value *BEValue = nullptr, *StartValue = nullptr;
792 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
793 BEValue = Phi->getIncomingValue(0);
794 StartValue = Phi->getIncomingValue(1);
795 } else {
796 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
797 "Unexpected Phi node in the loop");
798 BEValue = Phi->getIncomingValue(1);
799 StartValue = Phi->getIncomingValue(0);
800 }
801
802 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
803 if (!BOp)
804 return false;
805
806 Value *Addend = nullptr;
807 if (BOp->getOpcode() == Instruction::FAdd) {
808 if (BOp->getOperand(0) == Phi)
809 Addend = BOp->getOperand(1);
810 else if (BOp->getOperand(1) == Phi)
811 Addend = BOp->getOperand(0);
812 } else if (BOp->getOpcode() == Instruction::FSub)
813 if (BOp->getOperand(0) == Phi)
814 Addend = BOp->getOperand(1);
815
816 if (!Addend)
817 return false;
818
819 // The addend should be loop invariant
820 if (auto *I = dyn_cast<Instruction>(Addend))
821 if (TheLoop->contains(I))
822 return false;
823
824 // FP Step has unknown SCEV
825 const SCEV *Step = SE->getUnknown(Addend);
826 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
827 return true;
828}
829
830bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000831 PredicatedScalarEvolution &PSE,
832 InductionDescriptor &D,
833 bool Assume) {
834 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000835
836 // Handle integer and pointer inductions variables.
837 // Now we handle also FP induction but not trying to make a
838 // recurrent expression from the PHI node in-place.
839
840 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
841 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +0000842 return false;
843
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000844 if (PhiTy->isFloatingPointTy())
845 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
846
Silviu Barangac05bab82016-05-05 15:20:39 +0000847 const SCEV *PhiScev = PSE.getSCEV(Phi);
848 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
849
850 // We need this expression to be an AddRecExpr.
851 if (Assume && !AR)
852 AR = PSE.getAsAddRec(Phi);
853
854 if (!AR) {
855 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
856 return false;
857 }
858
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000859 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +0000860}
861
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000862bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000863 ScalarEvolution *SE,
864 InductionDescriptor &D,
865 const SCEV *Expr) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000866 Type *PhiTy = Phi->getType();
867 // We only handle integer and pointer inductions variables.
868 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
869 return false;
870
871 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +0000872 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000873 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +0000874
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000875 if (!AR) {
876 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
877 return false;
878 }
879
Michael Kupersteinee31cbe2017-01-10 19:32:30 +0000880 if (AR->getLoop() != TheLoop) {
881 // FIXME: We should treat this as a uniform. Unfortunately, we
882 // don't currently know how to handled uniform PHIs.
883 DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
884 return false;
885 }
886
James Molloy1bbf15c2015-08-27 09:53:00 +0000887 Value *StartValue =
888 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000889 const SCEV *Step = AR->getStepRecurrence(*SE);
890 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000891 // The stride may be a constant or a loop invariant integer value.
892 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000893 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000894 return false;
895
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000896 if (PhiTy->isIntegerTy()) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000897 D = InductionDescriptor(StartValue, IK_IntInduction, Step);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000898 return true;
899 }
900
901 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000902 // Pointer induction should be a constant.
903 if (!ConstStep)
904 return false;
905
906 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000907 Type *PointerElementType = PhiTy->getPointerElementType();
908 // The pointer stride cannot be determined if the pointer element type is not
909 // sized.
910 if (!PointerElementType->isSized())
911 return false;
912
913 const DataLayout &DL = Phi->getModule()->getDataLayout();
914 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000915 if (!Size)
916 return false;
917
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000918 int64_t CVSize = CV->getSExtValue();
919 if (CVSize % Size)
920 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000921 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
922 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +0000923 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000924 return true;
925}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000926
Chandler Carruth4ab0f492017-06-23 04:03:04 +0000927bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
928 bool PreserveLCSSA) {
929 bool Changed = false;
930
931 // We re-use a vector for the in-loop predecesosrs.
932 SmallVector<BasicBlock *, 4> InLoopPredecessors;
933
934 auto RewriteExit = [&](BasicBlock *BB) {
935 // See if there are any non-loop predecessors of this exit block and
936 // keep track of the in-loop predecessors.
937 bool IsDedicatedExit = true;
938 for (auto *PredBB : predecessors(BB))
939 if (L->contains(PredBB)) {
940 if (isa<IndirectBrInst>(PredBB->getTerminator()))
941 // We cannot rewrite exiting edges from an indirectbr.
942 return false;
943
944 InLoopPredecessors.push_back(PredBB);
945 } else {
946 IsDedicatedExit = false;
947 }
948
949 // Nothing to do if this is already a dedicated exit.
950 if (IsDedicatedExit) {
951 InLoopPredecessors.clear();
952 return false;
953 }
954
955 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
956 auto *NewExitBB = SplitBlockPredecessors(
957 BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
958
959 if (!NewExitBB)
960 DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
961 << *L << "\n");
962 else
963 DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
964 << NewExitBB->getName() << "\n");
965 InLoopPredecessors.clear();
966 return true;
967 };
968
969 // Walk the exit blocks directly rather than building up a data structure for
970 // them, but only visit each one once.
971 SmallPtrSet<BasicBlock *, 4> Visited;
972 for (auto *BB : L->blocks())
973 for (auto *SuccBB : successors(BB)) {
974 // We're looking for exit blocks so skip in-loop successors.
975 if (L->contains(SuccBB))
976 continue;
977
978 // Visit each exit block exactly once.
979 if (!Visited.insert(SuccBB).second)
980 continue;
981
982 Changed |= RewriteExit(SuccBB);
983 }
984
985 return Changed;
986}
987
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000988/// \brief Returns the instructions that use values defined in the loop.
989SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
990 SmallVector<Instruction *, 8> UsedOutside;
991
992 for (auto *Block : L->getBlocks())
993 // FIXME: I believe that this could use copy_if if the Inst reference could
994 // be adapted into a pointer.
995 for (auto &Inst : *Block) {
996 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000997 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000998 auto *Use = cast<Instruction>(U);
999 return !L->contains(Use->getParent());
1000 }))
1001 UsedOutside.push_back(&Inst);
1002 }
1003
1004 return UsedOutside;
1005}
Chandler Carruth31088a92016-02-19 10:45:18 +00001006
1007void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
1008 // By definition, all loop passes need the LoopInfo analysis and the
1009 // Dominator tree it depends on. Because they all participate in the loop
1010 // pass manager, they must also preserve these.
1011 AU.addRequired<DominatorTreeWrapperPass>();
1012 AU.addPreserved<DominatorTreeWrapperPass>();
1013 AU.addRequired<LoopInfoWrapperPass>();
1014 AU.addPreserved<LoopInfoWrapperPass>();
1015
1016 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
1017 // here because users shouldn't directly get them from this header.
1018 extern char &LoopSimplifyID;
1019 extern char &LCSSAID;
1020 AU.addRequiredID(LoopSimplifyID);
1021 AU.addPreservedID(LoopSimplifyID);
1022 AU.addRequiredID(LCSSAID);
1023 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +00001024 // This is used in the LPPassManager to perform LCSSA verification on passes
1025 // which preserve lcssa form
1026 AU.addRequired<LCSSAVerificationPass>();
1027 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +00001028
1029 // Loop passes are designed to run inside of a loop pass manager which means
1030 // that any function analyses they require must be required by the first loop
1031 // pass in the manager (so that it is computed before the loop pass manager
1032 // runs) and preserved by all loop pasess in the manager. To make this
1033 // reasonably robust, the set needed for most loop passes is maintained here.
1034 // If your loop pass requires an analysis not listed here, you will need to
1035 // carefully audit the loop pass manager nesting structure that results.
1036 AU.addRequired<AAResultsWrapperPass>();
1037 AU.addPreserved<AAResultsWrapperPass>();
1038 AU.addPreserved<BasicAAWrapperPass>();
1039 AU.addPreserved<GlobalsAAWrapperPass>();
1040 AU.addPreserved<SCEVAAWrapperPass>();
1041 AU.addRequired<ScalarEvolutionWrapperPass>();
1042 AU.addPreserved<ScalarEvolutionWrapperPass>();
1043}
1044
1045/// Manually defined generic "LoopPass" dependency initialization. This is used
1046/// to initialize the exact set of passes from above in \c
1047/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
1048/// with:
1049///
1050/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
1051///
1052/// As-if "LoopPass" were a pass.
1053void llvm::initializeLoopPassPass(PassRegistry &Registry) {
1054 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1055 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1056 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001057 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +00001058 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1059 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
1060 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1061 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
1062 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1063}
Adam Nemet963341c2016-04-21 17:33:17 +00001064
Adam Nemetfe3def72016-04-22 19:10:05 +00001065/// \brief Find string metadata for loop
1066///
1067/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1068/// operand or null otherwise. If the string metadata is not found return
1069/// Optional's not-a-value.
1070Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1071 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +00001072 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +00001073 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +00001074 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +00001075 return None;
Adam Nemet293be662016-04-21 17:33:20 +00001076
1077 // First operand should refer to the loop id itself.
1078 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1079 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1080
Adam Nemet963341c2016-04-21 17:33:17 +00001081 // Iterate over LoopID operands and look for MDString Metadata
1082 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1083 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1084 if (!MD)
1085 continue;
1086 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1087 if (!S)
1088 continue;
1089 // Return true if MDString holds expected MetaData.
1090 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001091 switch (MD->getNumOperands()) {
1092 case 1:
1093 return nullptr;
1094 case 2:
1095 return &MD->getOperand(1);
1096 default:
1097 llvm_unreachable("loop metadata has 0 or 1 operand");
1098 }
Adam Nemet963341c2016-04-21 17:33:17 +00001099 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001100 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001101}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001102
1103/// Returns true if the instruction in a loop is guaranteed to execute at least
1104/// once.
1105bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1106 const DominatorTree *DT, const Loop *CurLoop,
1107 const LoopSafetyInfo *SafetyInfo) {
1108 // We have to check to make sure that the instruction dominates all
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001109 // of the exit blocks. If it doesn't, then there is a path out of the loop
1110 // which does not execute this instruction, so we can't hoist it.
1111
1112 // If the instruction is in the header block for the loop (which is very
1113 // common), it is always guaranteed to dominate the exit blocks. Since this
1114 // is a common case, and can save some work, check it now.
1115 if (Inst.getParent() == CurLoop->getHeader())
1116 // If there's a throw in the header block, we can't guarantee we'll reach
1117 // Inst.
1118 return !SafetyInfo->HeaderMayThrow;
1119
1120 // Somewhere in this loop there is an instruction which may throw and make us
1121 // exit the loop.
1122 if (SafetyInfo->MayThrow)
1123 return false;
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001124
1125 // Get the exit blocks for the current loop.
1126 SmallVector<BasicBlock *, 8> ExitBlocks;
1127 CurLoop->getExitBlocks(ExitBlocks);
1128
1129 // Verify that the block dominates each of the exit blocks of the loop.
1130 for (BasicBlock *ExitBlock : ExitBlocks)
1131 if (!DT->dominates(Inst.getParent(), ExitBlock))
1132 return false;
1133
1134 // As a degenerate case, if the loop is statically infinite then we haven't
1135 // proven anything since there are no exit blocks.
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001136 if (ExitBlocks.empty())
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001137 return false;
1138
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001139 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1140 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1141 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001142 return true;
1143}
Dehao Chen41d72a82016-11-17 01:17:02 +00001144
1145Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
1146 // Only support loops with a unique exiting block, and a latch.
1147 if (!L->getExitingBlock())
1148 return None;
1149
1150 // Get the branch weights for the the loop's backedge.
1151 BranchInst *LatchBR =
1152 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
1153 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
1154 return None;
1155
1156 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
1157 LatchBR->getSuccessor(1) == L->getHeader()) &&
1158 "At least one edge out of the latch must go to the header");
1159
1160 // To estimate the number of times the loop body was executed, we want to
1161 // know the number of times the backedge was taken, vs. the number of times
1162 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +00001163 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +00001164 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +00001165 return None;
1166
Michael Kupersteinb151a642016-11-30 21:13:57 +00001167 if (!TrueVal || !FalseVal)
1168 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +00001169
Michael Kupersteinb151a642016-11-30 21:13:57 +00001170 // Divide the count of the backedge by the count of the edge exiting the loop,
1171 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +00001172 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +00001173 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001174 else
Michael Kupersteinb151a642016-11-30 21:13:57 +00001175 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001176}
Amara Emersoncf9daa32017-05-09 10:43:25 +00001177
1178/// \brief Adds a 'fast' flag to floating point operations.
1179static Value *addFastMathFlag(Value *V) {
1180 if (isa<FPMathOperator>(V)) {
1181 FastMathFlags Flags;
1182 Flags.setUnsafeAlgebra();
1183 cast<Instruction>(V)->setFastMathFlags(Flags);
1184 }
1185 return V;
1186}
1187
1188// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +00001189Value *
1190llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1191 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1192 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +00001193 unsigned VF = Src->getType()->getVectorNumElements();
1194 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1195 // and vector ops, reducing the set of values being computed by half each
1196 // round.
1197 assert(isPowerOf2_32(VF) &&
1198 "Reduction emission only supported for pow2 vectors!");
1199 Value *TmpVec = Src;
1200 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1201 for (unsigned i = VF; i != 1; i >>= 1) {
1202 // Move the upper half of the vector to the lower half.
1203 for (unsigned j = 0; j != i / 2; ++j)
1204 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1205
1206 // Fill the rest of the mask with undef.
1207 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1208 UndefValue::get(Builder.getInt32Ty()));
1209
1210 Value *Shuf = Builder.CreateShuffleVector(
1211 TmpVec, UndefValue::get(TmpVec->getType()),
1212 ConstantVector::get(ShuffleMask), "rdx.shuf");
1213
1214 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1215 // Floating point operations had to be 'fast' to enable the reduction.
1216 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1217 TmpVec, Shuf, "bin.rdx"));
1218 } else {
1219 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1220 "Invalid min/max");
1221 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1222 Shuf);
1223 }
1224 if (!RedOps.empty())
1225 propagateIRFlags(TmpVec, RedOps);
1226 }
1227 // The result is in the first element of the vector.
1228 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1229}
1230
1231/// Create a simple vector reduction specified by an opcode and some
1232/// flags (if generating min/max reductions).
1233Value *llvm::createSimpleTargetReduction(
1234 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1235 Value *Src, TargetTransformInfo::ReductionFlags Flags,
1236 ArrayRef<Value *> RedOps) {
1237 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1238
1239 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1240 std::function<Value*()> BuildFunc;
1241 using RD = RecurrenceDescriptor;
1242 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1243 // TODO: Support creating ordered reductions.
1244 FastMathFlags FMFUnsafe;
1245 FMFUnsafe.setUnsafeAlgebra();
1246
1247 switch (Opcode) {
1248 case Instruction::Add:
1249 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1250 break;
1251 case Instruction::Mul:
1252 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1253 break;
1254 case Instruction::And:
1255 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1256 break;
1257 case Instruction::Or:
1258 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1259 break;
1260 case Instruction::Xor:
1261 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1262 break;
1263 case Instruction::FAdd:
1264 BuildFunc = [&]() {
1265 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
1266 cast<CallInst>(Rdx)->setFastMathFlags(FMFUnsafe);
1267 return Rdx;
1268 };
1269 break;
1270 case Instruction::FMul:
1271 BuildFunc = [&]() {
1272 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
1273 cast<CallInst>(Rdx)->setFastMathFlags(FMFUnsafe);
1274 return Rdx;
1275 };
1276 break;
1277 case Instruction::ICmp:
1278 if (Flags.IsMaxOp) {
1279 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1280 BuildFunc = [&]() {
1281 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1282 };
1283 } else {
1284 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1285 BuildFunc = [&]() {
1286 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1287 };
1288 }
1289 break;
1290 case Instruction::FCmp:
1291 if (Flags.IsMaxOp) {
1292 MinMaxKind = RD::MRK_FloatMax;
1293 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1294 } else {
1295 MinMaxKind = RD::MRK_FloatMin;
1296 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1297 }
1298 break;
1299 default:
1300 llvm_unreachable("Unhandled opcode");
1301 break;
1302 }
1303 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1304 return BuildFunc();
1305 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1306}
1307
1308/// Create a vector reduction using a given recurrence descriptor.
1309Value *llvm::createTargetReduction(IRBuilder<> &Builder,
1310 const TargetTransformInfo *TTI,
1311 RecurrenceDescriptor &Desc, Value *Src,
1312 bool NoNaN) {
1313 // TODO: Support in-order reductions based on the recurrence descriptor.
1314 RecurrenceDescriptor::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1315 TargetTransformInfo::ReductionFlags Flags;
1316 Flags.NoNaN = NoNaN;
1317 auto getSimpleRdx = [&](unsigned Opc) {
1318 return createSimpleTargetReduction(Builder, TTI, Opc, Src, Flags);
1319 };
1320 switch (RecKind) {
1321 case RecurrenceDescriptor::RK_FloatAdd:
1322 return getSimpleRdx(Instruction::FAdd);
1323 case RecurrenceDescriptor::RK_FloatMult:
1324 return getSimpleRdx(Instruction::FMul);
1325 case RecurrenceDescriptor::RK_IntegerAdd:
1326 return getSimpleRdx(Instruction::Add);
1327 case RecurrenceDescriptor::RK_IntegerMult:
1328 return getSimpleRdx(Instruction::Mul);
1329 case RecurrenceDescriptor::RK_IntegerAnd:
1330 return getSimpleRdx(Instruction::And);
1331 case RecurrenceDescriptor::RK_IntegerOr:
1332 return getSimpleRdx(Instruction::Or);
1333 case RecurrenceDescriptor::RK_IntegerXor:
1334 return getSimpleRdx(Instruction::Xor);
1335 case RecurrenceDescriptor::RK_IntegerMinMax: {
1336 switch (Desc.getMinMaxRecurrenceKind()) {
1337 case RecurrenceDescriptor::MRK_SIntMax:
1338 Flags.IsSigned = true;
1339 Flags.IsMaxOp = true;
1340 break;
1341 case RecurrenceDescriptor::MRK_UIntMax:
1342 Flags.IsMaxOp = true;
1343 break;
1344 case RecurrenceDescriptor::MRK_SIntMin:
1345 Flags.IsSigned = true;
1346 break;
1347 case RecurrenceDescriptor::MRK_UIntMin:
1348 break;
1349 default:
1350 llvm_unreachable("Unhandled MRK");
1351 }
1352 return getSimpleRdx(Instruction::ICmp);
1353 }
1354 case RecurrenceDescriptor::RK_FloatMinMax: {
1355 Flags.IsMaxOp =
1356 Desc.getMinMaxRecurrenceKind() == RecurrenceDescriptor::MRK_FloatMax;
1357 return getSimpleRdx(Instruction::FCmp);
1358 }
1359 default:
1360 llvm_unreachable("Unhandled RecKind");
1361 }
1362}
1363
1364void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
1365 if (auto *VecOp = dyn_cast<Instruction>(I)) {
1366 if (auto *I0 = dyn_cast<Instruction>(VL[0])) {
1367 // VecOVp is initialized to the 0th scalar, so start counting from index
1368 // '1'.
1369 VecOp->copyIRFlags(I0);
1370 for (int i = 1, e = VL.size(); i < e; ++i) {
1371 if (auto *Scalar = dyn_cast<Instruction>(VL[i]))
1372 VecOp->andIRFlags(Scalar);
1373 }
1374 }
1375 }
1376}