LLVM  10.0.0
IVDescriptors.cpp
Go to the documentation of this file.
1 //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file "describes" induction and recurrence variables.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/ScopeExit.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39 
40 #define DEBUG_TYPE "iv-descriptors"
41 
44  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 
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 
66  return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
67 }
68 
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 
82 /// 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.
89  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.
97  if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
98  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 
109 /// Compute the minimal bit width needed to represent a reduction whose exit
110 /// instruction is given by Exit.
111 static 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());
118 
119  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  }
128 
129  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;
148  }
149  }
150  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.
160 static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
161  Type *RecurrenceType,
163 
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  }
187 }
188 
190  Loop *TheLoop, bool HasFunNoNaNAttr,
191  RecurrenceDescriptor &RedDes,
192  DemandedBits *DB,
193  AssumptionCache *AC,
194  DominatorTree *DT) {
195  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;
224  InstDesc ReduxDesc(false, nullptr);
225 
226  // Data used for determining if the recurrence has been type-promoted.
227  Type *RecurrenceType = Phi->getType();
229  Instruction *Start = Phi;
230  bool IsSigned = false;
231 
232  SmallPtrSet<Instruction *, 8> VisitedInsts;
234 
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);
252 
253  // Start with all flags set because we will intersect this with the reduction
254  // flags from all the reduction operations.
256 
257  // A value in the reduction can be used:
258  // - By the reduction:
259  // - Reduction operation:
260  // - One use of reduction value (safe).
261  // - Multiple use of reduction value (not safe).
262  // - PHI:
263  // - All uses of the PHI must be the reduction (safe).
264  // - Otherwise, not safe.
265  // - By instructions outside of the loop (safe).
266  // * One value may have several outside users, but all outside
267  // uses must be of the same value.
268  // - By an instruction that is not part of the reduction (not safe).
269  // This is either:
270  // * An instruction type other than PHI or the reduction operation.
271  // * A PHI in the header other than the initial PHI.
272  while (!Worklist.empty()) {
273  Instruction *Cur = Worklist.back();
274  Worklist.pop_back();
275 
276  // No Users.
277  // If the instruction has no users then this is a broken chain and can't be
278  // a reduction variable.
279  if (Cur->use_empty())
280  return false;
281 
282  bool IsAPhi = isa<PHINode>(Cur);
283 
284  // A header PHI use other than the original PHI.
285  if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
286  return false;
287 
288  // Reductions of instructions such as Div, and Sub is only possible if the
289  // LHS is the reduction variable.
290  if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
291  !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
292  !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
293  return false;
294 
295  // Any reduction instruction must be of one of the allowed kinds. We ignore
296  // the starting value (the Phi or an AND instruction if the Phi has been
297  // type-promoted).
298  if (Cur != Start) {
299  ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
300  if (!ReduxDesc.isRecurrence())
301  return false;
302  // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
303  if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
304  FMF &= ReduxDesc.getPatternInst()->getFastMathFlags();
305  }
306 
307  bool IsASelect = isa<SelectInst>(Cur);
308 
309  // A conditional reduction operation must only have 2 or less uses in
310  // VisitedInsts.
311  if (IsASelect && (Kind == RK_FloatAdd || Kind == RK_FloatMult) &&
312  hasMultipleUsesOf(Cur, VisitedInsts, 2))
313  return false;
314 
315  // A reduction operation must only have one use of the reduction value.
316  if (!IsAPhi && !IsASelect && Kind != RK_IntegerMinMax &&
317  Kind != RK_FloatMinMax && hasMultipleUsesOf(Cur, VisitedInsts, 1))
318  return false;
319 
320  // All inputs to a PHI node must be a reduction value.
321  if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
322  return false;
323 
324  if (Kind == RK_IntegerMinMax &&
325  (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
326  ++NumCmpSelectPatternInst;
327  if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
328  ++NumCmpSelectPatternInst;
329 
330  // Check whether we found a reduction operator.
331  FoundReduxOp |= !IsAPhi && Cur != Start;
332 
333  // Process users of current instruction. Push non-PHI nodes after PHI nodes
334  // onto the stack. This way we are going to have seen all inputs to PHI
335  // nodes once we get to them.
338  for (User *U : Cur->users()) {
339  Instruction *UI = cast<Instruction>(U);
340 
341  // Check if we found the exit user.
342  BasicBlock *Parent = UI->getParent();
343  if (!TheLoop->contains(Parent)) {
344  // If we already know this instruction is used externally, move on to
345  // the next user.
346  if (ExitInstruction == Cur)
347  continue;
348 
349  // Exit if you find multiple values used outside or if the header phi
350  // node is being used. In this case the user uses the value of the
351  // previous iteration, in which case we would loose "VF-1" iterations of
352  // the reduction operation if we vectorize.
353  if (ExitInstruction != nullptr || Cur == Phi)
354  return false;
355 
356  // The instruction used by an outside user must be the last instruction
357  // before we feed back to the reduction phi. Otherwise, we loose VF-1
358  // operations on the value.
359  if (!is_contained(Phi->operands(), Cur))
360  return false;
361 
362  ExitInstruction = Cur;
363  continue;
364  }
365 
366  // Process instructions only once (termination). Each reduction cycle
367  // value must only be used once, except by phi nodes and min/max
368  // reductions which are represented as a cmp followed by a select.
369  InstDesc IgnoredVal(false, nullptr);
370  if (VisitedInsts.insert(UI).second) {
371  if (isa<PHINode>(UI))
372  PHIs.push_back(UI);
373  else
374  NonPHIs.push_back(UI);
375  } else if (!isa<PHINode>(UI) &&
376  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
377  !isa<SelectInst>(UI)) ||
378  (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
379  !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence())))
380  return false;
381 
382  // Remember that we completed the cycle.
383  if (UI == Phi)
384  FoundStartPHI = true;
385  }
386  Worklist.append(PHIs.begin(), PHIs.end());
387  Worklist.append(NonPHIs.begin(), NonPHIs.end());
388  }
389 
390  // This means we have seen one but not the other instruction of the
391  // pattern or more than just a select and cmp.
392  if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
393  NumCmpSelectPatternInst != 2)
394  return false;
395 
396  if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
397  return false;
398 
399  if (Start != Phi) {
400  // If the starting value is not the same as the phi node, we speculatively
401  // looked through an 'and' instruction when evaluating a potential
402  // arithmetic reduction to determine if it may have been type-promoted.
403  //
404  // We now compute the minimal bit width that is required to represent the
405  // reduction. If this is the same width that was indicated by the 'and', we
406  // can represent the reduction in the smaller type. The 'and' instruction
407  // will be eliminated since it will essentially be a cast instruction that
408  // can be ignore in the cost model. If we compute a different type than we
409  // did when evaluating the 'and', the 'and' will not be eliminated, and we
410  // will end up with different kinds of operations in the recurrence
411  // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is
412  // the case.
413  //
414  // The vectorizer relies on InstCombine to perform the actual
415  // type-shrinking. It does this by inserting instructions to truncate the
416  // exit value of the reduction to the width indicated by RecurrenceType and
417  // then extend this value back to the original width. If IsSigned is false,
418  // a 'zext' instruction will be generated; otherwise, a 'sext' will be
419  // used.
420  //
421  // TODO: We should not rely on InstCombine to rewrite the reduction in the
422  // smaller type. We should just generate a correctly typed expression
423  // to begin with.
424  Type *ComputedType;
425  std::tie(ComputedType, IsSigned) =
426  computeRecurrenceType(ExitInstruction, DB, AC, DT);
427  if (ComputedType != RecurrenceType)
428  return false;
429 
430  // The recurrence expression will be represented in a narrower type. If
431  // there are any cast instructions that will be unnecessary, collect them
432  // in CastInsts. Note that the 'and' instruction was already included in
433  // this list.
434  //
435  // TODO: A better way to represent this may be to tag in some way all the
436  // instructions that are a part of the reduction. The vectorizer cost
437  // model could then apply the recurrence type to these instructions,
438  // without needing a white list of instructions to ignore.
439  collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
440  }
441 
442  // We found a reduction var if we have reached the original phi node and we
443  // only have a single instruction with out-of-loop users.
444 
445  // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
446  // is saved as part of the RecurrenceDescriptor.
447 
448  // Save the description of this reduction variable.
450  RdxStart, ExitInstruction, Kind, FMF, ReduxDesc.getMinMaxKind(),
451  ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
452  RedDes = RD;
453 
454  return true;
455 }
456 
457 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
458 /// pattern corresponding to a min(X, Y) or max(X, Y).
461 
462  assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
463  "Expect a select instruction");
464  Instruction *Cmp = nullptr;
465  SelectInst *Select = nullptr;
466 
467  // We must handle the select(cmp()) as a single instruction. Advance to the
468  // select.
469  if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
470  if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
471  return InstDesc(false, I);
472  return InstDesc(Select, Prev.getMinMaxKind());
473  }
474 
475  // Only handle single use cases for now.
476  if (!(Select = dyn_cast<SelectInst>(I)))
477  return InstDesc(false, I);
478  if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
479  !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
480  return InstDesc(false, I);
481  if (!Cmp->hasOneUse())
482  return InstDesc(false, I);
483 
484  Value *CmpLeft;
485  Value *CmpRight;
486 
487  // Look for a min/max pattern.
488  if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
489  return InstDesc(Select, MRK_UIntMin);
490  else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
491  return InstDesc(Select, MRK_UIntMax);
492  else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
493  return InstDesc(Select, MRK_SIntMax);
494  else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
495  return InstDesc(Select, MRK_SIntMin);
496  else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
497  return InstDesc(Select, MRK_FloatMin);
498  else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
499  return InstDesc(Select, MRK_FloatMax);
500  else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
501  return InstDesc(Select, MRK_FloatMin);
502  else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
503  return InstDesc(Select, MRK_FloatMax);
504 
505  return InstDesc(false, I);
506 }
507 
508 /// Returns true if the select instruction has users in the compare-and-add
509 /// reduction pattern below. The select instruction argument is the last one
510 /// in the sequence.
511 ///
512 /// %sum.1 = phi ...
513 /// ...
514 /// %cmp = fcmp pred %0, %CFP
515 /// %add = fadd %0, %sum.1
516 /// %sum.2 = select %cmp, %add, %sum.1
521  if (!SI)
522  return InstDesc(false, I);
523 
524  CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
525  // Only handle single use cases for now.
526  if (!CI || !CI->hasOneUse())
527  return InstDesc(false, I);
528 
529  Value *TrueVal = SI->getTrueValue();
530  Value *FalseVal = SI->getFalseValue();
531  // Handle only when either of operands of select instruction is a PHI
532  // node for now.
533  if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
534  (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
535  return InstDesc(false, I);
536 
537  Instruction *I1 =
538  isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
539  : dyn_cast<Instruction>(TrueVal);
540  if (!I1 || !I1->isBinaryOp())
541  return InstDesc(false, I);
542 
543  Value *Op1, *Op2;
544  if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) ||
545  m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
546  I1->isFast())
547  return InstDesc(Kind == RK_FloatAdd, SI);
548 
549  if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
550  return InstDesc(Kind == RK_FloatMult, SI);
551 
552  return InstDesc(false, I);
553 }
554 
557  InstDesc &Prev, bool HasFunNoNaNAttr) {
558  Instruction *UAI = Prev.getUnsafeAlgebraInst();
559  if (!UAI && isa<FPMathOperator>(I) && !I->hasAllowReassoc())
560  UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
561 
562  switch (I->getOpcode()) {
563  default:
564  return InstDesc(false, I);
565  case Instruction::PHI:
566  return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
567  case Instruction::Sub:
568  case Instruction::Add:
569  return InstDesc(Kind == RK_IntegerAdd, I);
570  case Instruction::Mul:
571  return InstDesc(Kind == RK_IntegerMult, I);
572  case Instruction::And:
573  return InstDesc(Kind == RK_IntegerAnd, I);
574  case Instruction::Or:
575  return InstDesc(Kind == RK_IntegerOr, I);
576  case Instruction::Xor:
577  return InstDesc(Kind == RK_IntegerXor, I);
578  case Instruction::FMul:
579  return InstDesc(Kind == RK_FloatMult, I, UAI);
580  case Instruction::FSub:
581  case Instruction::FAdd:
582  return InstDesc(Kind == RK_FloatAdd, I, UAI);
583  case Instruction::Select:
584  if (Kind == RK_FloatAdd || Kind == RK_FloatMult)
585  return isConditionalRdxPattern(Kind, I);
587  case Instruction::FCmp:
588  case Instruction::ICmp:
589  if (Kind != RK_IntegerMinMax &&
590  (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
591  return InstDesc(false, I);
592  return isMinMaxSelectCmpPattern(I, Prev);
593  }
594 }
595 
598  unsigned MaxNumUses) {
599  unsigned NumUses = 0;
600  for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
601  ++Use) {
602  if (Insts.count(dyn_cast<Instruction>(*Use)))
603  ++NumUses;
604  if (NumUses > MaxNumUses)
605  return true;
606  }
607 
608  return false;
609 }
611  RecurrenceDescriptor &RedDes,
612  DemandedBits *DB, AssumptionCache *AC,
613  DominatorTree *DT) {
614 
615  BasicBlock *Header = TheLoop->getHeader();
616  Function &F = *Header->getParent();
617  bool HasFunNoNaNAttr =
618  F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
619 
620  if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
621  AC, DT)) {
622  LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
623  return true;
624  }
625  if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
626  AC, DT)) {
627  LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
628  return true;
629  }
630  if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
631  AC, DT)) {
632  LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
633  return true;
634  }
635  if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
636  AC, DT)) {
637  LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
638  return true;
639  }
640  if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
641  AC, DT)) {
642  LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
643  return true;
644  }
645  if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
646  DB, AC, DT)) {
647  LLVM_DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
648  return true;
649  }
650  if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
651  AC, DT)) {
652  LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
653  return true;
654  }
655  if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
656  AC, DT)) {
657  LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
658  return true;
659  }
660  if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
661  AC, DT)) {
662  LLVM_DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi
663  << "\n");
664  return true;
665  }
666  // Not a reduction of known type.
667  return false;
668 }
669 
671  PHINode *Phi, Loop *TheLoop,
673 
674  // Ensure the phi node is in the loop header and has two incoming values.
675  if (Phi->getParent() != TheLoop->getHeader() ||
676  Phi->getNumIncomingValues() != 2)
677  return false;
678 
679  // Ensure the loop has a preheader and a single latch block. The loop
680  // vectorizer will need the latch to set up the next iteration of the loop.
681  auto *Preheader = TheLoop->getLoopPreheader();
682  auto *Latch = TheLoop->getLoopLatch();
683  if (!Preheader || !Latch)
684  return false;
685 
686  // Ensure the phi node's incoming blocks are the loop preheader and latch.
687  if (Phi->getBasicBlockIndex(Preheader) < 0 ||
688  Phi->getBasicBlockIndex(Latch) < 0)
689  return false;
690 
691  // Get the previous value. The previous value comes from the latch edge while
692  // the initial value comes form the preheader edge.
693  auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
694  if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
695  SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
696  return false;
697 
698  // Ensure every user of the phi node is dominated by the previous value.
699  // The dominance requirement ensures the loop vectorizer will not need to
700  // vectorize the initial value prior to the first iteration of the loop.
701  // TODO: Consider extending this sinking to handle memory instructions and
702  // phis with multiple users.
703 
704  // Returns true, if all users of I are dominated by DominatedBy.
705  auto allUsesDominatedBy = [DT](Instruction *I, Instruction *DominatedBy) {
706  return all_of(I->uses(), [DT, DominatedBy](Use &U) {
707  return DT->dominates(DominatedBy, U);
708  });
709  };
710 
711  if (Phi->hasOneUse()) {
712  Instruction *I = Phi->user_back();
713 
714  // If the user of the PHI is also the incoming value, we potentially have a
715  // reduction and which cannot be handled by sinking.
716  if (Previous == I)
717  return false;
718 
719  // We cannot sink terminator instructions.
720  if (I->getParent()->getTerminator() == I)
721  return false;
722 
723  // Do not try to sink an instruction multiple times (if multiple operands
724  // are first order recurrences).
725  // TODO: We can support this case, by sinking the instruction after the
726  // 'deepest' previous instruction.
727  if (SinkAfter.find(I) != SinkAfter.end())
728  return false;
729 
730  if (DT->dominates(Previous, I)) // We already are good w/o sinking.
731  return true;
732 
733  // We can sink any instruction without side effects, as long as all users
734  // are dominated by the instruction we are sinking after.
735  if (I->getParent() == Phi->getParent() && !I->mayHaveSideEffects() &&
736  allUsesDominatedBy(I, Previous)) {
737  SinkAfter[I] = Previous;
738  return true;
739  }
740  }
741 
742  return allUsesDominatedBy(Phi, Previous);
743 }
744 
745 /// This function returns the identity element (or neutral element) for
746 /// the operation K.
748  Type *Tp) {
749  switch (K) {
750  case RK_IntegerXor:
751  case RK_IntegerAdd:
752  case RK_IntegerOr:
753  // Adding, Xoring, Oring zero to a number does not change it.
754  return ConstantInt::get(Tp, 0);
755  case RK_IntegerMult:
756  // Multiplying a number by 1 does not change it.
757  return ConstantInt::get(Tp, 1);
758  case RK_IntegerAnd:
759  // AND-ing a number with an all-1 value does not change it.
760  return ConstantInt::get(Tp, -1, true);
761  case RK_FloatMult:
762  // Multiplying a number by 1 does not change it.
763  return ConstantFP::get(Tp, 1.0L);
764  case RK_FloatAdd:
765  // Adding zero to a number does not change it.
766  return ConstantFP::get(Tp, 0.0L);
767  default:
768  llvm_unreachable("Unknown recurrence kind");
769  }
770 }
771 
772 /// This function translates the recurrence kind to an LLVM binary operator.
774  switch (Kind) {
775  case RK_IntegerAdd:
776  return Instruction::Add;
777  case RK_IntegerMult:
778  return Instruction::Mul;
779  case RK_IntegerOr:
780  return Instruction::Or;
781  case RK_IntegerAnd:
782  return Instruction::And;
783  case RK_IntegerXor:
784  return Instruction::Xor;
785  case RK_FloatMult:
786  return Instruction::FMul;
787  case RK_FloatAdd:
788  return Instruction::FAdd;
789  case RK_IntegerMinMax:
790  return Instruction::ICmp;
791  case RK_FloatMinMax:
792  return Instruction::FCmp;
793  default:
794  llvm_unreachable("Unknown recurrence operation");
795  }
796 }
797 
798 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
799  const SCEV *Step, BinaryOperator *BOp,
801  : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
802  assert(IK != IK_NoInduction && "Not an induction");
803 
804  // Start value type should match the induction kind and the value
805  // itself should not be null.
806  assert(StartValue && "StartValue is null");
807  assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
808  "StartValue is not a pointer for pointer induction");
809  assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
810  "StartValue is not an integer for integer induction");
811 
812  // Check the Step Value. It should be non-zero integer value.
813  assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
814  "Step value is zero");
815 
816  assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
817  "Step value should be constant for pointer induction");
818  assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
819  "StepValue is not an integer");
820 
821  assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
822  "StepValue is not FP for FpInduction");
823  assert((IK != IK_FpInduction ||
824  (InductionBinOp &&
825  (InductionBinOp->getOpcode() == Instruction::FAdd ||
826  InductionBinOp->getOpcode() == Instruction::FSub))) &&
827  "Binary opcode should be specified for FP induction");
828 
829  if (Casts) {
830  for (auto &Inst : *Casts) {
831  RedundantCasts.push_back(Inst);
832  }
833  }
834 }
835 
837  ConstantInt *ConstStep = getConstIntStepValue();
838  if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
839  return ConstStep->getSExtValue();
840  return 0;
841 }
842 
844  if (isa<SCEVConstant>(Step))
845  return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
846  return nullptr;
847 }
848 
850  ScalarEvolution *SE,
852 
853  // Here we only handle FP induction variables.
854  assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
855 
856  if (TheLoop->getHeader() != Phi->getParent())
857  return false;
858 
859  // The loop may have multiple entrances or multiple exits; we can analyze
860  // this phi if it has a unique entry value and a unique backedge value.
861  if (Phi->getNumIncomingValues() != 2)
862  return false;
863  Value *BEValue = nullptr, *StartValue = nullptr;
864  if (TheLoop->contains(Phi->getIncomingBlock(0))) {
865  BEValue = Phi->getIncomingValue(0);
866  StartValue = Phi->getIncomingValue(1);
867  } else {
868  assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
869  "Unexpected Phi node in the loop");
870  BEValue = Phi->getIncomingValue(1);
871  StartValue = Phi->getIncomingValue(0);
872  }
873 
874  BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
875  if (!BOp)
876  return false;
877 
878  Value *Addend = nullptr;
879  if (BOp->getOpcode() == Instruction::FAdd) {
880  if (BOp->getOperand(0) == Phi)
881  Addend = BOp->getOperand(1);
882  else if (BOp->getOperand(1) == Phi)
883  Addend = BOp->getOperand(0);
884  } else if (BOp->getOpcode() == Instruction::FSub)
885  if (BOp->getOperand(0) == Phi)
886  Addend = BOp->getOperand(1);
887 
888  if (!Addend)
889  return false;
890 
891  // The addend should be loop invariant
892  if (auto *I = dyn_cast<Instruction>(Addend))
893  if (TheLoop->contains(I))
894  return false;
895 
896  // FP Step has unknown SCEV
897  const SCEV *Step = SE->getUnknown(Addend);
898  D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
899  return true;
900 }
901 
902 /// This function is called when we suspect that the update-chain of a phi node
903 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
904 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
905 /// predicate P under which the SCEV expression for the phi can be the
906 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
907 /// cast instructions that are involved in the update-chain of this induction.
908 /// A caller that adds the required runtime predicate can be free to drop these
909 /// cast instructions, and compute the phi using \p AR (instead of some scev
910 /// expression with casts).
911 ///
912 /// For example, without a predicate the scev expression can take the following
913 /// form:
914 /// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
915 ///
916 /// It corresponds to the following IR sequence:
917 /// %for.body:
918 /// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
919 /// %casted_phi = "ExtTrunc i64 %x"
920 /// %add = add i64 %casted_phi, %step
921 ///
922 /// where %x is given in \p PN,
923 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
924 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
925 /// several forms, for example, such as:
926 /// ExtTrunc1: %casted_phi = and %x, 2^n-1
927 /// or:
928 /// ExtTrunc2: %t = shl %x, m
929 /// %casted_phi = ashr %t, m
930 ///
931 /// If we are able to find such sequence, we return the instructions
932 /// we found, namely %casted_phi and the instructions on its use-def chain up
933 /// to the phi (not including the phi).
935  const SCEVUnknown *PhiScev,
936  const SCEVAddRecExpr *AR,
937  SmallVectorImpl<Instruction *> &CastInsts) {
938 
939  assert(CastInsts.empty() && "CastInsts is expected to be empty.");
940  auto *PN = cast<PHINode>(PhiScev->getValue());
941  assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
942  const Loop *L = AR->getLoop();
943 
944  // Find any cast instructions that participate in the def-use chain of
945  // PhiScev in the loop.
946  // FORNOW/TODO: We currently expect the def-use chain to include only
947  // two-operand instructions, where one of the operands is an invariant.
948  // createAddRecFromPHIWithCasts() currently does not support anything more
949  // involved than that, so we keep the search simple. This can be
950  // extended/generalized as needed.
951 
952  auto getDef = [&](const Value *Val) -> Value * {
953  const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
954  if (!BinOp)
955  return nullptr;
956  Value *Op0 = BinOp->getOperand(0);
957  Value *Op1 = BinOp->getOperand(1);
958  Value *Def = nullptr;
959  if (L->isLoopInvariant(Op0))
960  Def = Op1;
961  else if (L->isLoopInvariant(Op1))
962  Def = Op0;
963  return Def;
964  };
965 
966  // Look for the instruction that defines the induction via the
967  // loop backedge.
968  BasicBlock *Latch = L->getLoopLatch();
969  if (!Latch)
970  return false;
971  Value *Val = PN->getIncomingValueForBlock(Latch);
972  if (!Val)
973  return false;
974 
975  // Follow the def-use chain until the induction phi is reached.
976  // If on the way we encounter a Value that has the same SCEV Expr as the
977  // phi node, we can consider the instructions we visit from that point
978  // as part of the cast-sequence that can be ignored.
979  bool InCastSequence = false;
980  auto *Inst = dyn_cast<Instruction>(Val);
981  while (Val != PN) {
982  // If we encountered a phi node other than PN, or if we left the loop,
983  // we bail out.
984  if (!Inst || !L->contains(Inst)) {
985  return false;
986  }
987  auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
988  if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
989  InCastSequence = true;
990  if (InCastSequence) {
991  // Only the last instruction in the cast sequence is expected to have
992  // uses outside the induction def-use chain.
993  if (!CastInsts.empty())
994  if (!Inst->hasOneUse())
995  return false;
996  CastInsts.push_back(Inst);
997  }
998  Val = getDef(Val);
999  if (!Val)
1000  return false;
1001  Inst = dyn_cast<Instruction>(Val);
1002  }
1003 
1004  return InCastSequence;
1005 }
1006 
1009  InductionDescriptor &D, bool Assume) {
1010  Type *PhiTy = Phi->getType();
1011 
1012  // Handle integer and pointer inductions variables.
1013  // Now we handle also FP induction but not trying to make a
1014  // recurrent expression from the PHI node in-place.
1015 
1016  if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1017  !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1018  return false;
1019 
1020  if (PhiTy->isFloatingPointTy())
1021  return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1022 
1023  const SCEV *PhiScev = PSE.getSCEV(Phi);
1024  const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1025 
1026  // We need this expression to be an AddRecExpr.
1027  if (Assume && !AR)
1028  AR = PSE.getAsAddRec(Phi);
1029 
1030  if (!AR) {
1031  LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1032  return false;
1033  }
1034 
1035  // Record any Cast instructions that participate in the induction update
1036  const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1037  // If we started from an UnknownSCEV, and managed to build an addRecurrence
1038  // only after enabling Assume with PSCEV, this means we may have encountered
1039  // cast instructions that required adding a runtime check in order to
1040  // guarantee the correctness of the AddRecurrence respresentation of the
1041  // induction.
1042  if (PhiScev != AR && SymbolicPhi) {
1044  if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1045  return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1046  }
1047 
1048  return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1049 }
1050 
1052  PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1053  InductionDescriptor &D, const SCEV *Expr,
1054  SmallVectorImpl<Instruction *> *CastsToIgnore) {
1055  Type *PhiTy = Phi->getType();
1056  // We only handle integer and pointer inductions variables.
1057  if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1058  return false;
1059 
1060  // Check that the PHI is consecutive.
1061  const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1062  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1063 
1064  if (!AR) {
1065  LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1066  return false;
1067  }
1068 
1069  if (AR->getLoop() != TheLoop) {
1070  // FIXME: We should treat this as a uniform. Unfortunately, we
1071  // don't currently know how to handled uniform PHIs.
1072  LLVM_DEBUG(
1073  dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1074  return false;
1075  }
1076 
1077  Value *StartValue =
1079 
1080  BasicBlock *Latch = AR->getLoop()->getLoopLatch();
1081  if (!Latch)
1082  return false;
1083  BinaryOperator *BOp =
1085 
1086  const SCEV *Step = AR->getStepRecurrence(*SE);
1087  // Calculate the pointer stride and check if it is consecutive.
1088  // The stride may be a constant or a loop invariant integer value.
1089  const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1090  if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
1091  return false;
1092 
1093  if (PhiTy->isIntegerTy()) {
1094  D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1095  CastsToIgnore);
1096  return true;
1097  }
1098 
1099  assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1100  // Pointer induction should be a constant.
1101  if (!ConstStep)
1102  return false;
1103 
1104  ConstantInt *CV = ConstStep->getValue();
1105  Type *PointerElementType = PhiTy->getPointerElementType();
1106  // The pointer stride cannot be determined if the pointer element type is not
1107  // sized.
1108  if (!PointerElementType->isSized())
1109  return false;
1110 
1111  const DataLayout &DL = Phi->getModule()->getDataLayout();
1112  int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1113  if (!Size)
1114  return false;
1115 
1116  int64_t CVSize = CV->getSExtValue();
1117  if (CVSize % Size)
1118  return false;
1119  auto *StepValue =
1120  SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
1121  D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue, BOp);
1122  return true;
1123 }
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static bool isArithmeticRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is an arithmetic kind.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:171
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:71
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:722
iterator_range< use_iterator > uses()
Definition: Value.h:375
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:209
static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D)
Returns true if Phi is a floating point induction in the loop L.
InductionDescriptor()=default
Default constructor - creates an invalid induction.
const SCEV * getConstant(ConstantInt *V)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
BinaryOps getOpcode() const
Definition: InstrTypes.h:402
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
Definition: PatternMatch.h:790
This is the interface for a simple mod/ref and alias analysis over globals.
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction *> *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
int getConsecutiveDirection() const
Get the consecutive direction.
ConstantInt * getConstIntStepValue() const
static bool AddReductionVar(PHINode *Phi, RecurrenceKind Kind, Loop *TheLoop, bool HasFunNoNaNAttr, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction of type Kind and adds it to the RecurrenceDescriptor.
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:160
const Value * getTrueValue() const
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:744
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1182
F(f)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:802
MaxMin_match< FCmpInst, LHS, RHS, ufmax_pred_ty > m_UnordFMax(const LHS &L, const RHS &R)
Match an &#39;unordered&#39; floating point maximum function.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:624
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
static InstDesc isRecurrenceInstr(Instruction *I, RecurrenceKind Kind, InstDesc &Prev, bool HasFunNoNaNAttr)
Returns a struct describing if the instruction &#39;I&#39; can be a recurrence variable of type &#39;Kind&#39;...
op_iterator op_begin()
Definition: User.h:229
static bool hasMultipleUsesOf(Instruction *I, SmallPtrSetImpl< Instruction *> &Insts, unsigned MaxNumUses)
Returns true if instruction I has multiple uses in Insts.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:48
This is the interface for a SCEV-based alias analysis.
static FastMathFlags getFast()
Definition: Operator.h:191
This class represents the LLVM &#39;select&#39; instruction.
Type * getPointerElementType() const
Definition: Type.h:381
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:162
static Instruction * lookThroughAnd(PHINode *Phi, Type *&RT, SmallPtrSetImpl< Instruction *> &Visited, SmallPtrSetImpl< Instruction *> &CI)
Determines if Phi may have been type-promoted.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl< Instruction *> &Set)
Returns true if all uses of the instruction I is within the Set.
static InstDesc isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev)
Returns a struct describing if the instruction if the instruction is a Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y) or max(X, Y).
static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR, SmallVectorImpl< Instruction *> &CastInsts)
This function is called when we suspect that the update-chain of a phi node (whose symbolic SCEV expr...
MaxMin_match< FCmpInst, LHS, RHS, ufmin_pred_ty > m_UnordFMin(const LHS &L, const RHS &R)
Match an &#39;unordered&#39; floating point minimum function.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
BlockT * getHeader() const
Definition: LoopInfo.h:105
ConstantInt * getValue() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:200
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
This node represents a polynomial recurrence on the trip count of the specified loop.
This instruction compares its operands according to the predicate given to the constructor.
MaxMin_match< FCmpInst, LHS, RHS, ofmin_pred_ty > m_OrdFMin(const LHS &L, const RHS &R)
Match an &#39;ordered&#39; floating point minimum function.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
const SCEVAddRecExpr * getAsAddRec(Value *V)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
static std::pair< Type *, bool > computeRecurrenceType(Instruction *Exit, DemandedBits *DB, AssumptionCache *AC, DominatorTree *DT)
Compute the minimal bit width needed to represent a reduction whose exit instruction is given by Exit...
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition: Constants.h:208
This POD struct holds information about a potential recurrence operation.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Value * getOperand(unsigned i) const
Definition: User.h:169
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
bool isNegative() const
Returns true if this value is known to be negative.
Definition: KnownBits.h:95
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
Definition: PatternMatch.h:195
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:486
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:582
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:470
op_iterator op_end()
Definition: User.h:231
bool isFast() const
Determine whether all fast-math-flags are set.
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:144
bool isBinaryOp() const
Definition: Instruction.h:130
op_range operands()
Definition: User.h:237
bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction in TheLoop.
const Value * getCondition() const
static InstDesc isConditionalRdxPattern(RecurrenceKind Kind, Instruction *I)
Returns a struct describing if the instruction is a Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:672
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static unsigned getRecurrenceBinOp(RecurrenceKind Kind)
Returns the opcode of binary operation corresponding to the RecurrenceKind.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static bool isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, DenseMap< Instruction *, Instruction *> &SinkAfter, DominatorTree *DT)
Returns true if Phi is a first-order recurrence.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:62
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:244
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:115
MinMaxRecurrenceKind getMinMaxKind()
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
Type * getType() const
Return the LLVM type of this SCEV expression.
A struct for saving information about induction variables.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:249
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Definition: Instruction.h:63
static bool isFloatingPointRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is a floating point kind.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:184
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:704
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:767
unsigned getNumIncomingValues() const
Return the number of incoming edges.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
Definition: PatternMatch.h:857
APInt getDemandedBits(Instruction *I)
Return the bits demanded from instruction I.
bool isCommutative() const
Return true if the instruction is commutative:
Definition: Instruction.h:498
static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit, Type *RecurrenceType, SmallPtrSetImpl< Instruction *> &Casts)
Collect cast instructions that can be ignored in the vectorizer&#39;s cost model, given a reduction exit ...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static Constant * getRecurrenceIdentity(RecurrenceKind K, Type *Tp)
Returns identity corresponding to the RecurrenceKind.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
Class for arbitrary precision integers.
Definition: APInt.h:69
iterator_range< user_iterator > users()
Definition: Value.h:420
const Value * getFalseValue() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
use_iterator use_begin()
Definition: Value.h:359
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:550
This class represents an analyzed expression in the program.
static bool isIntegerRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is an integer kind.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:220
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
uint32_t Size
Definition: Profile.cpp:46
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:145
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:396
MaxMin_match< FCmpInst, LHS, RHS, ofmax_pred_ty > m_OrdFMax(const LHS &L, const RHS &R)
Match an &#39;ordered&#39; floating point maximum function.
LLVM Value Representation.
Definition: Value.h:74
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
bool hasAllowReassoc() const
Determine whether the allow-reassociation flag is set.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:279
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
const SCEV * getUnknown(Value *V)
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:433
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:98
This pass exposes codegen information to IR-level passes.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:156
#define LLVM_DEBUG(X)
Definition: Debug.h:122
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:150
bool use_empty() const
Definition: Value.h:343
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:581
RecurrenceKind
This enum represents the kinds of recurrences that we support.
Definition: IVDescriptors.h:65
const BasicBlock * getParent() const
Definition: Instruction.h:66
This class represents a constant integer value.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1241