LLVM  9.0.0svn
ScalarEvolutionExpander.cpp
Go to the documentation of this file.
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
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 contains the implementation of the scalar evolution expander,
10 // which is used to generate the code corresponding to a given scalar evolution
11 // expression.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Support/Debug.h"
29 
30 using namespace llvm;
31 using namespace PatternMatch;
32 
33 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
34 /// reusing an existing cast if a suitable one exists, moving an existing
35 /// cast if a suitable one exists but isn't in the right place, or
36 /// creating a new one.
37 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
40  // This function must be called with the builder having a valid insertion
41  // point. It doesn't need to be the actual IP where the uses of the returned
42  // cast will be added, but it must dominate such IP.
43  // We use this precondition to produce a cast that will dominate all its
44  // uses. In particular, this is crucial for the case where the builder's
45  // insertion point *is* the point where we were asked to put the cast.
46  // Since we don't know the builder's insertion point is actually
47  // where the uses will be added (only that it dominates it), we are
48  // not allowed to move it.
49  BasicBlock::iterator BIP = Builder.GetInsertPoint();
50 
51  Instruction *Ret = nullptr;
52 
53  // Check to see if there is already a cast!
54  for (User *U : V->users())
55  if (U->getType() == Ty)
56  if (CastInst *CI = dyn_cast<CastInst>(U))
57  if (CI->getOpcode() == Op) {
58  // If the cast isn't where we want it, create a new cast at IP.
59  // Likewise, do not reuse a cast at BIP because it must dominate
60  // instructions that might be inserted before BIP.
61  if (BasicBlock::iterator(CI) != IP || BIP == IP) {
62  // Create a new cast, and leave the old cast in place in case
63  // it is being used as an insert point. Clear its operand
64  // so that it doesn't hold anything live.
65  Ret = CastInst::Create(Op, V, Ty, "", &*IP);
66  Ret->takeName(CI);
67  CI->replaceAllUsesWith(Ret);
68  CI->setOperand(0, UndefValue::get(V->getType()));
69  break;
70  }
71  Ret = CI;
72  break;
73  }
74 
75  // Create a new cast.
76  if (!Ret)
77  Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
78 
79  // We assert at the end of the function since IP might point to an
80  // instruction with different dominance properties than a cast
81  // (an invoke for example) and not dominate BIP (but the cast does).
82  assert(SE.DT.dominates(Ret, &*BIP));
83 
84  rememberInstruction(Ret);
85  return Ret;
86 }
87 
89  BasicBlock *MustDominate) {
91  if (auto *II = dyn_cast<InvokeInst>(I))
92  IP = II->getNormalDest()->begin();
93 
94  while (isa<PHINode>(IP))
95  ++IP;
96 
97  if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
98  ++IP;
99  } else if (isa<CatchSwitchInst>(IP)) {
100  IP = MustDominate->getFirstInsertionPt();
101  } else {
102  assert(!IP->isEHPad() && "unexpected eh pad!");
103  }
104 
105  return IP;
106 }
107 
108 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
109 /// which must be possible with a noop cast, doing what we can to share
110 /// the casts.
111 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
112  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
113  assert((Op == Instruction::BitCast ||
114  Op == Instruction::PtrToInt ||
115  Op == Instruction::IntToPtr) &&
116  "InsertNoopCastOfTo cannot perform non-noop casts!");
117  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
118  "InsertNoopCastOfTo cannot change sizes!");
119 
120  // Short-circuit unnecessary bitcasts.
121  if (Op == Instruction::BitCast) {
122  if (V->getType() == Ty)
123  return V;
124  if (CastInst *CI = dyn_cast<CastInst>(V)) {
125  if (CI->getOperand(0)->getType() == Ty)
126  return CI->getOperand(0);
127  }
128  }
129  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
130  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
131  SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
132  if (CastInst *CI = dyn_cast<CastInst>(V))
133  if ((CI->getOpcode() == Instruction::PtrToInt ||
134  CI->getOpcode() == Instruction::IntToPtr) &&
135  SE.getTypeSizeInBits(CI->getType()) ==
136  SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
137  return CI->getOperand(0);
138  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
139  if ((CE->getOpcode() == Instruction::PtrToInt ||
140  CE->getOpcode() == Instruction::IntToPtr) &&
141  SE.getTypeSizeInBits(CE->getType()) ==
142  SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
143  return CE->getOperand(0);
144  }
145 
146  // Fold a cast of a constant.
147  if (Constant *C = dyn_cast<Constant>(V))
148  return ConstantExpr::getCast(Op, C, Ty);
149 
150  // Cast the argument at the beginning of the entry block, after
151  // any bitcasts of other arguments.
152  if (Argument *A = dyn_cast<Argument>(V)) {
153  BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
154  while ((isa<BitCastInst>(IP) &&
155  isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
156  cast<BitCastInst>(IP)->getOperand(0) != A) ||
157  isa<DbgInfoIntrinsic>(IP))
158  ++IP;
159  return ReuseOrCreateCast(A, Ty, Op, IP);
160  }
161 
162  // Cast the instruction immediately after the instruction.
163  Instruction *I = cast<Instruction>(V);
164  BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
165  return ReuseOrCreateCast(I, Ty, Op, IP);
166 }
167 
168 /// InsertBinop - Insert the specified binary operator, doing a small amount
169 /// of work to avoid inserting an obviously redundant operation, and hoisting
170 /// to an outer loop when the opportunity is there and it is safe.
171 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172  Value *LHS, Value *RHS,
173  SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
174  // Fold a binop with constant operands.
175  if (Constant *CLHS = dyn_cast<Constant>(LHS))
176  if (Constant *CRHS = dyn_cast<Constant>(RHS))
177  return ConstantExpr::get(Opcode, CLHS, CRHS);
178 
179  // Do a quick scan to see if we have this binop nearby. If so, reuse it.
180  unsigned ScanLimit = 6;
181  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
182  // Scanning starts from the last instruction before the insertion point.
183  BasicBlock::iterator IP = Builder.GetInsertPoint();
184  if (IP != BlockBegin) {
185  --IP;
186  for (; ScanLimit; --IP, --ScanLimit) {
187  // Don't count dbg.value against the ScanLimit, to avoid perturbing the
188  // generated code.
189  if (isa<DbgInfoIntrinsic>(IP))
190  ScanLimit++;
191 
192  auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
193  // Ensure that no-wrap flags match.
194  if (isa<OverflowingBinaryOperator>(I)) {
195  if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
196  return true;
197  if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
198  return true;
199  }
200  // Conservatively, do not use any instruction which has any of exact
201  // flags installed.
202  if (isa<PossiblyExactOperator>(I) && I->isExact())
203  return true;
204  return false;
205  };
206  if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
207  IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
208  return &*IP;
209  if (IP == BlockBegin) break;
210  }
211  }
212 
213  // Save the original insertion point so we can restore it when we're done.
214  DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
215  SCEVInsertPointGuard Guard(Builder, this);
216 
217  if (IsSafeToHoist) {
218  // Move the insertion point out of as many loops as we can.
219  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
220  if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
221  BasicBlock *Preheader = L->getLoopPreheader();
222  if (!Preheader) break;
223 
224  // Ok, move up a level.
225  Builder.SetInsertPoint(Preheader->getTerminator());
226  }
227  }
228 
229  // If we haven't found this binop, insert it.
230  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
231  BO->setDebugLoc(Loc);
232  if (Flags & SCEV::FlagNUW)
233  BO->setHasNoUnsignedWrap();
234  if (Flags & SCEV::FlagNSW)
235  BO->setHasNoSignedWrap();
236  rememberInstruction(BO);
237 
238  return BO;
239 }
240 
241 /// FactorOutConstant - Test if S is divisible by Factor, using signed
242 /// division. If so, update S with Factor divided out and return true.
243 /// S need not be evenly divisible if a reasonable remainder can be
244 /// computed.
245 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
246 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
247 /// check to see if the divide was folded.
248 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
249  const SCEV *Factor, ScalarEvolution &SE,
250  const DataLayout &DL) {
251  // Everything is divisible by one.
252  if (Factor->isOne())
253  return true;
254 
255  // x/x == 1.
256  if (S == Factor) {
257  S = SE.getConstant(S->getType(), 1);
258  return true;
259  }
260 
261  // For a Constant, check for a multiple of the given factor.
262  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
263  // 0/x == 0.
264  if (C->isZero())
265  return true;
266  // Check for divisibility.
267  if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
268  ConstantInt *CI =
269  ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
270  // If the quotient is zero and the remainder is non-zero, reject
271  // the value at this scale. It will be considered for subsequent
272  // smaller scales.
273  if (!CI->isZero()) {
274  const SCEV *Div = SE.getConstant(CI);
275  S = Div;
276  Remainder = SE.getAddExpr(
277  Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
278  return true;
279  }
280  }
281  }
282 
283  // In a Mul, check if there is a constant operand which is a multiple
284  // of the given factor.
285  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
286  // Size is known, check if there is a constant operand which is a multiple
287  // of the given factor. If so, we can factor it.
288  const SCEVConstant *FC = cast<SCEVConstant>(Factor);
289  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
290  if (!C->getAPInt().srem(FC->getAPInt())) {
291  SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
292  NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
293  S = SE.getMulExpr(NewMulOps);
294  return true;
295  }
296  }
297 
298  // In an AddRec, check if both start and step are divisible.
299  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
300  const SCEV *Step = A->getStepRecurrence(SE);
301  const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
302  if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
303  return false;
304  if (!StepRem->isZero())
305  return false;
306  const SCEV *Start = A->getStart();
307  if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
308  return false;
309  S = SE.getAddRecExpr(Start, Step, A->getLoop(),
310  A->getNoWrapFlags(SCEV::FlagNW));
311  return true;
312  }
313 
314  return false;
315 }
316 
317 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
318 /// is the number of SCEVAddRecExprs present, which are kept at the end of
319 /// the list.
320 ///
322  Type *Ty,
323  ScalarEvolution &SE) {
324  unsigned NumAddRecs = 0;
325  for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
326  ++NumAddRecs;
327  // Group Ops into non-addrecs and addrecs.
328  SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
329  SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
330  // Let ScalarEvolution sort and simplify the non-addrecs list.
331  const SCEV *Sum = NoAddRecs.empty() ?
332  SE.getConstant(Ty, 0) :
333  SE.getAddExpr(NoAddRecs);
334  // If it returned an add, use the operands. Otherwise it simplified
335  // the sum into a single value, so just use that.
336  Ops.clear();
337  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
338  Ops.append(Add->op_begin(), Add->op_end());
339  else if (!Sum->isZero())
340  Ops.push_back(Sum);
341  // Then append the addrecs.
342  Ops.append(AddRecs.begin(), AddRecs.end());
343 }
344 
345 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
346 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
347 /// This helps expose more opportunities for folding parts of the expressions
348 /// into GEP indices.
349 ///
351  Type *Ty,
352  ScalarEvolution &SE) {
353  // Find the addrecs.
355  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
356  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
357  const SCEV *Start = A->getStart();
358  if (Start->isZero()) break;
359  const SCEV *Zero = SE.getConstant(Ty, 0);
360  AddRecs.push_back(SE.getAddRecExpr(Zero,
361  A->getStepRecurrence(SE),
362  A->getLoop(),
363  A->getNoWrapFlags(SCEV::FlagNW)));
364  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
365  Ops[i] = Zero;
366  Ops.append(Add->op_begin(), Add->op_end());
367  e += Add->getNumOperands();
368  } else {
369  Ops[i] = Start;
370  }
371  }
372  if (!AddRecs.empty()) {
373  // Add the addrecs onto the end of the list.
374  Ops.append(AddRecs.begin(), AddRecs.end());
375  // Resort the operand list, moving any constants to the front.
376  SimplifyAddOperands(Ops, Ty, SE);
377  }
378 }
379 
380 /// expandAddToGEP - Expand an addition expression with a pointer type into
381 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
382 /// BasicAliasAnalysis and other passes analyze the result. See the rules
383 /// for getelementptr vs. inttoptr in
384 /// http://llvm.org/docs/LangRef.html#pointeraliasing
385 /// for details.
386 ///
387 /// Design note: The correctness of using getelementptr here depends on
388 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
389 /// they may introduce pointer arithmetic which may not be safely converted
390 /// into getelementptr.
391 ///
392 /// Design note: It might seem desirable for this function to be more
393 /// loop-aware. If some of the indices are loop-invariant while others
394 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
395 /// loop-invariant portions of the overall computation outside the loop.
396 /// However, there are a few reasons this is not done here. Hoisting simple
397 /// arithmetic is a low-level optimization that often isn't very
398 /// important until late in the optimization process. In fact, passes
399 /// like InstructionCombining will combine GEPs, even if it means
400 /// pushing loop-invariant computation down into loops, so even if the
401 /// GEPs were split here, the work would quickly be undone. The
402 /// LoopStrengthReduction pass, which is usually run quite late (and
403 /// after the last InstructionCombining pass), takes care of hoisting
404 /// loop-invariant portions of expressions, after considering what
405 /// can be folded using target addressing modes.
406 ///
407 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
408  const SCEV *const *op_end,
409  PointerType *PTy,
410  Type *Ty,
411  Value *V) {
412  Type *OriginalElTy = PTy->getElementType();
413  Type *ElTy = OriginalElTy;
414  SmallVector<Value *, 4> GepIndices;
415  SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
416  bool AnyNonZeroIndices = false;
417 
418  // Split AddRecs up into parts as either of the parts may be usable
419  // without the other.
420  SplitAddRecs(Ops, Ty, SE);
421 
422  Type *IntPtrTy = DL.getIntPtrType(PTy);
423 
424  // Descend down the pointer's type and attempt to convert the other
425  // operands into GEP indices, at each level. The first index in a GEP
426  // indexes into the array implied by the pointer operand; the rest of
427  // the indices index into the element or field type selected by the
428  // preceding index.
429  for (;;) {
430  // If the scale size is not 0, attempt to factor out a scale for
431  // array indexing.
433  if (ElTy->isSized()) {
434  const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
435  if (!ElSize->isZero()) {
437  for (const SCEV *Op : Ops) {
438  const SCEV *Remainder = SE.getConstant(Ty, 0);
439  if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
440  // Op now has ElSize factored out.
441  ScaledOps.push_back(Op);
442  if (!Remainder->isZero())
443  NewOps.push_back(Remainder);
444  AnyNonZeroIndices = true;
445  } else {
446  // The operand was not divisible, so add it to the list of operands
447  // we'll scan next iteration.
448  NewOps.push_back(Op);
449  }
450  }
451  // If we made any changes, update Ops.
452  if (!ScaledOps.empty()) {
453  Ops = NewOps;
454  SimplifyAddOperands(Ops, Ty, SE);
455  }
456  }
457  }
458 
459  // Record the scaled array index for this level of the type. If
460  // we didn't find any operands that could be factored, tentatively
461  // assume that element zero was selected (since the zero offset
462  // would obviously be folded away).
463  Value *Scaled = ScaledOps.empty() ?
465  expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
466  GepIndices.push_back(Scaled);
467 
468  // Collect struct field index operands.
469  while (StructType *STy = dyn_cast<StructType>(ElTy)) {
470  bool FoundFieldNo = false;
471  // An empty struct has no fields.
472  if (STy->getNumElements() == 0) break;
473  // Field offsets are known. See if a constant offset falls within any of
474  // the struct fields.
475  if (Ops.empty())
476  break;
477  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
478  if (SE.getTypeSizeInBits(C->getType()) <= 64) {
479  const StructLayout &SL = *DL.getStructLayout(STy);
480  uint64_t FullOffset = C->getValue()->getZExtValue();
481  if (FullOffset < SL.getSizeInBytes()) {
482  unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
483  GepIndices.push_back(
485  ElTy = STy->getTypeAtIndex(ElIdx);
486  Ops[0] =
487  SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
488  AnyNonZeroIndices = true;
489  FoundFieldNo = true;
490  }
491  }
492  // If no struct field offsets were found, tentatively assume that
493  // field zero was selected (since the zero offset would obviously
494  // be folded away).
495  if (!FoundFieldNo) {
496  ElTy = STy->getTypeAtIndex(0u);
497  GepIndices.push_back(
499  }
500  }
501 
502  if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
503  ElTy = ATy->getElementType();
504  else
505  break;
506  }
507 
508  // If none of the operands were convertible to proper GEP indices, cast
509  // the base to i8* and do an ugly getelementptr with that. It's still
510  // better than ptrtoint+arithmetic+inttoptr at least.
511  if (!AnyNonZeroIndices) {
512  // Cast the base to i8*.
513  V = InsertNoopCastOfTo(V,
515 
516  assert(!isa<Instruction>(V) ||
517  SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
518 
519  // Expand the operands for a plain byte offset.
520  Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
521 
522  // Fold a GEP with constant operands.
523  if (Constant *CLHS = dyn_cast<Constant>(V))
524  if (Constant *CRHS = dyn_cast<Constant>(Idx))
526  CLHS, CRHS);
527 
528  // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
529  unsigned ScanLimit = 6;
530  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
531  // Scanning starts from the last instruction before the insertion point.
532  BasicBlock::iterator IP = Builder.GetInsertPoint();
533  if (IP != BlockBegin) {
534  --IP;
535  for (; ScanLimit; --IP, --ScanLimit) {
536  // Don't count dbg.value against the ScanLimit, to avoid perturbing the
537  // generated code.
538  if (isa<DbgInfoIntrinsic>(IP))
539  ScanLimit++;
540  if (IP->getOpcode() == Instruction::GetElementPtr &&
541  IP->getOperand(0) == V && IP->getOperand(1) == Idx)
542  return &*IP;
543  if (IP == BlockBegin) break;
544  }
545  }
546 
547  // Save the original insertion point so we can restore it when we're done.
548  SCEVInsertPointGuard Guard(Builder, this);
549 
550  // Move the insertion point out of as many loops as we can.
551  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
552  if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
553  BasicBlock *Preheader = L->getLoopPreheader();
554  if (!Preheader) break;
555 
556  // Ok, move up a level.
557  Builder.SetInsertPoint(Preheader->getTerminator());
558  }
559 
560  // Emit a GEP.
561  Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
562  rememberInstruction(GEP);
563 
564  return GEP;
565  }
566 
567  {
568  SCEVInsertPointGuard Guard(Builder, this);
569 
570  // Move the insertion point out of as many loops as we can.
571  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
572  if (!L->isLoopInvariant(V)) break;
573 
574  bool AnyIndexNotLoopInvariant = any_of(
575  GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
576 
577  if (AnyIndexNotLoopInvariant)
578  break;
579 
580  BasicBlock *Preheader = L->getLoopPreheader();
581  if (!Preheader) break;
582 
583  // Ok, move up a level.
584  Builder.SetInsertPoint(Preheader->getTerminator());
585  }
586 
587  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
588  // because ScalarEvolution may have changed the address arithmetic to
589  // compute a value which is beyond the end of the allocated object.
590  Value *Casted = V;
591  if (V->getType() != PTy)
592  Casted = InsertNoopCastOfTo(Casted, PTy);
593  Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
594  Ops.push_back(SE.getUnknown(GEP));
595  rememberInstruction(GEP);
596  }
597 
598  return expand(SE.getAddExpr(Ops));
599 }
600 
601 Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
602  Value *V) {
603  const SCEV *const Ops[1] = {Op};
604  return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
605 }
606 
607 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
608 /// SCEV expansion. If they are nested, this is the most nested. If they are
609 /// neighboring, pick the later.
610 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
611  DominatorTree &DT) {
612  if (!A) return B;
613  if (!B) return A;
614  if (A->contains(B)) return B;
615  if (B->contains(A)) return A;
616  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
617  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
618  return A; // Arbitrarily break the tie.
619 }
620 
621 /// getRelevantLoop - Get the most relevant loop associated with the given
622 /// expression, according to PickMostRelevantLoop.
623 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
624  // Test whether we've already computed the most relevant loop for this SCEV.
625  auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
626  if (!Pair.second)
627  return Pair.first->second;
628 
629  if (isa<SCEVConstant>(S))
630  // A constant has no relevant loops.
631  return nullptr;
632  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
633  if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
634  return Pair.first->second = SE.LI.getLoopFor(I->getParent());
635  // A non-instruction has no relevant loops.
636  return nullptr;
637  }
638  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
639  const Loop *L = nullptr;
640  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
641  L = AR->getLoop();
642  for (const SCEV *Op : N->operands())
643  L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
644  return RelevantLoops[N] = L;
645  }
646  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
647  const Loop *Result = getRelevantLoop(C->getOperand());
648  return RelevantLoops[C] = Result;
649  }
650  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
651  const Loop *Result = PickMostRelevantLoop(
652  getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
653  return RelevantLoops[D] = Result;
654  }
655  llvm_unreachable("Unexpected SCEV type!");
656 }
657 
658 namespace {
659 
660 /// LoopCompare - Compare loops by PickMostRelevantLoop.
661 class LoopCompare {
662  DominatorTree &DT;
663 public:
664  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
665 
666  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
667  std::pair<const Loop *, const SCEV *> RHS) const {
668  // Keep pointer operands sorted at the end.
669  if (LHS.second->getType()->isPointerTy() !=
670  RHS.second->getType()->isPointerTy())
671  return LHS.second->getType()->isPointerTy();
672 
673  // Compare loops with PickMostRelevantLoop.
674  if (LHS.first != RHS.first)
675  return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
676 
677  // If one operand is a non-constant negative and the other is not,
678  // put the non-constant negative on the right so that a sub can
679  // be used instead of a negate and add.
680  if (LHS.second->isNonConstantNegative()) {
681  if (!RHS.second->isNonConstantNegative())
682  return false;
683  } else if (RHS.second->isNonConstantNegative())
684  return true;
685 
686  // Otherwise they are equivalent according to this comparison.
687  return false;
688  }
689 };
690 
691 }
692 
693 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
694  Type *Ty = SE.getEffectiveSCEVType(S->getType());
695 
696  // Collect all the add operands in a loop, along with their associated loops.
697  // Iterate in reverse so that constants are emitted last, all else equal, and
698  // so that pointer operands are inserted first, which the code below relies on
699  // to form more involved GEPs.
701  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
702  E(S->op_begin()); I != E; ++I)
703  OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
704 
705  // Sort by loop. Use a stable sort so that constants follow non-constants and
706  // pointer operands precede non-pointer operands.
707  llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
708 
709  // Emit instructions to add all the operands. Hoist as much as possible
710  // out of loops, and form meaningful getelementptrs where possible.
711  Value *Sum = nullptr;
712  for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
713  const Loop *CurLoop = I->first;
714  const SCEV *Op = I->second;
715  if (!Sum) {
716  // This is the first operand. Just expand it.
717  Sum = expand(Op);
718  ++I;
719  } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
720  // The running sum expression is a pointer. Try to form a getelementptr
721  // at this level with that as the base.
723  for (; I != E && I->first == CurLoop; ++I) {
724  // If the operand is SCEVUnknown and not instructions, peek through
725  // it, to enable more of it to be folded into the GEP.
726  const SCEV *X = I->second;
727  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
728  if (!isa<Instruction>(U->getValue()))
729  X = SE.getSCEV(U->getValue());
730  NewOps.push_back(X);
731  }
732  Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
733  } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
734  // The running sum is an integer, and there's a pointer at this level.
735  // Try to form a getelementptr. If the running sum is instructions,
736  // use a SCEVUnknown to avoid re-analyzing them.
738  NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
739  SE.getSCEV(Sum));
740  for (++I; I != E && I->first == CurLoop; ++I)
741  NewOps.push_back(I->second);
742  Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
743  } else if (Op->isNonConstantNegative()) {
744  // Instead of doing a negate and add, just do a subtract.
745  Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
746  Sum = InsertNoopCastOfTo(Sum, Ty);
747  Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
748  /*IsSafeToHoist*/ true);
749  ++I;
750  } else {
751  // A simple add.
752  Value *W = expandCodeFor(Op, Ty);
753  Sum = InsertNoopCastOfTo(Sum, Ty);
754  // Canonicalize a constant to the RHS.
755  if (isa<Constant>(Sum)) std::swap(Sum, W);
756  Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
757  /*IsSafeToHoist*/ true);
758  ++I;
759  }
760  }
761 
762  return Sum;
763 }
764 
765 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
766  Type *Ty = SE.getEffectiveSCEVType(S->getType());
767 
768  // Collect all the mul operands in a loop, along with their associated loops.
769  // Iterate in reverse so that constants are emitted last, all else equal.
771  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
772  E(S->op_begin()); I != E; ++I)
773  OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
774 
775  // Sort by loop. Use a stable sort so that constants follow non-constants.
776  llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
777 
778  // Emit instructions to mul all the operands. Hoist as much as possible
779  // out of loops.
780  Value *Prod = nullptr;
781  auto I = OpsAndLoops.begin();
782 
783  // Expand the calculation of X pow N in the following manner:
784  // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
785  // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
786  const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
787  auto E = I;
788  // Calculate how many times the same operand from the same loop is included
789  // into this power.
790  uint64_t Exponent = 0;
791  const uint64_t MaxExponent = UINT64_MAX >> 1;
792  // No one sane will ever try to calculate such huge exponents, but if we
793  // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
794  // below when the power of 2 exceeds our Exponent, and we want it to be
795  // 1u << 31 at most to not deal with unsigned overflow.
796  while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
797  ++Exponent;
798  ++E;
799  }
800  assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
801 
802  // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
803  // that are needed into the result.
804  Value *P = expandCodeFor(I->second, Ty);
805  Value *Result = nullptr;
806  if (Exponent & 1)
807  Result = P;
808  for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
809  P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
810  /*IsSafeToHoist*/ true);
811  if (Exponent & BinExp)
812  Result = Result ? InsertBinop(Instruction::Mul, Result, P,
814  /*IsSafeToHoist*/ true)
815  : P;
816  }
817 
818  I = E;
819  assert(Result && "Nothing was expanded?");
820  return Result;
821  };
822 
823  while (I != OpsAndLoops.end()) {
824  if (!Prod) {
825  // This is the first operand. Just expand it.
826  Prod = ExpandOpBinPowN();
827  } else if (I->second->isAllOnesValue()) {
828  // Instead of doing a multiply by negative one, just do a negate.
829  Prod = InsertNoopCastOfTo(Prod, Ty);
830  Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
831  SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
832  ++I;
833  } else {
834  // A simple mul.
835  Value *W = ExpandOpBinPowN();
836  Prod = InsertNoopCastOfTo(Prod, Ty);
837  // Canonicalize a constant to the RHS.
838  if (isa<Constant>(Prod)) std::swap(Prod, W);
839  const APInt *RHS;
840  if (match(W, m_Power2(RHS))) {
841  // Canonicalize Prod*(1<<C) to Prod<<C.
842  assert(!Ty->isVectorTy() && "vector types are not SCEVable");
843  Prod = InsertBinop(Instruction::Shl, Prod,
844  ConstantInt::get(Ty, RHS->logBase2()),
845  SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
846  } else {
847  Prod = InsertBinop(Instruction::Mul, Prod, W, SCEV::FlagAnyWrap,
848  /*IsSafeToHoist*/ true);
849  }
850  }
851  }
852 
853  return Prod;
854 }
855 
856 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
857  Type *Ty = SE.getEffectiveSCEVType(S->getType());
858 
859  Value *LHS = expandCodeFor(S->getLHS(), Ty);
860  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
861  const APInt &RHS = SC->getAPInt();
862  if (RHS.isPowerOf2())
863  return InsertBinop(Instruction::LShr, LHS,
864  ConstantInt::get(Ty, RHS.logBase2()),
865  SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
866  }
867 
868  Value *RHS = expandCodeFor(S->getRHS(), Ty);
869  return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
870  /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
871 }
872 
873 /// Move parts of Base into Rest to leave Base with the minimal
874 /// expression that provides a pointer operand suitable for a
875 /// GEP expansion.
876 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
877  ScalarEvolution &SE) {
878  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
879  Base = A->getStart();
880  Rest = SE.getAddExpr(Rest,
881  SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
882  A->getStepRecurrence(SE),
883  A->getLoop(),
884  A->getNoWrapFlags(SCEV::FlagNW)));
885  }
886  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
887  Base = A->getOperand(A->getNumOperands()-1);
888  SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
889  NewAddOps.back() = Rest;
890  Rest = SE.getAddExpr(NewAddOps);
891  ExposePointerBase(Base, Rest, SE);
892  }
893 }
894 
895 /// Determine if this is a well-behaved chain of instructions leading back to
896 /// the PHI. If so, it may be reused by expanded expressions.
897 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
898  const Loop *L) {
899  if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
900  (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
901  return false;
902  // If any of the operands don't dominate the insert position, bail.
903  // Addrec operands are always loop-invariant, so this can only happen
904  // if there are instructions which haven't been hoisted.
905  if (L == IVIncInsertLoop) {
906  for (User::op_iterator OI = IncV->op_begin()+1,
907  OE = IncV->op_end(); OI != OE; ++OI)
908  if (Instruction *OInst = dyn_cast<Instruction>(OI))
909  if (!SE.DT.dominates(OInst, IVIncInsertPos))
910  return false;
911  }
912  // Advance to the next instruction.
913  IncV = dyn_cast<Instruction>(IncV->getOperand(0));
914  if (!IncV)
915  return false;
916 
917  if (IncV->mayHaveSideEffects())
918  return false;
919 
920  if (IncV == PN)
921  return true;
922 
923  return isNormalAddRecExprPHI(PN, IncV, L);
924 }
925 
926 /// getIVIncOperand returns an induction variable increment's induction
927 /// variable operand.
928 ///
929 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
930 /// operands dominate InsertPos.
931 ///
932 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
933 /// simple patterns generated by getAddRecExprPHILiterally and
934 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
936  Instruction *InsertPos,
937  bool allowScale) {
938  if (IncV == InsertPos)
939  return nullptr;
940 
941  switch (IncV->getOpcode()) {
942  default:
943  return nullptr;
944  // Check for a simple Add/Sub or GEP of a loop invariant step.
945  case Instruction::Add:
946  case Instruction::Sub: {
947  Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
948  if (!OInst || SE.DT.dominates(OInst, InsertPos))
949  return dyn_cast<Instruction>(IncV->getOperand(0));
950  return nullptr;
951  }
952  case Instruction::BitCast:
953  return dyn_cast<Instruction>(IncV->getOperand(0));
954  case Instruction::GetElementPtr:
955  for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
956  if (isa<Constant>(*I))
957  continue;
958  if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
959  if (!SE.DT.dominates(OInst, InsertPos))
960  return nullptr;
961  }
962  if (allowScale) {
963  // allow any kind of GEP as long as it can be hoisted.
964  continue;
965  }
966  // This must be a pointer addition of constants (pretty), which is already
967  // handled, or some number of address-size elements (ugly). Ugly geps
968  // have 2 operands. i1* is used by the expander to represent an
969  // address-size element.
970  if (IncV->getNumOperands() != 2)
971  return nullptr;
972  unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
973  if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
974  && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
975  return nullptr;
976  break;
977  }
978  return dyn_cast<Instruction>(IncV->getOperand(0));
979  }
980 }
981 
982 /// If the insert point of the current builder or any of the builders on the
983 /// stack of saved builders has 'I' as its insert point, update it to point to
984 /// the instruction after 'I'. This is intended to be used when the instruction
985 /// 'I' is being moved. If this fixup is not done and 'I' is moved to a
986 /// different block, the inconsistent insert point (with a mismatched
987 /// Instruction and Block) can lead to an instruction being inserted in a block
988 /// other than its parent.
989 void SCEVExpander::fixupInsertPoints(Instruction *I) {
990  BasicBlock::iterator It(*I);
991  BasicBlock::iterator NewInsertPt = std::next(It);
992  if (Builder.GetInsertPoint() == It)
993  Builder.SetInsertPoint(&*NewInsertPt);
994  for (auto *InsertPtGuard : InsertPointGuards)
995  if (InsertPtGuard->GetInsertPoint() == It)
996  InsertPtGuard->SetInsertPoint(NewInsertPt);
997 }
998 
999 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
1000 /// it available to other uses in this loop. Recursively hoist any operands,
1001 /// until we reach a value that dominates InsertPos.
1003  if (SE.DT.dominates(IncV, InsertPos))
1004  return true;
1005 
1006  // InsertPos must itself dominate IncV so that IncV's new position satisfies
1007  // its existing users.
1008  if (isa<PHINode>(InsertPos) ||
1009  !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
1010  return false;
1011 
1012  if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
1013  return false;
1014 
1015  // Check that the chain of IV operands leading back to Phi can be hoisted.
1017  for(;;) {
1018  Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
1019  if (!Oper)
1020  return false;
1021  // IncV is safe to hoist.
1022  IVIncs.push_back(IncV);
1023  IncV = Oper;
1024  if (SE.DT.dominates(IncV, InsertPos))
1025  break;
1026  }
1027  for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
1028  fixupInsertPoints(*I);
1029  (*I)->moveBefore(InsertPos);
1030  }
1031  return true;
1032 }
1033 
1034 /// Determine if this cyclic phi is in a form that would have been generated by
1035 /// LSR. We don't care if the phi was actually expanded in this pass, as long
1036 /// as it is in a low-cost form, for example, no implied multiplication. This
1037 /// should match any patterns generated by getAddRecExprPHILiterally and
1038 /// expandAddtoGEP.
1039 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
1040  const Loop *L) {
1041  for(Instruction *IVOper = IncV;
1042  (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
1043  /*allowScale=*/false));) {
1044  if (IVOper == PN)
1045  return true;
1046  }
1047  return false;
1048 }
1049 
1050 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
1051 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
1052 /// need to materialize IV increments elsewhere to handle difficult situations.
1053 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
1054  Type *ExpandTy, Type *IntTy,
1055  bool useSubtract) {
1056  Value *IncV;
1057  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1058  if (ExpandTy->isPointerTy()) {
1059  PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1060  // If the step isn't constant, don't use an implicitly scaled GEP, because
1061  // that would require a multiply inside the loop.
1062  if (!isa<ConstantInt>(StepV))
1063  GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1064  GEPPtrTy->getAddressSpace());
1065  IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
1066  if (IncV->getType() != PN->getType()) {
1067  IncV = Builder.CreateBitCast(IncV, PN->getType());
1068  rememberInstruction(IncV);
1069  }
1070  } else {
1071  IncV = useSubtract ?
1072  Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1073  Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1074  rememberInstruction(IncV);
1075  }
1076  return IncV;
1077 }
1078 
1079 /// Hoist the addrec instruction chain rooted in the loop phi above the
1080 /// position. This routine assumes that this is possible (has been checked).
1081 void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1082  Instruction *Pos, PHINode *LoopPhi) {
1083  do {
1084  if (DT->dominates(InstToHoist, Pos))
1085  break;
1086  // Make sure the increment is where we want it. But don't move it
1087  // down past a potential existing post-inc user.
1088  fixupInsertPoints(InstToHoist);
1089  InstToHoist->moveBefore(Pos);
1090  Pos = InstToHoist;
1091  InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1092  } while (InstToHoist != LoopPhi);
1093 }
1094 
1095 /// Check whether we can cheaply express the requested SCEV in terms of
1096 /// the available PHI SCEV by truncation and/or inversion of the step.
1098  const SCEVAddRecExpr *Phi,
1099  const SCEVAddRecExpr *Requested,
1100  bool &InvertStep) {
1101  Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1102  Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1103 
1104  if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1105  return false;
1106 
1107  // Try truncate it if necessary.
1108  Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1109  if (!Phi)
1110  return false;
1111 
1112  // Check whether truncation will help.
1113  if (Phi == Requested) {
1114  InvertStep = false;
1115  return true;
1116  }
1117 
1118  // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1119  if (SE.getAddExpr(Requested->getStart(),
1120  SE.getNegativeSCEV(Requested)) == Phi) {
1121  InvertStep = true;
1122  return true;
1123  }
1124 
1125  return false;
1126 }
1127 
1128 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1129  if (!isa<IntegerType>(AR->getType()))
1130  return false;
1131 
1132  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1133  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1134  const SCEV *Step = AR->getStepRecurrence(SE);
1135  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1136  SE.getSignExtendExpr(AR, WideTy));
1137  const SCEV *ExtendAfterOp =
1138  SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1139  return ExtendAfterOp == OpAfterExtend;
1140 }
1141 
1142 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1143  if (!isa<IntegerType>(AR->getType()))
1144  return false;
1145 
1146  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1147  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1148  const SCEV *Step = AR->getStepRecurrence(SE);
1149  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1150  SE.getZeroExtendExpr(AR, WideTy));
1151  const SCEV *ExtendAfterOp =
1152  SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1153  return ExtendAfterOp == OpAfterExtend;
1154 }
1155 
1156 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1157 /// the base addrec, which is the addrec without any non-loop-dominating
1158 /// values, and return the PHI.
1159 PHINode *
1160 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1161  const Loop *L,
1162  Type *ExpandTy,
1163  Type *IntTy,
1164  Type *&TruncTy,
1165  bool &InvertStep) {
1166  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1167 
1168  // Reuse a previously-inserted PHI, if present.
1169  BasicBlock *LatchBlock = L->getLoopLatch();
1170  if (LatchBlock) {
1171  PHINode *AddRecPhiMatch = nullptr;
1172  Instruction *IncV = nullptr;
1173  TruncTy = nullptr;
1174  InvertStep = false;
1175 
1176  // Only try partially matching scevs that need truncation and/or
1177  // step-inversion if we know this loop is outside the current loop.
1178  bool TryNonMatchingSCEV =
1179  IVIncInsertLoop &&
1180  SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1181 
1182  for (PHINode &PN : L->getHeader()->phis()) {
1183  if (!SE.isSCEVable(PN.getType()))
1184  continue;
1185 
1186  const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1187  if (!PhiSCEV)
1188  continue;
1189 
1190  bool IsMatchingSCEV = PhiSCEV == Normalized;
1191  // We only handle truncation and inversion of phi recurrences for the
1192  // expanded expression if the expanded expression's loop dominates the
1193  // loop we insert to. Check now, so we can bail out early.
1194  if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1195  continue;
1196 
1197  // TODO: this possibly can be reworked to avoid this cast at all.
1198  Instruction *TempIncV =
1200  if (!TempIncV)
1201  continue;
1202 
1203  // Check whether we can reuse this PHI node.
1204  if (LSRMode) {
1205  if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1206  continue;
1207  if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1208  continue;
1209  } else {
1210  if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1211  continue;
1212  }
1213 
1214  // Stop if we have found an exact match SCEV.
1215  if (IsMatchingSCEV) {
1216  IncV = TempIncV;
1217  TruncTy = nullptr;
1218  InvertStep = false;
1219  AddRecPhiMatch = &PN;
1220  break;
1221  }
1222 
1223  // Try whether the phi can be translated into the requested form
1224  // (truncated and/or offset by a constant).
1225  if ((!TruncTy || InvertStep) &&
1226  canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1227  // Record the phi node. But don't stop we might find an exact match
1228  // later.
1229  AddRecPhiMatch = &PN;
1230  IncV = TempIncV;
1231  TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1232  }
1233  }
1234 
1235  if (AddRecPhiMatch) {
1236  // Potentially, move the increment. We have made sure in
1237  // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1238  if (L == IVIncInsertLoop)
1239  hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1240 
1241  // Ok, the add recurrence looks usable.
1242  // Remember this PHI, even in post-inc mode.
1243  InsertedValues.insert(AddRecPhiMatch);
1244  // Remember the increment.
1245  rememberInstruction(IncV);
1246  return AddRecPhiMatch;
1247  }
1248  }
1249 
1250  // Save the original insertion point so we can restore it when we're done.
1251  SCEVInsertPointGuard Guard(Builder, this);
1252 
1253  // Another AddRec may need to be recursively expanded below. For example, if
1254  // this AddRec is quadratic, the StepV may itself be an AddRec in this
1255  // loop. Remove this loop from the PostIncLoops set before expanding such
1256  // AddRecs. Otherwise, we cannot find a valid position for the step
1257  // (i.e. StepV can never dominate its loop header). Ideally, we could do
1258  // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1259  // so it's not worth implementing SmallPtrSet::swap.
1260  PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1261  PostIncLoops.clear();
1262 
1263  // Expand code for the start value into the loop preheader.
1264  assert(L->getLoopPreheader() &&
1265  "Can't expand add recurrences without a loop preheader!");
1266  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1268 
1269  // StartV must have been be inserted into L's preheader to dominate the new
1270  // phi.
1271  assert(!isa<Instruction>(StartV) ||
1272  SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1273  L->getHeader()));
1274 
1275  // Expand code for the step value. Do this before creating the PHI so that PHI
1276  // reuse code doesn't see an incomplete PHI.
1277  const SCEV *Step = Normalized->getStepRecurrence(SE);
1278  // If the stride is negative, insert a sub instead of an add for the increment
1279  // (unless it's a constant, because subtracts of constants are canonicalized
1280  // to adds).
1281  bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1282  if (useSubtract)
1283  Step = SE.getNegativeSCEV(Step);
1284  // Expand the step somewhere that dominates the loop header.
1285  Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1286 
1287  // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1288  // we actually do emit an addition. It does not apply if we emit a
1289  // subtraction.
1290  bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1291  bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1292 
1293  // Create the PHI.
1294  BasicBlock *Header = L->getHeader();
1295  Builder.SetInsertPoint(Header, Header->begin());
1296  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1297  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1298  Twine(IVName) + ".iv");
1299  rememberInstruction(PN);
1300 
1301  // Create the step instructions and populate the PHI.
1302  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1303  BasicBlock *Pred = *HPI;
1304 
1305  // Add a start value.
1306  if (!L->contains(Pred)) {
1307  PN->addIncoming(StartV, Pred);
1308  continue;
1309  }
1310 
1311  // Create a step value and add it to the PHI.
1312  // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1313  // instructions at IVIncInsertPos.
1314  Instruction *InsertPos = L == IVIncInsertLoop ?
1315  IVIncInsertPos : Pred->getTerminator();
1316  Builder.SetInsertPoint(InsertPos);
1317  Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1318 
1319  if (isa<OverflowingBinaryOperator>(IncV)) {
1320  if (IncrementIsNUW)
1321  cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1322  if (IncrementIsNSW)
1323  cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1324  }
1325  PN->addIncoming(IncV, Pred);
1326  }
1327 
1328  // After expanding subexpressions, restore the PostIncLoops set so the caller
1329  // can ensure that IVIncrement dominates the current uses.
1330  PostIncLoops = SavedPostIncLoops;
1331 
1332  // Remember this PHI, even in post-inc mode.
1333  InsertedValues.insert(PN);
1334 
1335  return PN;
1336 }
1337 
1338 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1339  Type *STy = S->getType();
1340  Type *IntTy = SE.getEffectiveSCEVType(STy);
1341  const Loop *L = S->getLoop();
1342 
1343  // Determine a normalized form of this expression, which is the expression
1344  // before any post-inc adjustment is made.
1345  const SCEVAddRecExpr *Normalized = S;
1346  if (PostIncLoops.count(L)) {
1348  Loops.insert(L);
1349  Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
1350  }
1351 
1352  // Strip off any non-loop-dominating component from the addrec start.
1353  const SCEV *Start = Normalized->getStart();
1354  const SCEV *PostLoopOffset = nullptr;
1355  if (!SE.properlyDominates(Start, L->getHeader())) {
1356  PostLoopOffset = Start;
1357  Start = SE.getConstant(Normalized->getType(), 0);
1358  Normalized = cast<SCEVAddRecExpr>(
1359  SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1360  Normalized->getLoop(),
1361  Normalized->getNoWrapFlags(SCEV::FlagNW)));
1362  }
1363 
1364  // Strip off any non-loop-dominating component from the addrec step.
1365  const SCEV *Step = Normalized->getStepRecurrence(SE);
1366  const SCEV *PostLoopScale = nullptr;
1367  if (!SE.dominates(Step, L->getHeader())) {
1368  PostLoopScale = Step;
1369  Step = SE.getConstant(Normalized->getType(), 1);
1370  if (!Start->isZero()) {
1371  // The normalization below assumes that Start is constant zero, so if
1372  // it isn't re-associate Start to PostLoopOffset.
1373  assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1374  PostLoopOffset = Start;
1375  Start = SE.getConstant(Normalized->getType(), 0);
1376  }
1377  Normalized =
1378  cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1379  Start, Step, Normalized->getLoop(),
1380  Normalized->getNoWrapFlags(SCEV::FlagNW)));
1381  }
1382 
1383  // Expand the core addrec. If we need post-loop scaling, force it to
1384  // expand to an integer type to avoid the need for additional casting.
1385  Type *ExpandTy = PostLoopScale ? IntTy : STy;
1386  // We can't use a pointer type for the addrec if the pointer type is
1387  // non-integral.
1388  Type *AddRecPHIExpandTy =
1389  DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
1390 
1391  // In some cases, we decide to reuse an existing phi node but need to truncate
1392  // it and/or invert the step.
1393  Type *TruncTy = nullptr;
1394  bool InvertStep = false;
1395  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
1396  IntTy, TruncTy, InvertStep);
1397 
1398  // Accommodate post-inc mode, if necessary.
1399  Value *Result;
1400  if (!PostIncLoops.count(L))
1401  Result = PN;
1402  else {
1403  // In PostInc mode, use the post-incremented value.
1404  BasicBlock *LatchBlock = L->getLoopLatch();
1405  assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1406  Result = PN->getIncomingValueForBlock(LatchBlock);
1407 
1408  // For an expansion to use the postinc form, the client must call
1409  // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1410  // or dominated by IVIncInsertPos.
1411  if (isa<Instruction>(Result) &&
1412  !SE.DT.dominates(cast<Instruction>(Result),
1413  &*Builder.GetInsertPoint())) {
1414  // The induction variable's postinc expansion does not dominate this use.
1415  // IVUsers tries to prevent this case, so it is rare. However, it can
1416  // happen when an IVUser outside the loop is not dominated by the latch
1417  // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1418  // all cases. Consider a phi outside whose operand is replaced during
1419  // expansion with the value of the postinc user. Without fundamentally
1420  // changing the way postinc users are tracked, the only remedy is
1421  // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1422  // but hopefully expandCodeFor handles that.
1423  bool useSubtract =
1424  !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1425  if (useSubtract)
1426  Step = SE.getNegativeSCEV(Step);
1427  Value *StepV;
1428  {
1429  // Expand the step somewhere that dominates the loop header.
1430  SCEVInsertPointGuard Guard(Builder, this);
1431  StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1432  }
1433  Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1434  }
1435  }
1436 
1437  // We have decided to reuse an induction variable of a dominating loop. Apply
1438  // truncation and/or inversion of the step.
1439  if (TruncTy) {
1440  Type *ResTy = Result->getType();
1441  // Normalize the result type.
1442  if (ResTy != SE.getEffectiveSCEVType(ResTy))
1443  Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1444  // Truncate the result.
1445  if (TruncTy != Result->getType()) {
1446  Result = Builder.CreateTrunc(Result, TruncTy);
1447  rememberInstruction(Result);
1448  }
1449  // Invert the result.
1450  if (InvertStep) {
1451  Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1452  Result);
1453  rememberInstruction(Result);
1454  }
1455  }
1456 
1457  // Re-apply any non-loop-dominating scale.
1458  if (PostLoopScale) {
1459  assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1460  Result = InsertNoopCastOfTo(Result, IntTy);
1461  Result = Builder.CreateMul(Result,
1462  expandCodeFor(PostLoopScale, IntTy));
1463  rememberInstruction(Result);
1464  }
1465 
1466  // Re-apply any non-loop-dominating offset.
1467  if (PostLoopOffset) {
1468  if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1469  if (Result->getType()->isIntegerTy()) {
1470  Value *Base = expandCodeFor(PostLoopOffset, ExpandTy);
1471  Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
1472  } else {
1473  Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
1474  }
1475  } else {
1476  Result = InsertNoopCastOfTo(Result, IntTy);
1477  Result = Builder.CreateAdd(Result,
1478  expandCodeFor(PostLoopOffset, IntTy));
1479  rememberInstruction(Result);
1480  }
1481  }
1482 
1483  return Result;
1484 }
1485 
1486 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1487  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1488 
1489  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1490  const Loop *L = S->getLoop();
1491 
1492  // First check for an existing canonical IV in a suitable type.
1493  PHINode *CanonicalIV = nullptr;
1494  if (PHINode *PN = L->getCanonicalInductionVariable())
1495  if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1496  CanonicalIV = PN;
1497 
1498  // Rewrite an AddRec in terms of the canonical induction variable, if
1499  // its type is more narrow.
1500  if (CanonicalIV &&
1501  SE.getTypeSizeInBits(CanonicalIV->getType()) >
1502  SE.getTypeSizeInBits(Ty)) {
1504  for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1505  NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1506  Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1508  BasicBlock::iterator NewInsertPt =
1509  findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1510  V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1511  &*NewInsertPt);
1512  return V;
1513  }
1514 
1515  // {X,+,F} --> X + {0,+,F}
1516  if (!S->getStart()->isZero()) {
1517  SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1518  NewOps[0] = SE.getConstant(Ty, 0);
1519  const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1521 
1522  // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1523  // comments on expandAddToGEP for details.
1524  const SCEV *Base = S->getStart();
1525  // Dig into the expression to find the pointer base for a GEP.
1526  const SCEV *ExposedRest = Rest;
1527  ExposePointerBase(Base, ExposedRest, SE);
1528  // If we found a pointer, expand the AddRec with a GEP.
1529  if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1530  // Make sure the Base isn't something exotic, such as a multiplied
1531  // or divided pointer value. In those cases, the result type isn't
1532  // actually a pointer type.
1533  if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1534  Value *StartV = expand(Base);
1535  assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1536  return expandAddToGEP(ExposedRest, PTy, Ty, StartV);
1537  }
1538  }
1539 
1540  // Just do a normal add. Pre-expand the operands to suppress folding.
1541  //
1542  // The LHS and RHS values are factored out of the expand call to make the
1543  // output independent of the argument evaluation order.
1544  const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1545  const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1546  return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1547  }
1548 
1549  // If we don't yet have a canonical IV, create one.
1550  if (!CanonicalIV) {
1551  // Create and insert the PHI node for the induction variable in the
1552  // specified loop.
1553  BasicBlock *Header = L->getHeader();
1554  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1555  CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1556  &Header->front());
1557  rememberInstruction(CanonicalIV);
1558 
1559  SmallSet<BasicBlock *, 4> PredSeen;
1560  Constant *One = ConstantInt::get(Ty, 1);
1561  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1562  BasicBlock *HP = *HPI;
1563  if (!PredSeen.insert(HP).second) {
1564  // There must be an incoming value for each predecessor, even the
1565  // duplicates!
1566  CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1567  continue;
1568  }
1569 
1570  if (L->contains(HP)) {
1571  // Insert a unit add instruction right before the terminator
1572  // corresponding to the back-edge.
1573  Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1574  "indvar.next",
1575  HP->getTerminator());
1576  Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1577  rememberInstruction(Add);
1578  CanonicalIV->addIncoming(Add, HP);
1579  } else {
1580  CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1581  }
1582  }
1583  }
1584 
1585  // {0,+,1} --> Insert a canonical induction variable into the loop!
1586  if (S->isAffine() && S->getOperand(1)->isOne()) {
1587  assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1588  "IVs with types different from the canonical IV should "
1589  "already have been handled!");
1590  return CanonicalIV;
1591  }
1592 
1593  // {0,+,F} --> {0,+,1} * F
1594 
1595  // If this is a simple linear addrec, emit it now as a special case.
1596  if (S->isAffine()) // {0,+,F} --> i*F
1597  return
1598  expand(SE.getTruncateOrNoop(
1599  SE.getMulExpr(SE.getUnknown(CanonicalIV),
1600  SE.getNoopOrAnyExtend(S->getOperand(1),
1601  CanonicalIV->getType())),
1602  Ty));
1603 
1604  // If this is a chain of recurrences, turn it into a closed form, using the
1605  // folders, then expandCodeFor the closed form. This allows the folders to
1606  // simplify the expression without having to build a bunch of special code
1607  // into this folder.
1608  const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1609 
1610  // Promote S up to the canonical IV type, if the cast is foldable.
1611  const SCEV *NewS = S;
1612  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1613  if (isa<SCEVAddRecExpr>(Ext))
1614  NewS = Ext;
1615 
1616  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1617  //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1618 
1619  // Truncate the result down to the original type, if needed.
1620  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1621  return expand(T);
1622 }
1623 
1624 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1625  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1626  Value *V = expandCodeFor(S->getOperand(),
1627  SE.getEffectiveSCEVType(S->getOperand()->getType()));
1628  Value *I = Builder.CreateTrunc(V, Ty);
1629  rememberInstruction(I);
1630  return I;
1631 }
1632 
1633 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1634  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1635  Value *V = expandCodeFor(S->getOperand(),
1636  SE.getEffectiveSCEVType(S->getOperand()->getType()));
1637  Value *I = Builder.CreateZExt(V, Ty);
1638  rememberInstruction(I);
1639  return I;
1640 }
1641 
1642 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1643  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1644  Value *V = expandCodeFor(S->getOperand(),
1645  SE.getEffectiveSCEVType(S->getOperand()->getType()));
1646  Value *I = Builder.CreateSExt(V, Ty);
1647  rememberInstruction(I);
1648  return I;
1649 }
1650 
1651 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1652  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1653  Type *Ty = LHS->getType();
1654  for (int i = S->getNumOperands()-2; i >= 0; --i) {
1655  // In the case of mixed integer and pointer types, do the
1656  // rest of the comparisons as integer.
1657  Type *OpTy = S->getOperand(i)->getType();
1658  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1659  Ty = SE.getEffectiveSCEVType(Ty);
1660  LHS = InsertNoopCastOfTo(LHS, Ty);
1661  }
1662  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1663  Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1664  rememberInstruction(ICmp);
1665  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1666  rememberInstruction(Sel);
1667  LHS = Sel;
1668  }
1669  // In the case of mixed integer and pointer types, cast the
1670  // final result back to the pointer type.
1671  if (LHS->getType() != S->getType())
1672  LHS = InsertNoopCastOfTo(LHS, S->getType());
1673  return LHS;
1674 }
1675 
1676 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1677  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1678  Type *Ty = LHS->getType();
1679  for (int i = S->getNumOperands()-2; i >= 0; --i) {
1680  // In the case of mixed integer and pointer types, do the
1681  // rest of the comparisons as integer.
1682  Type *OpTy = S->getOperand(i)->getType();
1683  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1684  Ty = SE.getEffectiveSCEVType(Ty);
1685  LHS = InsertNoopCastOfTo(LHS, Ty);
1686  }
1687  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1688  Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1689  rememberInstruction(ICmp);
1690  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1691  rememberInstruction(Sel);
1692  LHS = Sel;
1693  }
1694  // In the case of mixed integer and pointer types, cast the
1695  // final result back to the pointer type.
1696  if (LHS->getType() != S->getType())
1697  LHS = InsertNoopCastOfTo(LHS, S->getType());
1698  return LHS;
1699 }
1700 
1701 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
1702  Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1703  Type *Ty = LHS->getType();
1704  for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1705  // In the case of mixed integer and pointer types, do the
1706  // rest of the comparisons as integer.
1707  Type *OpTy = S->getOperand(i)->getType();
1708  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1709  Ty = SE.getEffectiveSCEVType(Ty);
1710  LHS = InsertNoopCastOfTo(LHS, Ty);
1711  }
1712  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1713  Value *ICmp = Builder.CreateICmpSLT(LHS, RHS);
1714  rememberInstruction(ICmp);
1715  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smin");
1716  rememberInstruction(Sel);
1717  LHS = Sel;
1718  }
1719  // In the case of mixed integer and pointer types, cast the
1720  // final result back to the pointer type.
1721  if (LHS->getType() != S->getType())
1722  LHS = InsertNoopCastOfTo(LHS, S->getType());
1723  return LHS;
1724 }
1725 
1726 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
1727  Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1728  Type *Ty = LHS->getType();
1729  for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1730  // In the case of mixed integer and pointer types, do the
1731  // rest of the comparisons as integer.
1732  Type *OpTy = S->getOperand(i)->getType();
1733  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1734  Ty = SE.getEffectiveSCEVType(Ty);
1735  LHS = InsertNoopCastOfTo(LHS, Ty);
1736  }
1737  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1738  Value *ICmp = Builder.CreateICmpULT(LHS, RHS);
1739  rememberInstruction(ICmp);
1740  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umin");
1741  rememberInstruction(Sel);
1742  LHS = Sel;
1743  }
1744  // In the case of mixed integer and pointer types, cast the
1745  // final result back to the pointer type.
1746  if (LHS->getType() != S->getType())
1747  LHS = InsertNoopCastOfTo(LHS, S->getType());
1748  return LHS;
1749 }
1750 
1752  Instruction *IP) {
1753  setInsertPoint(IP);
1754  return expandCodeFor(SH, Ty);
1755 }
1756 
1758  // Expand the code for this SCEV.
1759  Value *V = expand(SH);
1760  if (Ty) {
1761  assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1762  "non-trivial casts should be done with the SCEVs directly!");
1763  V = InsertNoopCastOfTo(V, Ty);
1764  }
1765  return V;
1766 }
1767 
1768 ScalarEvolution::ValueOffsetPair
1769 SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1770  const Instruction *InsertPt) {
1771  SetVector<ScalarEvolution::ValueOffsetPair> *Set = SE.getSCEVValues(S);
1772  // If the expansion is not in CanonicalMode, and the SCEV contains any
1773  // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1774  if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1775  // If S is scConstant, it may be worse to reuse an existing Value.
1776  if (S->getSCEVType() != scConstant && Set) {
1777  // Choose a Value from the set which dominates the insertPt.
1778  // insertPt should be inside the Value's parent loop so as not to break
1779  // the LCSSA form.
1780  for (auto const &VOPair : *Set) {
1781  Value *V = VOPair.first;
1782  ConstantInt *Offset = VOPair.second;
1783  Instruction *EntInst = nullptr;
1784  if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) &&
1785  S->getType() == V->getType() &&
1786  EntInst->getFunction() == InsertPt->getFunction() &&
1787  SE.DT.dominates(EntInst, InsertPt) &&
1788  (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1789  SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1790  return {V, Offset};
1791  }
1792  }
1793  }
1794  return {nullptr, nullptr};
1795 }
1796 
1797 // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1798 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1799 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1800 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1801 // the expansion will try to reuse Value from ExprValueMap, and only when it
1802 // fails, expand the SCEV literally.
1803 Value *SCEVExpander::expand(const SCEV *S) {
1804  // Compute an insertion point for this SCEV object. Hoist the instructions
1805  // as far out in the loop nest as possible.
1806  Instruction *InsertPt = &*Builder.GetInsertPoint();
1807 
1808  // We can move insertion point only if there is no div or rem operations
1809  // otherwise we are risky to move it over the check for zero denominator.
1810  auto SafeToHoist = [](const SCEV *S) {
1811  return !SCEVExprContains(S, [](const SCEV *S) {
1812  if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1813  if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1814  // Division by non-zero constants can be hoisted.
1815  return SC->getValue()->isZero();
1816  // All other divisions should not be moved as they may be
1817  // divisions by zero and should be kept within the
1818  // conditions of the surrounding loops that guard their
1819  // execution (see PR35406).
1820  return true;
1821  }
1822  return false;
1823  });
1824  };
1825  if (SafeToHoist(S)) {
1826  for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1827  L = L->getParentLoop()) {
1828  if (SE.isLoopInvariant(S, L)) {
1829  if (!L) break;
1830  if (BasicBlock *Preheader = L->getLoopPreheader())
1831  InsertPt = Preheader->getTerminator();
1832  else
1833  // LSR sets the insertion point for AddRec start/step values to the
1834  // block start to simplify value reuse, even though it's an invalid
1835  // position. SCEVExpander must correct for this in all cases.
1836  InsertPt = &*L->getHeader()->getFirstInsertionPt();
1837  } else {
1838  // If the SCEV is computable at this level, insert it into the header
1839  // after the PHIs (and after any other instructions that we've inserted
1840  // there) so that it is guaranteed to dominate any user inside the loop.
1841  if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1842  InsertPt = &*L->getHeader()->getFirstInsertionPt();
1843  while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1844  (isInsertedInstruction(InsertPt) ||
1845  isa<DbgInfoIntrinsic>(InsertPt)))
1846  InsertPt = &*std::next(InsertPt->getIterator());
1847  break;
1848  }
1849  }
1850  }
1851 
1852  // IndVarSimplify sometimes sets the insertion point at the block start, even
1853  // when there are PHIs at that point. We must correct for this.
1854  if (isa<PHINode>(*InsertPt))
1855  InsertPt = &*InsertPt->getParent()->getFirstInsertionPt();
1856 
1857  // Check to see if we already expanded this here.
1858  auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1859  if (I != InsertedExpressions.end())
1860  return I->second;
1861 
1862  SCEVInsertPointGuard Guard(Builder, this);
1863  Builder.SetInsertPoint(InsertPt);
1864 
1865  // Expand the expression into instructions.
1866  ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
1867  Value *V = VO.first;
1868 
1869  if (!V)
1870  V = visit(S);
1871  else if (VO.second) {
1872  if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) {
1873  Type *Ety = Vty->getPointerElementType();
1874  int64_t Offset = VO.second->getSExtValue();
1875  int64_t ESize = SE.getTypeSizeInBits(Ety);
1876  if ((Offset * 8) % ESize == 0) {
1877  ConstantInt *Idx =
1878  ConstantInt::getSigned(VO.second->getType(), -(Offset * 8) / ESize);
1879  V = Builder.CreateGEP(Ety, V, Idx, "scevgep");
1880  } else {
1881  ConstantInt *Idx =
1882  ConstantInt::getSigned(VO.second->getType(), -Offset);
1883  unsigned AS = Vty->getAddressSpace();
1884  V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS));
1885  V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx,
1886  "uglygep");
1887  V = Builder.CreateBitCast(V, Vty);
1888  }
1889  } else {
1890  V = Builder.CreateSub(V, VO.second);
1891  }
1892  }
1893  // Remember the expanded value for this SCEV at this location.
1894  //
1895  // This is independent of PostIncLoops. The mapped value simply materializes
1896  // the expression at this insertion point. If the mapped value happened to be
1897  // a postinc expansion, it could be reused by a non-postinc user, but only if
1898  // its insertion point was already at the head of the loop.
1899  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1900  return V;
1901 }
1902 
1903 void SCEVExpander::rememberInstruction(Value *I) {
1904  if (!PostIncLoops.empty())
1905  InsertedPostIncValues.insert(I);
1906  else
1907  InsertedValues.insert(I);
1908 }
1909 
1910 /// getOrInsertCanonicalInductionVariable - This method returns the
1911 /// canonical induction variable of the specified type for the specified
1912 /// loop (inserting one if there is none). A canonical induction variable
1913 /// starts at zero and steps by one on each iteration.
1914 PHINode *
1916  Type *Ty) {
1917  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1918 
1919  // Build a SCEV for {0,+,1}<L>.
1920  // Conservatively use FlagAnyWrap for now.
1921  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1922  SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1923 
1924  // Emit code for it.
1925  SCEVInsertPointGuard Guard(Builder, this);
1926  PHINode *V =
1927  cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1928 
1929  return V;
1930 }
1931 
1932 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1933 /// replace them with their most canonical representative. Return the number of
1934 /// phis eliminated.
1935 ///
1936 /// This does not depend on any SCEVExpander state but should be used in
1937 /// the same context that SCEVExpander is used.
1938 unsigned
1941  const TargetTransformInfo *TTI) {
1942  // Find integer phis in order of increasing width.
1944  for (PHINode &PN : L->getHeader()->phis())
1945  Phis.push_back(&PN);
1946 
1947  if (TTI)
1948  llvm::sort(Phis, [](Value *LHS, Value *RHS) {
1949  // Put pointers at the back and make sure pointer < pointer = false.
1950  if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1951  return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1952  return RHS->getType()->getPrimitiveSizeInBits() <
1953  LHS->getType()->getPrimitiveSizeInBits();
1954  });
1955 
1956  unsigned NumElim = 0;
1958  // Process phis from wide to narrow. Map wide phis to their truncation
1959  // so narrow phis can reuse them.
1960  for (PHINode *Phi : Phis) {
1961  auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1962  if (Value *V = SimplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1963  return V;
1964  if (!SE.isSCEVable(PN->getType()))
1965  return nullptr;
1966  auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1967  if (!Const)
1968  return nullptr;
1969  return Const->getValue();
1970  };
1971 
1972  // Fold constant phis. They may be congruent to other constant phis and
1973  // would confuse the logic below that expects proper IVs.
1974  if (Value *V = SimplifyPHINode(Phi)) {
1975  if (V->getType() != Phi->getType())
1976  continue;
1977  Phi->replaceAllUsesWith(V);
1978  DeadInsts.emplace_back(Phi);
1979  ++NumElim;
1981  << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1982  continue;
1983  }
1984 
1985  if (!SE.isSCEVable(Phi->getType()))
1986  continue;
1987 
1988  PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1989  if (!OrigPhiRef) {
1990  OrigPhiRef = Phi;
1991  if (Phi->getType()->isIntegerTy() && TTI &&
1992  TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1993  // This phi can be freely truncated to the narrowest phi type. Map the
1994  // truncated expression to it so it will be reused for narrow types.
1995  const SCEV *TruncExpr =
1996  SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1997  ExprToIVMap[TruncExpr] = Phi;
1998  }
1999  continue;
2000  }
2001 
2002  // Replacing a pointer phi with an integer phi or vice-versa doesn't make
2003  // sense.
2004  if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
2005  continue;
2006 
2007  if (BasicBlock *LatchBlock = L->getLoopLatch()) {
2008  Instruction *OrigInc = dyn_cast<Instruction>(
2009  OrigPhiRef->getIncomingValueForBlock(LatchBlock));
2010  Instruction *IsomorphicInc =
2011  dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
2012 
2013  if (OrigInc && IsomorphicInc) {
2014  // If this phi has the same width but is more canonical, replace the
2015  // original with it. As part of the "more canonical" determination,
2016  // respect a prior decision to use an IV chain.
2017  if (OrigPhiRef->getType() == Phi->getType() &&
2018  !(ChainedPhis.count(Phi) ||
2019  isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
2020  (ChainedPhis.count(Phi) ||
2021  isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
2022  std::swap(OrigPhiRef, Phi);
2023  std::swap(OrigInc, IsomorphicInc);
2024  }
2025  // Replacing the congruent phi is sufficient because acyclic
2026  // redundancy elimination, CSE/GVN, should handle the
2027  // rest. However, once SCEV proves that a phi is congruent,
2028  // it's often the head of an IV user cycle that is isomorphic
2029  // with the original phi. It's worth eagerly cleaning up the
2030  // common case of a single IV increment so that DeleteDeadPHIs
2031  // can remove cycles that had postinc uses.
2032  const SCEV *TruncExpr =
2033  SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
2034  if (OrigInc != IsomorphicInc &&
2035  TruncExpr == SE.getSCEV(IsomorphicInc) &&
2036  SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
2037  hoistIVInc(OrigInc, IsomorphicInc)) {
2039  dbgs() << "INDVARS: Eliminated congruent iv.inc: "
2040  << *IsomorphicInc << '\n');
2041  Value *NewInc = OrigInc;
2042  if (OrigInc->getType() != IsomorphicInc->getType()) {
2043  Instruction *IP = nullptr;
2044  if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
2045  IP = &*PN->getParent()->getFirstInsertionPt();
2046  else
2047  IP = OrigInc->getNextNode();
2048 
2049  IRBuilder<> Builder(IP);
2050  Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
2051  NewInc = Builder.CreateTruncOrBitCast(
2052  OrigInc, IsomorphicInc->getType(), IVName);
2053  }
2054  IsomorphicInc->replaceAllUsesWith(NewInc);
2055  DeadInsts.emplace_back(IsomorphicInc);
2056  }
2057  }
2058  }
2059  DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
2060  << *Phi << '\n');
2061  ++NumElim;
2062  Value *NewIV = OrigPhiRef;
2063  if (OrigPhiRef->getType() != Phi->getType()) {
2064  IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
2065  Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
2066  NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
2067  }
2068  Phi->replaceAllUsesWith(NewIV);
2069  DeadInsts.emplace_back(Phi);
2070  }
2071  return NumElim;
2072 }
2073 
2075  const Instruction *At, Loop *L) {
2077  getRelatedExistingExpansion(S, At, L);
2078  if (VO && VO.getValue().second == nullptr)
2079  return VO.getValue().first;
2080  return nullptr;
2081 }
2082 
2085  Loop *L) {
2086  using namespace llvm::PatternMatch;
2087 
2088  SmallVector<BasicBlock *, 4> ExitingBlocks;
2089  L->getExitingBlocks(ExitingBlocks);
2090 
2091  // Look for suitable value in simple conditions at the loop exits.
2092  for (BasicBlock *BB : ExitingBlocks) {
2093  ICmpInst::Predicate Pred;
2094  Instruction *LHS, *RHS;
2095  BasicBlock *TrueBB, *FalseBB;
2096 
2097  if (!match(BB->getTerminator(),
2098  m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
2099  TrueBB, FalseBB)))
2100  continue;
2101 
2102  if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
2103  return ScalarEvolution::ValueOffsetPair(LHS, nullptr);
2104 
2105  if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2106  return ScalarEvolution::ValueOffsetPair(RHS, nullptr);
2107  }
2108 
2109  // Use expand's logic which is used for reusing a previous Value in
2110  // ExprValueMap.
2111  ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
2112  if (VO.first)
2113  return VO;
2114 
2115  // There is potential to make this significantly smarter, but this simple
2116  // heuristic already gets some interesting cases.
2117 
2118  // Can not find suitable value.
2119  return None;
2120 }
2121 
2122 bool SCEVExpander::isHighCostExpansionHelper(
2123  const SCEV *S, Loop *L, const Instruction *At,
2124  SmallPtrSetImpl<const SCEV *> &Processed) {
2125 
2126  // If we can find an existing value for this scev available at the point "At"
2127  // then consider the expression cheap.
2128  if (At && getRelatedExistingExpansion(S, At, L))
2129  return false;
2130 
2131  // Zero/One operand expressions
2132  switch (S->getSCEVType()) {
2133  case scUnknown:
2134  case scConstant:
2135  return false;
2136  case scTruncate:
2137  return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
2138  L, At, Processed);
2139  case scZeroExtend:
2140  return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
2141  L, At, Processed);
2142  case scSignExtend:
2143  return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
2144  L, At, Processed);
2145  }
2146 
2147  if (!Processed.insert(S).second)
2148  return false;
2149 
2150  if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
2151  // If the divisor is a power of two and the SCEV type fits in a native
2152  // integer (and the LHS not expensive), consider the division cheap
2153  // irrespective of whether it occurs in the user code since it can be
2154  // lowered into a right shift.
2155  if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
2156  if (SC->getAPInt().isPowerOf2()) {
2157  if (isHighCostExpansionHelper(UDivExpr->getLHS(), L, At, Processed))
2158  return true;
2159  const DataLayout &DL =
2161  unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
2162  return DL.isIllegalInteger(Width);
2163  }
2164 
2165  // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2166  // HowManyLessThans produced to compute a precise expression, rather than a
2167  // UDiv from the user's code. If we can't find a UDiv in the code with some
2168  // simple searching, assume the former consider UDivExpr expensive to
2169  // compute.
2170  BasicBlock *ExitingBB = L->getExitingBlock();
2171  if (!ExitingBB)
2172  return true;
2173 
2174  // At the beginning of this function we already tried to find existing value
2175  // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
2176  // involving division. This is just a simple search heuristic.
2177  if (!At)
2178  At = &ExitingBB->back();
2179  if (!getRelatedExistingExpansion(
2180  SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
2181  return true;
2182  }
2183 
2184  // HowManyLessThans uses a Max expression whenever the loop is not guarded by
2185  // the exit condition.
2186  if (isa<SCEVMinMaxExpr>(S))
2187  return true;
2188 
2189  // Recurse past nary expressions, which commonly occur in the
2190  // BackedgeTakenCount. They may already exist in program code, and if not,
2191  // they are not too expensive rematerialize.
2192  if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
2193  for (auto *Op : NAry->operands())
2194  if (isHighCostExpansionHelper(Op, L, At, Processed))
2195  return true;
2196  }
2197 
2198  // If we haven't recognized an expensive SCEV pattern, assume it's an
2199  // expression produced by program code.
2200  return false;
2201 }
2202 
2204  Instruction *IP) {
2205  assert(IP);
2206  switch (Pred->getKind()) {
2208  return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2210  return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
2211  case SCEVPredicate::P_Wrap: {
2212  auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2213  return expandWrapPredicate(AddRecPred, IP);
2214  }
2215  }
2216  llvm_unreachable("Unknown SCEV predicate type");
2217 }
2218 
2220  Instruction *IP) {
2221  Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2222  Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2223 
2224  Builder.SetInsertPoint(IP);
2225  auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2226  return I;
2227 }
2228 
2230  Instruction *Loc, bool Signed) {
2231  assert(AR->isAffine() && "Cannot generate RT check for "
2232  "non-affine expression");
2233 
2234  SCEVUnionPredicate Pred;
2235  const SCEV *ExitCount =
2236  SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
2237 
2238  assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2239 
2240  const SCEV *Step = AR->getStepRecurrence(SE);
2241  const SCEV *Start = AR->getStart();
2242 
2243  Type *ARTy = AR->getType();
2244  unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2245  unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2246 
2247  // The expression {Start,+,Step} has nusw/nssw if
2248  // Step < 0, Start - |Step| * Backedge <= Start
2249  // Step >= 0, Start + |Step| * Backedge > Start
2250  // and |Step| * Backedge doesn't unsigned overflow.
2251 
2252  IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2253  Builder.SetInsertPoint(Loc);
2254  Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2255 
2256  IntegerType *Ty =
2257  IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2258  Type *ARExpandTy = DL.isNonIntegralPointerType(ARTy) ? ARTy : Ty;
2259 
2260  Value *StepValue = expandCodeFor(Step, Ty, Loc);
2261  Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2262  Value *StartValue = expandCodeFor(Start, ARExpandTy, Loc);
2263 
2264  ConstantInt *Zero =
2266 
2267  Builder.SetInsertPoint(Loc);
2268  // Compute |Step|
2269  Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2270  Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2271 
2272  // Get the backedge taken count and truncate or extended to the AR type.
2273  Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2274  auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2275  Intrinsic::umul_with_overflow, Ty);
2276 
2277  // Compute |Step| * Backedge
2278  CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2279  Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2280  Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2281 
2282  // Compute:
2283  // Start + |Step| * Backedge < Start
2284  // Start - |Step| * Backedge > Start
2285  Value *Add = nullptr, *Sub = nullptr;
2286  if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARExpandTy)) {
2287  const SCEV *MulS = SE.getSCEV(MulV);
2288  const SCEV *NegMulS = SE.getNegativeSCEV(MulS);
2289  Add = Builder.CreateBitCast(expandAddToGEP(MulS, ARPtrTy, Ty, StartValue),
2290  ARPtrTy);
2291  Sub = Builder.CreateBitCast(
2292  expandAddToGEP(NegMulS, ARPtrTy, Ty, StartValue), ARPtrTy);
2293  } else {
2294  Add = Builder.CreateAdd(StartValue, MulV);
2295  Sub = Builder.CreateSub(StartValue, MulV);
2296  }
2297 
2298  Value *EndCompareGT = Builder.CreateICmp(
2299  Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2300 
2301  Value *EndCompareLT = Builder.CreateICmp(
2302  Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2303 
2304  // Select the answer based on the sign of Step.
2305  Value *EndCheck =
2306  Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2307 
2308  // If the backedge taken count type is larger than the AR type,
2309  // check that we don't drop any bits by truncating it. If we are
2310  // dropping bits, then we have overflow (unless the step is zero).
2311  if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2312  auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2313  auto *BackedgeCheck =
2314  Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2315  ConstantInt::get(Loc->getContext(), MaxVal));
2316  BackedgeCheck = Builder.CreateAnd(
2317  BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2318 
2319  EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2320  }
2321 
2322  EndCheck = Builder.CreateOr(EndCheck, OfMul);
2323  return EndCheck;
2324 }
2325 
2327  Instruction *IP) {
2328  const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2329  Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2330 
2331  // Add a check for NUSW
2333  NUSWCheck = generateOverflowCheck(A, IP, false);
2334 
2335  // Add a check for NSSW
2337  NSSWCheck = generateOverflowCheck(A, IP, true);
2338 
2339  if (NUSWCheck && NSSWCheck)
2340  return Builder.CreateOr(NUSWCheck, NSSWCheck);
2341 
2342  if (NUSWCheck)
2343  return NUSWCheck;
2344 
2345  if (NSSWCheck)
2346  return NSSWCheck;
2347 
2348  return ConstantInt::getFalse(IP->getContext());
2349 }
2350 
2352  Instruction *IP) {
2353  auto *BoolType = IntegerType::get(IP->getContext(), 1);
2354  Value *Check = ConstantInt::getNullValue(BoolType);
2355 
2356  // Loop over all checks in this set.
2357  for (auto Pred : Union->getPredicates()) {
2358  auto *NextCheck = expandCodeForPredicate(Pred, IP);
2359  Builder.SetInsertPoint(IP);
2360  Check = Builder.CreateOr(Check, NextCheck);
2361  }
2362 
2363  return Check;
2364 }
2365 
2366 namespace {
2367 // Search for a SCEV subexpression that is not safe to expand. Any expression
2368 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2369 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2370 // instruction, but the important thing is that we prove the denominator is
2371 // nonzero before expansion.
2372 //
2373 // IVUsers already checks that IV-derived expressions are safe. So this check is
2374 // only needed when the expression includes some subexpression that is not IV
2375 // derived.
2376 //
2377 // Currently, we only allow division by a nonzero constant here. If this is
2378 // inadequate, we could easily allow division by SCEVUnknown by using
2379 // ValueTracking to check isKnownNonZero().
2380 //
2381 // We cannot generally expand recurrences unless the step dominates the loop
2382 // header. The expander handles the special case of affine recurrences by
2383 // scaling the recurrence outside the loop, but this technique isn't generally
2384 // applicable. Expanding a nested recurrence outside a loop requires computing
2385 // binomial coefficients. This could be done, but the recurrence has to be in a
2386 // perfectly reduced form, which can't be guaranteed.
2387 struct SCEVFindUnsafe {
2388  ScalarEvolution &SE;
2389  bool IsUnsafe;
2390 
2391  SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
2392 
2393  bool follow(const SCEV *S) {
2394  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2395  const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2396  if (!SC || SC->getValue()->isZero()) {
2397  IsUnsafe = true;
2398  return false;
2399  }
2400  }
2401  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2402  const SCEV *Step = AR->getStepRecurrence(SE);
2403  if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2404  IsUnsafe = true;
2405  return false;
2406  }
2407  }
2408  return true;
2409  }
2410  bool isDone() const { return IsUnsafe; }
2411 };
2412 }
2413 
2414 namespace llvm {
2415 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2416  SCEVFindUnsafe Search(SE);
2417  visitAll(S, Search);
2418  return !Search.IsUnsafe;
2419 }
2420 
2421 bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint,
2422  ScalarEvolution &SE) {
2423  if (!isSafeToExpand(S, SE))
2424  return false;
2425  // We have to prove that the expanded site of S dominates InsertionPoint.
2426  // This is easy when not in the same block, but hard when S is an instruction
2427  // to be expanded somewhere inside the same block as our insertion point.
2428  // What we really need here is something analogous to an OrderedBasicBlock,
2429  // but for the moment, we paper over the problem by handling two common and
2430  // cheap to check cases.
2431  if (SE.properlyDominates(S, InsertionPoint->getParent()))
2432  return true;
2433  if (SE.dominates(S, InsertionPoint->getParent())) {
2434  if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2435  return true;
2436  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2437  for (const Value *V : InsertionPoint->operand_values())
2438  if (V == U->getValue())
2439  return true;
2440  }
2441  return false;
2442 }
2443 }
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static bool Check(DecodeStatus &Out, DecodeStatus In)
const NoneType None
Definition: None.h:23
uint64_t CallInst * C
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos)
Utility for hoisting an IV increment.
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:594
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:641
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:172
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:224
Value * getExactExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find existing LLVM IR value for S available at the point At.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
const SCEV * getConstant(ConstantInt *V)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1153
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:264
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are d...
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Normalize S to be post-increment for all loops present in Loops.
The main scalar evolution driver.
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:857
bool isZero() const
Return true if the expression is a constant zero.
This class represents a function call, abstracting a target machine&#39;s calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:173
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:629
unsigned less than
Definition: InstrTypes.h:757
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block...
Optional< ScalarEvolution::ValueOffsetPair > getRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find the ValueOffsetPair for S.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:720
This class represents a truncation of an integer value to a smaller integer value.
Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
A debug info location.
Definition: DebugLoc.h:33
const SCEV * getOperand() const
Hexagon Common GEP
static void SimplifyAddOperands(SmallVectorImpl< const SCEV *> &Ops, Type *Ty, ScalarEvolution &SE)
SimplifyAddOperands - Sort and simplify a list of add operands.
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:137
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
op_iterator op_begin()
Definition: User.h:229
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Definition: DataLayout.cpp:83
This is the base class for unary cast operator classes.
return AArch64::GPR64RegClass contains(Reg)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:274
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:562
Hexagon Hardware Loops
Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
Type * getPointerElementType() const
Definition: Type.h:375
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
static const Loop * PickMostRelevantLoop(const Loop *A, const Loop *B, DominatorTree &DT)
PickMostRelevantLoop - Given two loops pick the one that&#39;s most relevant for SCEV expansion...
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:439
Class to represent struct types.
Definition: DerivedTypes.h:232
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:41
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
LLVMContext & getContext() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
This node represents multiplication of some number of SCEVs.
Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
const APInt & getAPInt() const
BlockT * getHeader() const
Definition: LoopInfo.h:102
ConstantInt * getValue() const
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
#define UINT64_MAX
Definition: DataTypes.h:83
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool isTruncateFree(Type *Ty1, Type *Ty2) const
Return true if it&#39;s free to truncate a value of type Ty1 to type Ty2.
This node represents a polynomial recurrence on the trip count of the specified loop.
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:255
Class to represent array types.
Definition: DerivedTypes.h:400
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
op_iterator op_begin() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:150
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:384
This class represents a signed minimum selection.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1044
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
Definition: User.h:169
Class to represent pointers.
Definition: DerivedTypes.h:498
#define P(N)
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
const SCEV * getOperand(unsigned i) const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:216
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:318
SCEVPredicateKind getKind() const
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
This class represents a binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an unsigned minimum selection.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
const Instruction & front() const
Definition: BasicBlock.h:280
#define H(x, y, z)
Definition: MD5.cpp:57
const SCEV * getExpr() const override
Implementation of the SCEVPredicate interface.
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:572
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getLHS() const
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
op_iterator op_end()
Definition: User.h:231
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1199
const Instruction & back() const
Definition: BasicBlock.h:282
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder, const SCEV *Factor, ScalarEvolution &SE, const DataLayout &DL)
FactorOutConstant - Test if S is divisible by Factor, using signed division.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:526
self_iterator getIterator()
Definition: ilist_node.h:81
Class to represent integer types.
Definition: DerivedTypes.h:39
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
static Expected< BitVector > expand(StringRef S, StringRef Original)
Definition: GlobPattern.cpp:27
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
const SCEV * getLHS() const
Returns the left hand side of the equality.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:34
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1424
const SCEV * getRHS() const
Returns the right hand side of the equality.
size_t size() const
Definition: SmallVector.h:52
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static void SplitAddRecs(SmallVectorImpl< const SCEV *> &Ops, Type *Ty, ScalarEvolution &SE)
SplitAddRecs - Flatten a list of add operands, moving addrec start values out to the top level...
signed greater than
Definition: InstrTypes.h:759
This class represents an assumption made using SCEV expressions which can be checked at run-time...
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1122
static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest, ScalarEvolution &SE)
Move parts of Base into Rest to leave Base with the minimal expression that provides a pointer operan...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:239
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:112
unsigned getSCEVType() const
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
unsigned getNumOperands() const
Definition: User.h:191
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:215
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.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
PHINode * getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty)
This method returns the canonical induction variable of the specified type for the specified loop (in...
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:248
Module.h This file contains the declarations for the Module class.
signed less than
Definition: InstrTypes.h:761
uint64_t getSizeInBytes() const
Definition: DataLayout.h:570
CHAIN = SC CHAIN, Imm128 - System call.
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:631
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.cpp:645
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
unsigned logBase2() const
Definition: APInt.h:1747
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition: LoopInfo.cpp:146
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
This node represents an addition of some number of SCEVs.
static BasicBlock::iterator findInsertPointAfter(Instruction *I, BasicBlock *MustDominate)
bool isPowerOf2() const
Check if this APInt&#39;s value is a power of two greater than zero.
Definition: APInt.h:463
This class represents a signed maximum selection.
iterator_range< user_iterator > users()
Definition: Value.h:399
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:89
Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1539
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition: APInt.h:529
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
This class represents a zero extension of a small integer value to a larger integer value...
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1837
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
LoopT * getParentLoop() const
Definition: LoopInfo.h:103
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass&#39;s ...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:321
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:584
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:96
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:467
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:192
iterator_range< value_op_iterator > operand_values()
Definition: User.h:261
This class represents a sign extension of a small integer value to a larger integer value...
This class represents an unsigned maximum selection.
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
Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment&#39;s IV operand.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:324
const SCEV * getRHS() const
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
const SmallVectorImpl< const SCEVPredicate * > & getPredicates() const
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
DebugType
Definition: COFF.h:645
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents a composition of other SCEV predicates, and is the class that most clients will...
bool isOne() const
Return true if the expression is a constant one.
void stable_sort(R &&Range)
Definition: STLExtras.h:1316
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
Value * expandEqualPredicate(const SCEVEqualPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM Value Representation.
Definition: Value.h:72
A vector that has set insertion semantics.
Definition: SetVector.h:40
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:86
static Value * SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q)
See if we can fold the given phi. If not, returns null.
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block...
unsigned greater than
Definition: InstrTypes.h:755
This pass exposes codegen information to IR-level passes.
bool isIllegalInteger(uint64_t Width) const
Definition: DataLayout.h:261
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:568
This node is a base class providing common functionality for n&#39;ary operators.
This class represents an assumption made on an AddRec expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
This class represents an assumption that two SCEV expressions are equal, and this can be checked at r...
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
Type * getElementType() const
Definition: DerivedTypes.h:517
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:478
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const BasicBlock * getParent() const
Definition: Instruction.h:66
static bool canBeCheaplyTransformed(ScalarEvolution &SE, const SCEVAddRecExpr *Phi, const SCEVAddRecExpr *Requested, bool &InvertStep)
Check whether we can cheaply express the requested SCEV in terms of the available PHI SCEV by truncat...
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1815