blob: 75665cfb7e904a8425fb3a821cef07f60f195064 [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 Carruth4a000882017-06-25 22:45:31 +000015#include "llvm/ADT/ScopeExit.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000016#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000018#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000019#include "llvm/Analysis/LoopInfo.h"
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000020#include "llvm/Analysis/LoopPass.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000022#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000023#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000024#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000027#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000028#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000029#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000030#include "llvm/IR/PatternMatch.h"
31#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000032#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000033#include "llvm/Support/Debug.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000034#include "llvm/Support/KnownBits.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000036
37using namespace llvm;
38using namespace llvm::PatternMatch;
39
40#define DEBUG_TYPE "loop-utils"
41
Tyler Nowicki0a913102015-06-16 18:07:34 +000042bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
43 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000044 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
45 if (!Set.count(dyn_cast<Instruction>(*Use)))
46 return false;
47 return true;
48}
49
Chad Rosierc94f8e22015-08-27 14:12:17 +000050bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
51 switch (Kind) {
52 default:
53 break;
54 case RK_IntegerAdd:
55 case RK_IntegerMult:
56 case RK_IntegerOr:
57 case RK_IntegerAnd:
58 case RK_IntegerXor:
59 case RK_IntegerMinMax:
60 return true;
61 }
62 return false;
63}
64
65bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
66 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
67}
68
69bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
70 switch (Kind) {
71 default:
72 break;
73 case RK_IntegerAdd:
74 case RK_IntegerMult:
75 case RK_FloatAdd:
76 case RK_FloatMult:
77 return true;
78 }
79 return false;
80}
81
Chad Rosiera097bc62018-02-04 15:42:24 +000082/// Determines if Phi may have been type-promoted. If Phi has a single user
83/// that ANDs the Phi with a type mask, return the user. RT is updated to
84/// account for the narrower bit width represented by the mask, and the AND
85/// instruction is added to CI.
86static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
87 SmallPtrSetImpl<Instruction *> &Visited,
88 SmallPtrSetImpl<Instruction *> &CI) {
Chad Rosierc94f8e22015-08-27 14:12:17 +000089 if (!Phi->hasOneUse())
90 return Phi;
91
92 const APInt *M = nullptr;
93 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
94
95 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
96 // with a new integer type of the corresponding bit width.
Craig Topper72ee6942017-06-24 06:24:01 +000097 if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
Chad Rosierc94f8e22015-08-27 14:12:17 +000098 int32_t Bits = (*M + 1).exactLogBase2();
99 if (Bits > 0) {
100 RT = IntegerType::get(Phi->getContext(), Bits);
101 Visited.insert(Phi);
102 CI.insert(J);
103 return J;
104 }
105 }
106 return Phi;
107}
108
Chad Rosiera097bc62018-02-04 15:42:24 +0000109/// Compute the minimal bit width needed to represent a reduction whose exit
110/// instruction is given by Exit.
111static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
112 DemandedBits *DB,
113 AssumptionCache *AC,
114 DominatorTree *DT) {
115 bool IsSigned = false;
116 const DataLayout &DL = Exit->getModule()->getDataLayout();
117 uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
Chad Rosierc94f8e22015-08-27 14:12:17 +0000118
Chad Rosiera097bc62018-02-04 15:42:24 +0000119 if (DB) {
120 // Use the demanded bits analysis to determine the bits that are live out
121 // of the exit instruction, rounding up to the nearest power of two. If the
122 // use of demanded bits results in a smaller bit width, we know the value
123 // must be positive (i.e., IsSigned = false), because if this were not the
124 // case, the sign bit would have been demanded.
125 auto Mask = DB->getDemandedBits(Exit);
126 MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
127 }
Chad Rosierc94f8e22015-08-27 14:12:17 +0000128
Chad Rosiera097bc62018-02-04 15:42:24 +0000129 if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
130 // If demanded bits wasn't able to limit the bit width, we can try to use
131 // value tracking instead. This can be the case, for example, if the value
132 // may be negative.
133 auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
134 auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
135 MaxBitWidth = NumTypeBits - NumSignBits;
136 KnownBits Bits = computeKnownBits(Exit, DL);
137 if (!Bits.isNonNegative()) {
138 // If the value is not known to be non-negative, we set IsSigned to true,
139 // meaning that we will use sext instructions instead of zext
140 // instructions to restore the original type.
141 IsSigned = true;
142 if (!Bits.isNegative())
143 // If the value is not known to be negative, we don't known what the
144 // upper bit is, and therefore, we don't know what kind of extend we
145 // will need. In this case, just increase the bit width by one bit and
146 // use sext.
147 ++MaxBitWidth;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000148 }
149 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000150 if (!isPowerOf2_64(MaxBitWidth))
151 MaxBitWidth = NextPowerOf2(MaxBitWidth);
152
153 return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
154 IsSigned);
155}
156
157/// Collect cast instructions that can be ignored in the vectorizer's cost
158/// model, given a reduction exit value and the minimal type in which the
159/// reduction can be represented.
160static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
161 Type *RecurrenceType,
162 SmallPtrSetImpl<Instruction *> &Casts) {
163
164 SmallVector<Instruction *, 8> Worklist;
165 SmallPtrSet<Instruction *, 8> Visited;
166 Worklist.push_back(Exit);
167
168 while (!Worklist.empty()) {
169 Instruction *Val = Worklist.pop_back_val();
170 Visited.insert(Val);
171 if (auto *Cast = dyn_cast<CastInst>(Val))
172 if (Cast->getSrcTy() == RecurrenceType) {
173 // If the source type of a cast instruction is equal to the recurrence
174 // type, it will be eliminated, and should be ignored in the vectorizer
175 // cost model.
176 Casts.insert(Cast);
177 continue;
178 }
179
180 // Add all operands to the work list if they are loop-varying values that
181 // we haven't yet visited.
182 for (Value *O : cast<User>(Val)->operands())
183 if (auto *I = dyn_cast<Instruction>(O))
184 if (TheLoop->contains(I) && !Visited.count(I))
185 Worklist.push_back(I);
186 }
Chad Rosierc94f8e22015-08-27 14:12:17 +0000187}
188
Tyler Nowicki0a913102015-06-16 18:07:34 +0000189bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
190 Loop *TheLoop, bool HasFunNoNaNAttr,
Chad Rosiera097bc62018-02-04 15:42:24 +0000191 RecurrenceDescriptor &RedDes,
192 DemandedBits *DB,
193 AssumptionCache *AC,
194 DominatorTree *DT) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000195 if (Phi->getNumIncomingValues() != 2)
196 return false;
197
198 // Reduction variables are only found in the loop header block.
199 if (Phi->getParent() != TheLoop->getHeader())
200 return false;
201
202 // Obtain the reduction start value from the value that comes from the loop
203 // preheader.
204 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
205
206 // ExitInstruction is the single value which is used outside the loop.
207 // We only allow for a single reduction value to be used outside the loop.
208 // This includes users of the reduction, variables (which form a cycle
209 // which ends in the phi node).
210 Instruction *ExitInstruction = nullptr;
211 // Indicates that we found a reduction operation in our scan.
212 bool FoundReduxOp = false;
213
214 // We start with the PHI node and scan for all of the users of this
215 // instruction. All users must be instructions that can be used as reduction
216 // variables (such as ADD). We must have a single out-of-block user. The cycle
217 // must include the original PHI.
218 bool FoundStartPHI = false;
219
220 // To recognize min/max patterns formed by a icmp select sequence, we store
221 // the number of instruction we saw from the recognized min/max pattern,
222 // to make sure we only see exactly the two instructions.
223 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000224 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000225
Chad Rosierc94f8e22015-08-27 14:12:17 +0000226 // Data used for determining if the recurrence has been type-promoted.
227 Type *RecurrenceType = Phi->getType();
228 SmallPtrSet<Instruction *, 4> CastInsts;
229 Instruction *Start = Phi;
230 bool IsSigned = false;
231
Karthik Bhat76aa6622015-04-20 04:38:33 +0000232 SmallPtrSet<Instruction *, 8> VisitedInsts;
233 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000234
235 // Return early if the recurrence kind does not match the type of Phi. If the
236 // recurrence kind is arithmetic, we attempt to look through AND operations
237 // resulting from the type promotion performed by InstCombine. Vector
238 // operations are not limited to the legal integer widths, so we may be able
239 // to evaluate the reduction in the narrower width.
240 if (RecurrenceType->isFloatingPointTy()) {
241 if (!isFloatingPointRecurrenceKind(Kind))
242 return false;
243 } else {
244 if (!isIntegerRecurrenceKind(Kind))
245 return false;
246 if (isArithmeticRecurrenceKind(Kind))
247 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
248 }
249
250 Worklist.push_back(Start);
251 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000252
253 // A value in the reduction can be used:
254 // - By the reduction:
255 // - Reduction operation:
256 // - One use of reduction value (safe).
257 // - Multiple use of reduction value (not safe).
258 // - PHI:
259 // - All uses of the PHI must be the reduction (safe).
260 // - Otherwise, not safe.
Michael Kuperstein7cefb402017-01-18 19:02:52 +0000261 // - By instructions outside of the loop (safe).
262 // * One value may have several outside users, but all outside
263 // uses must be of the same value.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000264 // - By an instruction that is not part of the reduction (not safe).
265 // This is either:
266 // * An instruction type other than PHI or the reduction operation.
267 // * A PHI in the header other than the initial PHI.
268 while (!Worklist.empty()) {
269 Instruction *Cur = Worklist.back();
270 Worklist.pop_back();
271
272 // No Users.
273 // If the instruction has no users then this is a broken chain and can't be
274 // a reduction variable.
275 if (Cur->use_empty())
276 return false;
277
278 bool IsAPhi = isa<PHINode>(Cur);
279
280 // A header PHI use other than the original PHI.
281 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
282 return false;
283
284 // Reductions of instructions such as Div, and Sub is only possible if the
285 // LHS is the reduction variable.
286 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
287 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
288 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
289 return false;
290
Chad Rosierc94f8e22015-08-27 14:12:17 +0000291 // Any reduction instruction must be of one of the allowed kinds. We ignore
292 // the starting value (the Phi or an AND instruction if the Phi has been
293 // type-promoted).
294 if (Cur != Start) {
295 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
296 if (!ReduxDesc.isRecurrence())
297 return false;
298 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000299
300 // A reduction operation must only have one use of the reduction value.
301 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
302 hasMultipleUsesOf(Cur, VisitedInsts))
303 return false;
304
305 // All inputs to a PHI node must be a reduction value.
306 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
307 return false;
308
309 if (Kind == RK_IntegerMinMax &&
310 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
311 ++NumCmpSelectPatternInst;
312 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
313 ++NumCmpSelectPatternInst;
314
315 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000316 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000317
318 // Process users of current instruction. Push non-PHI nodes after PHI nodes
319 // onto the stack. This way we are going to have seen all inputs to PHI
320 // nodes once we get to them.
321 SmallVector<Instruction *, 8> NonPHIs;
322 SmallVector<Instruction *, 8> PHIs;
323 for (User *U : Cur->users()) {
324 Instruction *UI = cast<Instruction>(U);
325
326 // Check if we found the exit user.
327 BasicBlock *Parent = UI->getParent();
328 if (!TheLoop->contains(Parent)) {
Michael Kuperstein7cefb402017-01-18 19:02:52 +0000329 // If we already know this instruction is used externally, move on to
330 // the next user.
331 if (ExitInstruction == Cur)
332 continue;
333
334 // Exit if you find multiple values used outside or if the header phi
335 // node is being used. In this case the user uses the value of the
336 // previous iteration, in which case we would loose "VF-1" iterations of
337 // the reduction operation if we vectorize.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000338 if (ExitInstruction != nullptr || Cur == Phi)
339 return false;
340
341 // The instruction used by an outside user must be the last instruction
342 // before we feed back to the reduction phi. Otherwise, we loose VF-1
343 // operations on the value.
David Majnemer42531262016-08-12 03:55:06 +0000344 if (!is_contained(Phi->operands(), Cur))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000345 return false;
346
347 ExitInstruction = Cur;
348 continue;
349 }
350
351 // Process instructions only once (termination). Each reduction cycle
352 // value must only be used once, except by phi nodes and min/max
353 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000354 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000355 if (VisitedInsts.insert(UI).second) {
356 if (isa<PHINode>(UI))
357 PHIs.push_back(UI);
358 else
359 NonPHIs.push_back(UI);
360 } else if (!isa<PHINode>(UI) &&
361 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
362 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000363 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000364 return false;
365
366 // Remember that we completed the cycle.
367 if (UI == Phi)
368 FoundStartPHI = true;
369 }
370 Worklist.append(PHIs.begin(), PHIs.end());
371 Worklist.append(NonPHIs.begin(), NonPHIs.end());
372 }
373
374 // This means we have seen one but not the other instruction of the
375 // pattern or more than just a select and cmp.
376 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
377 NumCmpSelectPatternInst != 2)
378 return false;
379
380 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
381 return false;
382
Chad Rosiera097bc62018-02-04 15:42:24 +0000383 if (Start != Phi) {
384 // If the starting value is not the same as the phi node, we speculatively
385 // looked through an 'and' instruction when evaluating a potential
386 // arithmetic reduction to determine if it may have been type-promoted.
387 //
388 // We now compute the minimal bit width that is required to represent the
389 // reduction. If this is the same width that was indicated by the 'and', we
390 // can represent the reduction in the smaller type. The 'and' instruction
391 // will be eliminated since it will essentially be a cast instruction that
392 // can be ignore in the cost model. If we compute a different type than we
393 // did when evaluating the 'and', the 'and' will not be eliminated, and we
394 // will end up with different kinds of operations in the recurrence
395 // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is
396 // the case.
397 //
398 // The vectorizer relies on InstCombine to perform the actual
399 // type-shrinking. It does this by inserting instructions to truncate the
400 // exit value of the reduction to the width indicated by RecurrenceType and
401 // then extend this value back to the original width. If IsSigned is false,
402 // a 'zext' instruction will be generated; otherwise, a 'sext' will be
403 // used.
404 //
405 // TODO: We should not rely on InstCombine to rewrite the reduction in the
406 // smaller type. We should just generate a correctly typed expression
407 // to begin with.
408 Type *ComputedType;
409 std::tie(ComputedType, IsSigned) =
410 computeRecurrenceType(ExitInstruction, DB, AC, DT);
411 if (ComputedType != RecurrenceType)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000412 return false;
413
Chad Rosiera097bc62018-02-04 15:42:24 +0000414 // The recurrence expression will be represented in a narrower type. If
415 // there are any cast instructions that will be unnecessary, collect them
416 // in CastInsts. Note that the 'and' instruction was already included in
417 // this list.
418 //
419 // TODO: A better way to represent this may be to tag in some way all the
420 // instructions that are a part of the reduction. The vectorizer cost
421 // model could then apply the recurrence type to these instructions,
422 // without needing a white list of instructions to ignore.
423 collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
424 }
425
Karthik Bhat76aa6622015-04-20 04:38:33 +0000426 // We found a reduction var if we have reached the original phi node and we
427 // only have a single instruction with out-of-loop users.
428
429 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000430 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000431
432 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000433 RecurrenceDescriptor RD(
434 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
435 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000436 RedDes = RD;
437
438 return true;
439}
440
441/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
442/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000443RecurrenceDescriptor::InstDesc
444RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000445
446 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
447 "Expect a select instruction");
448 Instruction *Cmp = nullptr;
449 SelectInst *Select = nullptr;
450
451 // We must handle the select(cmp()) as a single instruction. Advance to the
452 // select.
453 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
454 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000455 return InstDesc(false, I);
456 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000457 }
458
459 // Only handle single use cases for now.
460 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000461 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000462 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
463 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000464 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000465 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000466 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000467
468 Value *CmpLeft;
469 Value *CmpRight;
470
471 // Look for a min/max pattern.
472 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000473 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000474 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000475 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000476 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000477 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000478 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000479 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000480 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000481 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000482 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000483 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000484 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000485 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000486 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000487 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000488
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000489 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000490}
491
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000492RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000493RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000494 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000495 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000496 Instruction *UAI = Prev.getUnsafeAlgebraInst();
Sanjay Patel629c4112017-11-06 16:27:15 +0000497 if (!UAI && FP && !I->isFast())
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000498 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
499
Karthik Bhat76aa6622015-04-20 04:38:33 +0000500 switch (I->getOpcode()) {
501 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000502 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000503 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000504 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000505 case Instruction::Sub:
506 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000507 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000508 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000509 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000510 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000511 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000512 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000513 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000514 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000515 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000516 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000517 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000518 case Instruction::FSub:
519 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000520 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000521 case Instruction::FCmp:
522 case Instruction::ICmp:
523 case Instruction::Select:
524 if (Kind != RK_IntegerMinMax &&
525 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000526 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000527 return isMinMaxSelectCmpPattern(I, Prev);
528 }
529}
530
Tyler Nowicki0a913102015-06-16 18:07:34 +0000531bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000532 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
533 unsigned NumUses = 0;
534 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
535 ++Use) {
536 if (Insts.count(dyn_cast<Instruction>(*Use)))
537 ++NumUses;
538 if (NumUses > 1)
539 return true;
540 }
541
542 return false;
543}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000544bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
Chad Rosiera097bc62018-02-04 15:42:24 +0000545 RecurrenceDescriptor &RedDes,
546 DemandedBits *DB, AssumptionCache *AC,
547 DominatorTree *DT) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000548
Karthik Bhat76aa6622015-04-20 04:38:33 +0000549 BasicBlock *Header = TheLoop->getHeader();
550 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000551 bool HasFunNoNaNAttr =
552 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000553
Chad Rosiera097bc62018-02-04 15:42:24 +0000554 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
555 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000556 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
557 return true;
558 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000559 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
560 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000561 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
562 return true;
563 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000564 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
565 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000566 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
567 return true;
568 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000569 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
570 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000571 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
572 return true;
573 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000574 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
575 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000576 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
577 return true;
578 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000579 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
580 DB, AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000581 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
582 return true;
583 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000584 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
585 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000586 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
587 return true;
588 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000589 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
590 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000591 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
592 return true;
593 }
Chad Rosiera097bc62018-02-04 15:42:24 +0000594 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
595 AC, DT)) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000596 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
597 return true;
598 }
599 // Not a reduction of known type.
600 return false;
601}
602
Ayal Zaks2ff59d42017-06-30 21:05:06 +0000603bool RecurrenceDescriptor::isFirstOrderRecurrence(
604 PHINode *Phi, Loop *TheLoop,
605 DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
Matthew Simpson29c997c2016-02-19 17:56:08 +0000606
607 // Ensure the phi node is in the loop header and has two incoming values.
608 if (Phi->getParent() != TheLoop->getHeader() ||
609 Phi->getNumIncomingValues() != 2)
610 return false;
611
612 // Ensure the loop has a preheader and a single latch block. The loop
613 // vectorizer will need the latch to set up the next iteration of the loop.
614 auto *Preheader = TheLoop->getLoopPreheader();
615 auto *Latch = TheLoop->getLoopLatch();
616 if (!Preheader || !Latch)
617 return false;
618
619 // Ensure the phi node's incoming blocks are the loop preheader and latch.
620 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
621 Phi->getBasicBlockIndex(Latch) < 0)
622 return false;
623
624 // Get the previous value. The previous value comes from the latch edge while
625 // the initial value comes form the preheader edge.
626 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Ayal Zaks2ff59d42017-06-30 21:05:06 +0000627 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
628 SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
Matthew Simpson29c997c2016-02-19 17:56:08 +0000629 return false;
630
Anna Thomasdcdb3252017-04-13 18:59:25 +0000631 // Ensure every user of the phi node is dominated by the previous value.
632 // The dominance requirement ensures the loop vectorizer will not need to
633 // vectorize the initial value prior to the first iteration of the loop.
Ayal Zaks2ff59d42017-06-30 21:05:06 +0000634 // TODO: Consider extending this sinking to handle other kinds of instructions
635 // and expressions, beyond sinking a single cast past Previous.
636 if (Phi->hasOneUse()) {
637 auto *I = Phi->user_back();
638 if (I->isCast() && (I->getParent() == Phi->getParent()) && I->hasOneUse() &&
639 DT->dominates(Previous, I->user_back())) {
Ayal Zaks25e28002017-08-15 08:32:59 +0000640 if (!DT->dominates(Previous, I)) // Otherwise we're good w/o sinking.
641 SinkAfter[I] = Previous;
Ayal Zaks2ff59d42017-06-30 21:05:06 +0000642 return true;
643 }
644 }
645
Matthew Simpson29c997c2016-02-19 17:56:08 +0000646 for (User *U : Phi->users())
Anna Thomas00dc1b72017-04-11 21:02:00 +0000647 if (auto *I = dyn_cast<Instruction>(U)) {
Matthew Simpson29c997c2016-02-19 17:56:08 +0000648 if (!DT->dominates(Previous, I))
649 return false;
Anna Thomas00dc1b72017-04-11 21:02:00 +0000650 }
Matthew Simpson29c997c2016-02-19 17:56:08 +0000651
652 return true;
653}
654
Karthik Bhat76aa6622015-04-20 04:38:33 +0000655/// This function returns the identity element (or neutral element) for
656/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000657Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
658 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000659 switch (K) {
660 case RK_IntegerXor:
661 case RK_IntegerAdd:
662 case RK_IntegerOr:
663 // Adding, Xoring, Oring zero to a number does not change it.
664 return ConstantInt::get(Tp, 0);
665 case RK_IntegerMult:
666 // Multiplying a number by 1 does not change it.
667 return ConstantInt::get(Tp, 1);
668 case RK_IntegerAnd:
669 // AND-ing a number with an all-1 value does not change it.
670 return ConstantInt::get(Tp, -1, true);
671 case RK_FloatMult:
672 // Multiplying a number by 1 does not change it.
673 return ConstantFP::get(Tp, 1.0L);
674 case RK_FloatAdd:
675 // Adding zero to a number does not change it.
676 return ConstantFP::get(Tp, 0.0L);
677 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000678 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000679 }
680}
681
Tyler Nowicki0a913102015-06-16 18:07:34 +0000682/// This function translates the recurrence kind to an LLVM binary operator.
683unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000684 switch (Kind) {
685 case RK_IntegerAdd:
686 return Instruction::Add;
687 case RK_IntegerMult:
688 return Instruction::Mul;
689 case RK_IntegerOr:
690 return Instruction::Or;
691 case RK_IntegerAnd:
692 return Instruction::And;
693 case RK_IntegerXor:
694 return Instruction::Xor;
695 case RK_FloatMult:
696 return Instruction::FMul;
697 case RK_FloatAdd:
698 return Instruction::FAdd;
699 case RK_IntegerMinMax:
700 return Instruction::ICmp;
701 case RK_FloatMinMax:
702 return Instruction::FCmp;
703 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000704 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000705 }
706}
707
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000708Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
709 MinMaxRecurrenceKind RK,
710 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000711 CmpInst::Predicate P = CmpInst::ICMP_NE;
712 switch (RK) {
713 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000714 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000715 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000716 P = CmpInst::ICMP_ULT;
717 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000718 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000719 P = CmpInst::ICMP_UGT;
720 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000721 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000722 P = CmpInst::ICMP_SLT;
723 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000724 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000725 P = CmpInst::ICMP_SGT;
726 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000727 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000728 P = CmpInst::FCMP_OLT;
729 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000730 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000731 P = CmpInst::FCMP_OGT;
732 break;
733 }
734
Sanjay Patel629c4112017-11-06 16:27:15 +0000735 // We only match FP sequences that are 'fast', so we can unconditionally
James Molloy50a4c272015-09-21 19:41:19 +0000736 // set it on any generated instructions.
737 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
738 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +0000739 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +0000740 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000741
Karthik Bhat76aa6622015-04-20 04:38:33 +0000742 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000743 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000744 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
745 else
746 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
747
748 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
749 return Select;
750}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000751
James Molloy1bbf15c2015-08-27 09:53:00 +0000752InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Dorit Nuzman4750c782017-12-14 07:56:31 +0000753 const SCEV *Step, BinaryOperator *BOp,
754 SmallVectorImpl<Instruction *> *Casts)
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000755 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000756 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000757
758 // Start value type should match the induction kind and the value
759 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000760 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000761 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
762 "StartValue is not a pointer for pointer induction");
763 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
764 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000765
766 // Check the Step Value. It should be non-zero integer value.
767 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
768 "Step value is zero");
769
770 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
771 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000772 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
773 "StepValue is not an integer");
774
775 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
776 "StepValue is not FP for FpInduction");
777 assert((IK != IK_FpInduction || (InductionBinOp &&
778 (InductionBinOp->getOpcode() == Instruction::FAdd ||
779 InductionBinOp->getOpcode() == Instruction::FSub))) &&
780 "Binary opcode should be specified for FP induction");
Dorit Nuzman4750c782017-12-14 07:56:31 +0000781
782 if (Casts) {
783 for (auto &Inst : *Casts) {
784 RedundantCasts.push_back(Inst);
785 }
786 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000787}
788
789int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000790 ConstantInt *ConstStep = getConstIntStepValue();
791 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
792 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000793 return 0;
794}
795
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000796ConstantInt *InductionDescriptor::getConstIntStepValue() const {
797 if (isa<SCEVConstant>(Step))
798 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
799 return nullptr;
800}
801
802Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
803 ScalarEvolution *SE,
804 const DataLayout& DL) const {
805
806 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000807 assert(Index->getType() == Step->getType() &&
808 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000809 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000810 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000811 assert(Index->getType() == StartValue->getType() &&
812 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000813
814 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
815 // and calculate (Start + Index * Step) for all cases, without
816 // special handling for "isOne" and "isMinusOne".
817 // But in the real life the result code getting worse. We mix SCEV
818 // expressions and ADD/SUB operations and receive redundant
819 // intermediate values being calculated in different ways and
820 // Instcombine is unable to reduce them all.
821
822 if (getConstIntStepValue() &&
823 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000824 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000825 if (getConstIntStepValue() &&
826 getConstIntStepValue()->isOne())
827 return B.CreateAdd(StartValue, Index);
828 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
829 SE->getMulExpr(Step, SE->getSCEV(Index)));
830 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
831 }
832 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000833 assert(isa<SCEVConstant>(Step) &&
834 "Expected constant step for pointer induction");
835 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
836 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000837 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000838 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000839 case IK_FpInduction: {
840 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
841 assert(InductionBinOp &&
842 (InductionBinOp->getOpcode() == Instruction::FAdd ||
843 InductionBinOp->getOpcode() == Instruction::FSub) &&
844 "Original bin op should be defined for FP induction");
845
846 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
847
848 // Floating point operations had to be 'fast' to enable the induction.
849 FastMathFlags Flags;
Sanjay Patel629c4112017-11-06 16:27:15 +0000850 Flags.setFast();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000851
852 Value *MulExp = B.CreateFMul(StepValue, Index);
853 if (isa<Instruction>(MulExp))
854 // We have to check, the MulExp may be a constant.
855 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
856
857 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
858 MulExp, "induction");
859 if (isa<Instruction>(BOp))
860 cast<Instruction>(BOp)->setFastMathFlags(Flags);
861
862 return BOp;
863 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000864 case IK_NoInduction:
865 return nullptr;
866 }
867 llvm_unreachable("invalid enum");
868}
869
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000870bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
871 ScalarEvolution *SE,
872 InductionDescriptor &D) {
873
874 // Here we only handle FP induction variables.
875 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
876
877 if (TheLoop->getHeader() != Phi->getParent())
878 return false;
879
880 // The loop may have multiple entrances or multiple exits; we can analyze
881 // this phi if it has a unique entry value and a unique backedge value.
882 if (Phi->getNumIncomingValues() != 2)
883 return false;
884 Value *BEValue = nullptr, *StartValue = nullptr;
885 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
886 BEValue = Phi->getIncomingValue(0);
887 StartValue = Phi->getIncomingValue(1);
888 } else {
889 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
Dorit Nuzman4750c782017-12-14 07:56:31 +0000890 "Unexpected Phi node in the loop");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000891 BEValue = Phi->getIncomingValue(1);
892 StartValue = Phi->getIncomingValue(0);
893 }
894
895 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
896 if (!BOp)
897 return false;
898
899 Value *Addend = nullptr;
900 if (BOp->getOpcode() == Instruction::FAdd) {
901 if (BOp->getOperand(0) == Phi)
902 Addend = BOp->getOperand(1);
903 else if (BOp->getOperand(1) == Phi)
904 Addend = BOp->getOperand(0);
905 } else if (BOp->getOpcode() == Instruction::FSub)
906 if (BOp->getOperand(0) == Phi)
907 Addend = BOp->getOperand(1);
908
909 if (!Addend)
910 return false;
911
912 // The addend should be loop invariant
913 if (auto *I = dyn_cast<Instruction>(Addend))
914 if (TheLoop->contains(I))
915 return false;
916
917 // FP Step has unknown SCEV
918 const SCEV *Step = SE->getUnknown(Addend);
919 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
920 return true;
921}
922
Dorit Nuzman4750c782017-12-14 07:56:31 +0000923/// This function is called when we suspect that the update-chain of a phi node
924/// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
925/// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
926/// predicate P under which the SCEV expression for the phi can be the
927/// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
928/// cast instructions that are involved in the update-chain of this induction.
929/// A caller that adds the required runtime predicate can be free to drop these
930/// cast instructions, and compute the phi using \p AR (instead of some scev
931/// expression with casts).
932///
933/// For example, without a predicate the scev expression can take the following
934/// form:
935/// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
936///
937/// It corresponds to the following IR sequence:
938/// %for.body:
939/// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
940/// %casted_phi = "ExtTrunc i64 %x"
941/// %add = add i64 %casted_phi, %step
942///
943/// where %x is given in \p PN,
944/// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
945/// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
946/// several forms, for example, such as:
947/// ExtTrunc1: %casted_phi = and %x, 2^n-1
948/// or:
949/// ExtTrunc2: %t = shl %x, m
950/// %casted_phi = ashr %t, m
951///
952/// If we are able to find such sequence, we return the instructions
953/// we found, namely %casted_phi and the instructions on its use-def chain up
954/// to the phi (not including the phi).
Benjamin Kramer802e6252017-12-24 12:46:22 +0000955static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
956 const SCEVUnknown *PhiScev,
957 const SCEVAddRecExpr *AR,
958 SmallVectorImpl<Instruction *> &CastInsts) {
Dorit Nuzman4750c782017-12-14 07:56:31 +0000959
960 assert(CastInsts.empty() && "CastInsts is expected to be empty.");
961 auto *PN = cast<PHINode>(PhiScev->getValue());
962 assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
963 const Loop *L = AR->getLoop();
964
965 // Find any cast instructions that participate in the def-use chain of
966 // PhiScev in the loop.
967 // FORNOW/TODO: We currently expect the def-use chain to include only
968 // two-operand instructions, where one of the operands is an invariant.
969 // createAddRecFromPHIWithCasts() currently does not support anything more
970 // involved than that, so we keep the search simple. This can be
971 // extended/generalized as needed.
972
973 auto getDef = [&](const Value *Val) -> Value * {
974 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
975 if (!BinOp)
976 return nullptr;
977 Value *Op0 = BinOp->getOperand(0);
978 Value *Op1 = BinOp->getOperand(1);
979 Value *Def = nullptr;
980 if (L->isLoopInvariant(Op0))
981 Def = Op1;
982 else if (L->isLoopInvariant(Op1))
983 Def = Op0;
984 return Def;
985 };
986
987 // Look for the instruction that defines the induction via the
988 // loop backedge.
989 BasicBlock *Latch = L->getLoopLatch();
990 if (!Latch)
991 return false;
992 Value *Val = PN->getIncomingValueForBlock(Latch);
993 if (!Val)
994 return false;
995
996 // Follow the def-use chain until the induction phi is reached.
997 // If on the way we encounter a Value that has the same SCEV Expr as the
998 // phi node, we can consider the instructions we visit from that point
999 // as part of the cast-sequence that can be ignored.
1000 bool InCastSequence = false;
1001 auto *Inst = dyn_cast<Instruction>(Val);
1002 while (Val != PN) {
1003 // If we encountered a phi node other than PN, or if we left the loop,
1004 // we bail out.
1005 if (!Inst || !L->contains(Inst)) {
1006 return false;
1007 }
1008 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
1009 if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
1010 InCastSequence = true;
1011 if (InCastSequence) {
1012 // Only the last instruction in the cast sequence is expected to have
1013 // uses outside the induction def-use chain.
1014 if (!CastInsts.empty())
1015 if (!Inst->hasOneUse())
1016 return false;
1017 CastInsts.push_back(Inst);
1018 }
1019 Val = getDef(Val);
1020 if (!Val)
1021 return false;
1022 Inst = dyn_cast<Instruction>(Val);
1023 }
1024
1025 return InCastSequence;
1026}
1027
Elena Demikhovsky376a18b2016-07-24 07:24:54 +00001028bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +00001029 PredicatedScalarEvolution &PSE,
1030 InductionDescriptor &D,
1031 bool Assume) {
1032 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +00001033
1034 // Handle integer and pointer inductions variables.
1035 // Now we handle also FP induction but not trying to make a
1036 // recurrent expression from the PHI node in-place.
1037
1038 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
1039 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +00001040 return false;
1041
Elena Demikhovsky376a18b2016-07-24 07:24:54 +00001042 if (PhiTy->isFloatingPointTy())
1043 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1044
Silviu Barangac05bab82016-05-05 15:20:39 +00001045 const SCEV *PhiScev = PSE.getSCEV(Phi);
1046 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1047
1048 // We need this expression to be an AddRecExpr.
1049 if (Assume && !AR)
1050 AR = PSE.getAsAddRec(Phi);
1051
1052 if (!AR) {
1053 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1054 return false;
1055 }
1056
Dorit Nuzman4750c782017-12-14 07:56:31 +00001057 // Record any Cast instructions that participate in the induction update
1058 const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1059 // If we started from an UnknownSCEV, and managed to build an addRecurrence
1060 // only after enabling Assume with PSCEV, this means we may have encountered
1061 // cast instructions that required adding a runtime check in order to
1062 // guarantee the correctness of the AddRecurence respresentation of the
1063 // induction.
1064 if (PhiScev != AR && SymbolicPhi) {
1065 SmallVector<Instruction *, 2> Casts;
1066 if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1067 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1068 }
1069
Elena Demikhovsky376a18b2016-07-24 07:24:54 +00001070 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +00001071}
1072
Dorit Nuzman4750c782017-12-14 07:56:31 +00001073bool InductionDescriptor::isInductionPHI(
1074 PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1075 InductionDescriptor &D, const SCEV *Expr,
1076 SmallVectorImpl<Instruction *> *CastsToIgnore) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001077 Type *PhiTy = Phi->getType();
1078 // We only handle integer and pointer inductions variables.
1079 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1080 return false;
1081
1082 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +00001083 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001084 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +00001085
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001086 if (!AR) {
1087 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1088 return false;
1089 }
1090
Michael Kupersteinee31cbe2017-01-10 19:32:30 +00001091 if (AR->getLoop() != TheLoop) {
1092 // FIXME: We should treat this as a uniform. Unfortunately, we
1093 // don't currently know how to handled uniform PHIs.
1094 DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
Dorit Nuzman4750c782017-12-14 07:56:31 +00001095 return false;
Michael Kupersteinee31cbe2017-01-10 19:32:30 +00001096 }
1097
James Molloy1bbf15c2015-08-27 09:53:00 +00001098 Value *StartValue =
1099 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001100 const SCEV *Step = AR->getStepRecurrence(*SE);
1101 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +00001102 // The stride may be a constant or a loop invariant integer value.
1103 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +00001104 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001105 return false;
1106
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001107 if (PhiTy->isIntegerTy()) {
Dorit Nuzman4750c782017-12-14 07:56:31 +00001108 D = InductionDescriptor(StartValue, IK_IntInduction, Step, /*BOp=*/ nullptr,
1109 CastsToIgnore);
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001110 return true;
1111 }
1112
1113 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +00001114 // Pointer induction should be a constant.
1115 if (!ConstStep)
1116 return false;
1117
1118 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001119 Type *PointerElementType = PhiTy->getPointerElementType();
1120 // The pointer stride cannot be determined if the pointer element type is not
1121 // sized.
1122 if (!PointerElementType->isSized())
1123 return false;
1124
1125 const DataLayout &DL = Phi->getModule()->getDataLayout();
1126 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +00001127 if (!Size)
1128 return false;
1129
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001130 int64_t CVSize = CV->getSExtValue();
1131 if (CVSize % Size)
1132 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +00001133 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
1134 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +00001135 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +00001136 return true;
1137}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +00001138
Chandler Carruth4a000882017-06-25 22:45:31 +00001139bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
1140 bool PreserveLCSSA) {
1141 bool Changed = false;
1142
1143 // We re-use a vector for the in-loop predecesosrs.
1144 SmallVector<BasicBlock *, 4> InLoopPredecessors;
1145
1146 auto RewriteExit = [&](BasicBlock *BB) {
1147 assert(InLoopPredecessors.empty() &&
1148 "Must start with an empty predecessors list!");
1149 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
1150
1151 // See if there are any non-loop predecessors of this exit block and
1152 // keep track of the in-loop predecessors.
1153 bool IsDedicatedExit = true;
1154 for (auto *PredBB : predecessors(BB))
1155 if (L->contains(PredBB)) {
1156 if (isa<IndirectBrInst>(PredBB->getTerminator()))
1157 // We cannot rewrite exiting edges from an indirectbr.
1158 return false;
1159
1160 InLoopPredecessors.push_back(PredBB);
1161 } else {
1162 IsDedicatedExit = false;
1163 }
1164
1165 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
1166
1167 // Nothing to do if this is already a dedicated exit.
1168 if (IsDedicatedExit)
1169 return false;
1170
1171 auto *NewExitBB = SplitBlockPredecessors(
1172 BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
1173
1174 if (!NewExitBB)
1175 DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
1176 << *L << "\n");
1177 else
1178 DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
1179 << NewExitBB->getName() << "\n");
1180 return true;
1181 };
1182
1183 // Walk the exit blocks directly rather than building up a data structure for
1184 // them, but only visit each one once.
1185 SmallPtrSet<BasicBlock *, 4> Visited;
1186 for (auto *BB : L->blocks())
1187 for (auto *SuccBB : successors(BB)) {
1188 // We're looking for exit blocks so skip in-loop successors.
1189 if (L->contains(SuccBB))
1190 continue;
1191
1192 // Visit each exit block exactly once.
1193 if (!Visited.insert(SuccBB).second)
1194 continue;
1195
1196 Changed |= RewriteExit(SuccBB);
1197 }
1198
1199 return Changed;
1200}
1201
Ashutosh Nemac5b7b552015-08-19 05:40:42 +00001202/// \brief Returns the instructions that use values defined in the loop.
1203SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
1204 SmallVector<Instruction *, 8> UsedOutside;
1205
1206 for (auto *Block : L->getBlocks())
1207 // FIXME: I believe that this could use copy_if if the Inst reference could
1208 // be adapted into a pointer.
1209 for (auto &Inst : *Block) {
1210 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +00001211 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +00001212 auto *Use = cast<Instruction>(U);
1213 return !L->contains(Use->getParent());
1214 }))
1215 UsedOutside.push_back(&Inst);
1216 }
1217
1218 return UsedOutside;
1219}
Chandler Carruth31088a92016-02-19 10:45:18 +00001220
1221void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
1222 // By definition, all loop passes need the LoopInfo analysis and the
1223 // Dominator tree it depends on. Because they all participate in the loop
1224 // pass manager, they must also preserve these.
1225 AU.addRequired<DominatorTreeWrapperPass>();
1226 AU.addPreserved<DominatorTreeWrapperPass>();
1227 AU.addRequired<LoopInfoWrapperPass>();
1228 AU.addPreserved<LoopInfoWrapperPass>();
1229
1230 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
1231 // here because users shouldn't directly get them from this header.
1232 extern char &LoopSimplifyID;
1233 extern char &LCSSAID;
1234 AU.addRequiredID(LoopSimplifyID);
1235 AU.addPreservedID(LoopSimplifyID);
1236 AU.addRequiredID(LCSSAID);
1237 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +00001238 // This is used in the LPPassManager to perform LCSSA verification on passes
1239 // which preserve lcssa form
1240 AU.addRequired<LCSSAVerificationPass>();
1241 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +00001242
1243 // Loop passes are designed to run inside of a loop pass manager which means
1244 // that any function analyses they require must be required by the first loop
1245 // pass in the manager (so that it is computed before the loop pass manager
1246 // runs) and preserved by all loop pasess in the manager. To make this
1247 // reasonably robust, the set needed for most loop passes is maintained here.
1248 // If your loop pass requires an analysis not listed here, you will need to
1249 // carefully audit the loop pass manager nesting structure that results.
1250 AU.addRequired<AAResultsWrapperPass>();
1251 AU.addPreserved<AAResultsWrapperPass>();
1252 AU.addPreserved<BasicAAWrapperPass>();
1253 AU.addPreserved<GlobalsAAWrapperPass>();
1254 AU.addPreserved<SCEVAAWrapperPass>();
1255 AU.addRequired<ScalarEvolutionWrapperPass>();
1256 AU.addPreserved<ScalarEvolutionWrapperPass>();
1257}
1258
1259/// Manually defined generic "LoopPass" dependency initialization. This is used
1260/// to initialize the exact set of passes from above in \c
1261/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
1262/// with:
1263///
1264/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
1265///
1266/// As-if "LoopPass" were a pass.
1267void llvm::initializeLoopPassPass(PassRegistry &Registry) {
1268 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1269 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1270 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001271 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +00001272 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1273 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
1274 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1275 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
1276 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1277}
Adam Nemet963341c2016-04-21 17:33:17 +00001278
Adam Nemetfe3def72016-04-22 19:10:05 +00001279/// \brief Find string metadata for loop
1280///
1281/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1282/// operand or null otherwise. If the string metadata is not found return
1283/// Optional's not-a-value.
1284Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1285 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +00001286 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +00001287 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +00001288 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +00001289 return None;
Adam Nemet293be662016-04-21 17:33:20 +00001290
1291 // First operand should refer to the loop id itself.
1292 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1293 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1294
Adam Nemet963341c2016-04-21 17:33:17 +00001295 // Iterate over LoopID operands and look for MDString Metadata
1296 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1297 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1298 if (!MD)
1299 continue;
1300 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1301 if (!S)
1302 continue;
1303 // Return true if MDString holds expected MetaData.
1304 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001305 switch (MD->getNumOperands()) {
1306 case 1:
1307 return nullptr;
1308 case 2:
1309 return &MD->getOperand(1);
1310 default:
1311 llvm_unreachable("loop metadata has 0 or 1 operand");
1312 }
Adam Nemet963341c2016-04-21 17:33:17 +00001313 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001314 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001315}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001316
Alina Sbirlea7ed58562017-09-15 00:04:16 +00001317/// Does a BFS from a given node to all of its children inside a given loop.
1318/// The returned vector of nodes includes the starting point.
1319SmallVector<DomTreeNode *, 16>
1320llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
1321 SmallVector<DomTreeNode *, 16> Worklist;
1322 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
1323 // Only include subregions in the top level loop.
1324 BasicBlock *BB = DTN->getBlock();
1325 if (CurLoop->contains(BB))
1326 Worklist.push_back(DTN);
1327 };
1328
1329 AddRegionToWorklist(N);
1330
1331 for (size_t I = 0; I < Worklist.size(); I++)
1332 for (DomTreeNode *Child : Worklist[I]->getChildren())
1333 AddRegionToWorklist(Child);
1334
1335 return Worklist;
1336}
1337
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001338void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
1339 ScalarEvolution *SE = nullptr,
1340 LoopInfo *LI = nullptr) {
Hans Wennborg899809d2017-10-04 21:14:07 +00001341 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001342 auto *Preheader = L->getLoopPreheader();
1343 assert(Preheader && "Preheader should exist!");
1344
1345 // Now that we know the removal is safe, remove the loop by changing the
1346 // branch from the preheader to go to the single exit block.
1347 //
1348 // Because we're deleting a large chunk of code at once, the sequence in which
1349 // we remove things is very important to avoid invalidation issues.
1350
1351 // Tell ScalarEvolution that the loop is deleted. Do this before
1352 // deleting the loop so that ScalarEvolution can look at the loop
1353 // to determine what it needs to clean up.
1354 if (SE)
1355 SE->forgetLoop(L);
1356
1357 auto *ExitBlock = L->getUniqueExitBlock();
1358 assert(ExitBlock && "Should have a unique exit block!");
1359 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
1360
1361 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1362 assert(OldBr && "Preheader must end with a branch");
1363 assert(OldBr->isUnconditional() && "Preheader must have a single successor");
1364 // Connect the preheader to the exit block. Keep the old edge to the header
1365 // around to perform the dominator tree update in two separate steps
1366 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
1367 // preheader -> header.
1368 //
1369 //
1370 // 0. Preheader 1. Preheader 2. Preheader
1371 // | | | |
1372 // V | V |
1373 // Header <--\ | Header <--\ | Header <--\
1374 // | | | | | | | | | | |
1375 // | V | | | V | | | V |
1376 // | Body --/ | | Body --/ | | Body --/
1377 // V V V V V
1378 // Exit Exit Exit
1379 //
1380 // By doing this is two separate steps we can perform the dominator tree
1381 // update without using the batch update API.
1382 //
1383 // Even when the loop is never executed, we cannot remove the edge from the
1384 // source block to the exit block. Consider the case where the unexecuted loop
1385 // branches back to an outer loop. If we deleted the loop and removed the edge
1386 // coming to this inner loop, this will break the outer loop structure (by
1387 // deleting the backedge of the outer loop). If the outer loop is indeed a
1388 // non-loop, it will be deleted in a future iteration of loop deletion pass.
1389 IRBuilder<> Builder(OldBr);
1390 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
1391 // Remove the old branch. The conditional branch becomes a new terminator.
1392 OldBr->eraseFromParent();
1393
1394 // Rewrite phis in the exit block to get their inputs from the Preheader
1395 // instead of the exiting block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001396 for (PHINode &P : ExitBlock->phis()) {
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001397 // Set the zero'th element of Phi to be from the preheader and remove all
1398 // other incoming values. Given the loop has dedicated exits, all other
1399 // incoming values must be from the exiting blocks.
1400 int PredIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001401 P.setIncomingBlock(PredIndex, Preheader);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001402 // Removes all incoming values from all other exiting blocks (including
1403 // duplicate values from an exiting block).
1404 // Nuke all entries except the zero'th entry which is the preheader entry.
1405 // NOTE! We need to remove Incoming Values in the reverse order as done
1406 // below, to keep the indices valid for deletion (removeIncomingValues
1407 // updates getNumIncomingValues and shifts all values down into the operand
1408 // being deleted).
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001409 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
1410 P.removeIncomingValue(e - i, false);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001411
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001412 assert((P.getNumIncomingValues() == 1 &&
1413 P.getIncomingBlock(PredIndex) == Preheader) &&
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001414 "Should have exactly one value and that's from the preheader!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001415 }
1416
1417 // Disconnect the loop body by branching directly to its exit.
1418 Builder.SetInsertPoint(Preheader->getTerminator());
1419 Builder.CreateBr(ExitBlock);
1420 // Remove the old branch.
1421 Preheader->getTerminator()->eraseFromParent();
1422
1423 if (DT) {
1424 // Update the dominator tree by informing it about the new edge from the
1425 // preheader to the exit.
1426 DT->insertEdge(Preheader, ExitBlock);
1427 // Inform the dominator tree about the removed edge.
1428 DT->deleteEdge(Preheader, L->getHeader());
1429 }
1430
Serguei Katkova757d652018-01-12 07:24:43 +00001431 // Given LCSSA form is satisfied, we should not have users of instructions
1432 // within the dead loop outside of the loop. However, LCSSA doesn't take
1433 // unreachable uses into account. We handle them here.
1434 // We could do it after drop all references (in this case all users in the
1435 // loop will be already eliminated and we have less work to do but according
1436 // to API doc of User::dropAllReferences only valid operation after dropping
1437 // references, is deletion. So let's substitute all usages of
1438 // instruction from the loop with undef value of corresponding type first.
1439 for (auto *Block : L->blocks())
1440 for (Instruction &I : *Block) {
1441 auto *Undef = UndefValue::get(I.getType());
1442 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
1443 Use &U = *UI;
1444 ++UI;
1445 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
1446 if (L->contains(Usr->getParent()))
1447 continue;
1448 // If we have a DT then we can check that uses outside a loop only in
1449 // unreachable block.
1450 if (DT)
1451 assert(!DT->isReachableFromEntry(U) &&
1452 "Unexpected user in reachable block");
1453 U.set(Undef);
1454 }
1455 }
1456
Marcello Maggionidf3e71e2017-10-04 20:42:46 +00001457 // Remove the block from the reference counting scheme, so that we can
1458 // delete it freely later.
1459 for (auto *Block : L->blocks())
1460 Block->dropAllReferences();
1461
1462 if (LI) {
1463 // Erase the instructions and the blocks without having to worry
1464 // about ordering because we already dropped the references.
1465 // NOTE: This iteration is safe because erasing the block does not remove
1466 // its entry from the loop's block list. We do that in the next section.
1467 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
1468 LpI != LpE; ++LpI)
1469 (*LpI)->eraseFromParent();
1470
1471 // Finally, the blocks from loopinfo. This has to happen late because
1472 // otherwise our loop iterators won't work.
1473
1474 SmallPtrSet<BasicBlock *, 8> blocks;
1475 blocks.insert(L->block_begin(), L->block_end());
1476 for (BasicBlock *BB : blocks)
1477 LI->removeBlock(BB);
1478
1479 // The last step is to update LoopInfo now that we've eliminated this loop.
1480 LI->erase(L);
1481 }
1482}
1483
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001484/// Returns true if the instruction in a loop is guaranteed to execute at least
1485/// once.
1486bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1487 const DominatorTree *DT, const Loop *CurLoop,
1488 const LoopSafetyInfo *SafetyInfo) {
1489 // We have to check to make sure that the instruction dominates all
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001490 // of the exit blocks. If it doesn't, then there is a path out of the loop
1491 // which does not execute this instruction, so we can't hoist it.
1492
1493 // If the instruction is in the header block for the loop (which is very
1494 // common), it is always guaranteed to dominate the exit blocks. Since this
1495 // is a common case, and can save some work, check it now.
1496 if (Inst.getParent() == CurLoop->getHeader())
1497 // If there's a throw in the header block, we can't guarantee we'll reach
1498 // Inst.
1499 return !SafetyInfo->HeaderMayThrow;
1500
1501 // Somewhere in this loop there is an instruction which may throw and make us
1502 // exit the loop.
1503 if (SafetyInfo->MayThrow)
1504 return false;
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001505
1506 // Get the exit blocks for the current loop.
1507 SmallVector<BasicBlock *, 8> ExitBlocks;
1508 CurLoop->getExitBlocks(ExitBlocks);
1509
1510 // Verify that the block dominates each of the exit blocks of the loop.
1511 for (BasicBlock *ExitBlock : ExitBlocks)
1512 if (!DT->dominates(Inst.getParent(), ExitBlock))
1513 return false;
1514
1515 // As a degenerate case, if the loop is statically infinite then we haven't
1516 // proven anything since there are no exit blocks.
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001517 if (ExitBlocks.empty())
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001518 return false;
1519
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001520 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1521 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1522 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001523 return true;
1524}
Dehao Chen41d72a82016-11-17 01:17:02 +00001525
1526Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
1527 // Only support loops with a unique exiting block, and a latch.
1528 if (!L->getExitingBlock())
1529 return None;
1530
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +00001531 // Get the branch weights for the loop's backedge.
Dehao Chen41d72a82016-11-17 01:17:02 +00001532 BranchInst *LatchBR =
1533 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
1534 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
1535 return None;
1536
1537 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
1538 LatchBR->getSuccessor(1) == L->getHeader()) &&
1539 "At least one edge out of the latch must go to the header");
1540
1541 // To estimate the number of times the loop body was executed, we want to
1542 // know the number of times the backedge was taken, vs. the number of times
1543 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +00001544 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +00001545 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +00001546 return None;
1547
Michael Kupersteinb151a642016-11-30 21:13:57 +00001548 if (!TrueVal || !FalseVal)
1549 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +00001550
Michael Kupersteinb151a642016-11-30 21:13:57 +00001551 // Divide the count of the backedge by the count of the edge exiting the loop,
1552 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +00001553 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +00001554 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001555 else
Michael Kupersteinb151a642016-11-30 21:13:57 +00001556 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001557}
Amara Emersoncf9daa32017-05-09 10:43:25 +00001558
1559/// \brief Adds a 'fast' flag to floating point operations.
1560static Value *addFastMathFlag(Value *V) {
1561 if (isa<FPMathOperator>(V)) {
1562 FastMathFlags Flags;
Sanjay Patel629c4112017-11-06 16:27:15 +00001563 Flags.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +00001564 cast<Instruction>(V)->setFastMathFlags(Flags);
1565 }
1566 return V;
1567}
1568
1569// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +00001570Value *
1571llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1572 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1573 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +00001574 unsigned VF = Src->getType()->getVectorNumElements();
1575 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1576 // and vector ops, reducing the set of values being computed by half each
1577 // round.
1578 assert(isPowerOf2_32(VF) &&
1579 "Reduction emission only supported for pow2 vectors!");
1580 Value *TmpVec = Src;
1581 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1582 for (unsigned i = VF; i != 1; i >>= 1) {
1583 // Move the upper half of the vector to the lower half.
1584 for (unsigned j = 0; j != i / 2; ++j)
1585 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1586
1587 // Fill the rest of the mask with undef.
1588 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1589 UndefValue::get(Builder.getInt32Ty()));
1590
1591 Value *Shuf = Builder.CreateShuffleVector(
1592 TmpVec, UndefValue::get(TmpVec->getType()),
1593 ConstantVector::get(ShuffleMask), "rdx.shuf");
1594
1595 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1596 // Floating point operations had to be 'fast' to enable the reduction.
1597 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1598 TmpVec, Shuf, "bin.rdx"));
1599 } else {
1600 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1601 "Invalid min/max");
1602 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1603 Shuf);
1604 }
1605 if (!RedOps.empty())
1606 propagateIRFlags(TmpVec, RedOps);
1607 }
1608 // The result is in the first element of the vector.
1609 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1610}
1611
1612/// Create a simple vector reduction specified by an opcode and some
1613/// flags (if generating min/max reductions).
1614Value *llvm::createSimpleTargetReduction(
1615 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1616 Value *Src, TargetTransformInfo::ReductionFlags Flags,
1617 ArrayRef<Value *> RedOps) {
1618 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1619
1620 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1621 std::function<Value*()> BuildFunc;
1622 using RD = RecurrenceDescriptor;
1623 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1624 // TODO: Support creating ordered reductions.
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +00001625 FastMathFlags FMFFast;
1626 FMFFast.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +00001627
1628 switch (Opcode) {
1629 case Instruction::Add:
1630 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1631 break;
1632 case Instruction::Mul:
1633 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1634 break;
1635 case Instruction::And:
1636 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1637 break;
1638 case Instruction::Or:
1639 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1640 break;
1641 case Instruction::Xor:
1642 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1643 break;
1644 case Instruction::FAdd:
1645 BuildFunc = [&]() {
1646 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +00001647 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +00001648 return Rdx;
1649 };
1650 break;
1651 case Instruction::FMul:
1652 BuildFunc = [&]() {
1653 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +00001654 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +00001655 return Rdx;
1656 };
1657 break;
1658 case Instruction::ICmp:
1659 if (Flags.IsMaxOp) {
1660 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1661 BuildFunc = [&]() {
1662 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1663 };
1664 } else {
1665 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1666 BuildFunc = [&]() {
1667 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1668 };
1669 }
1670 break;
1671 case Instruction::FCmp:
1672 if (Flags.IsMaxOp) {
1673 MinMaxKind = RD::MRK_FloatMax;
1674 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1675 } else {
1676 MinMaxKind = RD::MRK_FloatMin;
1677 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1678 }
1679 break;
1680 default:
1681 llvm_unreachable("Unhandled opcode");
1682 break;
1683 }
1684 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1685 return BuildFunc();
1686 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1687}
1688
1689/// Create a vector reduction using a given recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +00001690Value *llvm::createTargetReduction(IRBuilder<> &B,
Amara Emersoncf9daa32017-05-09 10:43:25 +00001691 const TargetTransformInfo *TTI,
1692 RecurrenceDescriptor &Desc, Value *Src,
1693 bool NoNaN) {
1694 // TODO: Support in-order reductions based on the recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +00001695 using RD = RecurrenceDescriptor;
1696 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
Amara Emersoncf9daa32017-05-09 10:43:25 +00001697 TargetTransformInfo::ReductionFlags Flags;
1698 Flags.NoNaN = NoNaN;
Amara Emersoncf9daa32017-05-09 10:43:25 +00001699 switch (RecKind) {
Sanjay Patel3e069f52017-12-06 19:37:00 +00001700 case RD::RK_FloatAdd:
1701 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
1702 case RD::RK_FloatMult:
1703 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
1704 case RD::RK_IntegerAdd:
1705 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
1706 case RD::RK_IntegerMult:
1707 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
1708 case RD::RK_IntegerAnd:
1709 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
1710 case RD::RK_IntegerOr:
1711 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
1712 case RD::RK_IntegerXor:
1713 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
1714 case RD::RK_IntegerMinMax: {
1715 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
1716 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
1717 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
1718 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +00001719 }
Sanjay Patel3e069f52017-12-06 19:37:00 +00001720 case RD::RK_FloatMinMax: {
1721 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
1722 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +00001723 }
1724 default:
1725 llvm_unreachable("Unhandled RecKind");
1726 }
1727}
1728
Dinar Temirbulatova61f4b82017-07-19 10:02:07 +00001729void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1730 auto *VecOp = dyn_cast<Instruction>(I);
1731 if (!VecOp)
1732 return;
1733 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1734 : dyn_cast<Instruction>(OpValue);
1735 if (!Intersection)
1736 return;
1737 const unsigned Opcode = Intersection->getOpcode();
1738 VecOp->copyIRFlags(Intersection);
1739 for (auto *V : VL) {
1740 auto *Instr = dyn_cast<Instruction>(V);
1741 if (!Instr)
1742 continue;
1743 if (OpValue == nullptr || Opcode == Instr->getOpcode())
1744 VecOp->andIRFlags(V);
Amara Emersoncf9daa32017-05-09 10:43:25 +00001745 }
1746}