LLVM 24.0.0git
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/ScopeExit.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Dominators.h"
32
33#if LLVM_ENABLE_ABI_BREAKING_CHECKS
34#define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
35#else
36#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
37#endif
38
39using namespace llvm;
40
42 "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
43 cl::desc("When performing SCEV expansion only if it is cheap to do, this "
44 "controls the budget that is considered cheap (default = 4)"));
45
46using namespace PatternMatch;
47using namespace SCEVPatternMatch;
48
50 NUW = false;
51 NSW = false;
52 Exact = false;
53 Disjoint = false;
54 NNeg = false;
55 SameSign = false;
57 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
58 NUW = OBO->hasNoUnsignedWrap();
59 NSW = OBO->hasNoSignedWrap();
60 }
61 if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
62 Exact = PEO->isExact();
63 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
64 Disjoint = PDI->isDisjoint();
65 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
66 NNeg = PNI->hasNonNeg();
67 if (auto *TI = dyn_cast<TruncInst>(I)) {
68 NUW = TI->hasNoUnsignedWrap();
69 NSW = TI->hasNoSignedWrap();
70 }
72 GEPNW = GEP->getNoWrapFlags();
73 if (auto *ICmp = dyn_cast<ICmpInst>(I))
74 SameSign = ICmp->hasSameSign();
75}
76
79 I->setHasNoUnsignedWrap(NUW);
80 I->setHasNoSignedWrap(NSW);
81 }
83 I->setIsExact(Exact);
84 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
85 PDI->setIsDisjoint(Disjoint);
86 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
87 PNI->setNonNeg(NNeg);
88 if (isa<TruncInst>(I)) {
89 I->setHasNoUnsignedWrap(NUW);
90 I->setHasNoSignedWrap(NSW);
91 }
93 GEP->setNoWrapFlags(GEPNW);
94 if (auto *ICmp = dyn_cast<ICmpInst>(I))
95 ICmp->setSameSign(SameSign);
96}
97
98/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
99/// reusing an existing cast if a suitable one (= dominating IP) exists, or
100/// creating a new one.
101Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
104 // This function must be called with the builder having a valid insertion
105 // point. It doesn't need to be the actual IP where the uses of the returned
106 // cast will be added, but it must dominate such IP.
107 // We use this precondition to produce a cast that will dominate all its
108 // uses. In particular, this is crucial for the case where the builder's
109 // insertion point *is* the point where we were asked to put the cast.
110 // Since we don't know the builder's insertion point is actually
111 // where the uses will be added (only that it dominates it), we are
112 // not allowed to move it.
113 BasicBlock::iterator BIP = Builder.GetInsertPoint();
114
115 Value *Ret = nullptr;
116
117 if (!isa<Constant>(V)) {
118 // Check to see if there is already a cast!
119 for (User *U : V->users()) {
120 if (U->getType() != Ty)
121 continue;
123 if (!CI || CI->getOpcode() != Op)
124 continue;
125
126 // Found a suitable cast that is at IP or comes before IP. Use it. Note
127 // that the cast must also properly dominate the Builder's insertion
128 // point.
129 if (IP->getParent() == CI->getParent() && &*BIP != CI &&
130 (&*IP == CI || CI->comesBefore(&*IP))) {
131 Ret = CI;
132 break;
133 }
134 }
135 }
136
137 // Create a new cast.
138 if (!Ret) {
139 SCEVInsertPointGuard Guard(Builder, this);
140 Builder.SetInsertPoint(&*IP);
141 Ret = Builder.CreateCast(Op, V, Ty, V->getName());
142 }
143
144 // We assert at the end of the function since IP might point to an
145 // instruction with different dominance properties than a cast
146 // (an invoke for example) and not dominate BIP (but the cast does).
147 assert(!isa<Instruction>(Ret) ||
148 SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
149
150 return Ret;
151}
152
155 Instruction *MustDominate) const {
157 if (auto MaybeIP = I->getInsertionPointAfterDef()) {
158 IP = *MaybeIP;
159 } else {
160 assert(SE.DT.dominates(I, MustDominate) &&
161 "instruction must dominate the insertion point");
162 IP = MustDominate->getIterator();
163 }
164
165 // Adjust insert point to be after instructions inserted by the expander, so
166 // we can re-use already inserted instructions. Avoid skipping past the
167 // original \p MustDominate, in case it is an inserted instruction.
168 while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
169 ++IP;
170
171 return IP;
172}
173
175 SmallVector<Value *> WorkList;
176 SmallPtrSet<Value *, 8> DeletedValues;
178 while (!WorkList.empty()) {
179 Value *V = WorkList.pop_back_val();
180 if (DeletedValues.contains(V))
181 continue;
182 auto *I = dyn_cast<Instruction>(V);
183 if (!I || I == Root || !isInsertedInstruction(I) ||
185 continue;
186 append_range(WorkList, I->operands());
187 InsertedValues.erase(I);
188 InsertedPostIncValues.erase(I);
189 DeletedValues.insert(I);
190 I->eraseFromParent();
191 }
192}
193
195SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
196 // Cast the argument at the beginning of the entry block, after
197 // any bitcasts of other arguments.
198 if (Argument *A = dyn_cast<Argument>(V)) {
199 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
200 while ((isa<BitCastInst>(IP) &&
201 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
202 cast<BitCastInst>(IP)->getOperand(0) != A))
203 ++IP;
204 return IP;
205 }
206
207 // Cast the instruction immediately after the instruction.
209 return findInsertPointAfter(I, &*Builder.GetInsertPoint());
210
211 // Otherwise, this must be some kind of a constant,
212 // so let's plop this cast into the function's entry block.
214 "Expected the cast argument to be a global/constant");
215 return Builder.GetInsertBlock()
216 ->getParent()
217 ->getEntryBlock()
218 .getFirstInsertionPt();
219}
220
221/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
222/// which must be possible with a noop cast, doing what we can to share
223/// the casts.
224Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
225 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
226 assert((Op == Instruction::BitCast ||
227 Op == Instruction::PtrToInt ||
228 Op == Instruction::IntToPtr) &&
229 "InsertNoopCastOfTo cannot perform non-noop casts!");
230 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
231 "InsertNoopCastOfTo cannot change sizes!");
232
233 // inttoptr only works for integral pointers. For non-integral pointers, we
234 // can create a GEP on null with the integral value as index. Note that
235 // it is safe to use GEP of null instead of inttoptr here, because only
236 // expressions already based on a GEP of null should be converted to pointers
237 // during expansion.
238 if (Op == Instruction::IntToPtr) {
239 auto *PtrTy = cast<PointerType>(Ty);
240 if (DL.isNonIntegralPointerType(PtrTy))
241 return Builder.CreatePtrAdd(Constant::getNullValue(PtrTy), V, "scevgep");
242 }
243 // Short-circuit unnecessary bitcasts.
244 if (Op == Instruction::BitCast) {
245 if (V->getType() == Ty)
246 return V;
247 if (CastInst *CI = dyn_cast<CastInst>(V)) {
248 if (CI->getOperand(0)->getType() == Ty)
249 return CI->getOperand(0);
250 }
251 }
252 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
253 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
254 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
255 if (CastInst *CI = dyn_cast<CastInst>(V))
256 if ((CI->getOpcode() == Instruction::PtrToInt ||
257 CI->getOpcode() == Instruction::IntToPtr) &&
258 SE.getTypeSizeInBits(CI->getType()) ==
259 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
260 return CI->getOperand(0);
261 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
262 if ((CE->getOpcode() == Instruction::PtrToInt ||
263 CE->getOpcode() == Instruction::IntToPtr) &&
264 SE.getTypeSizeInBits(CE->getType()) ==
265 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
266 return CE->getOperand(0);
267 }
268
269 // Fold a cast of a constant.
270 if (Constant *C = dyn_cast<Constant>(V))
271 return ConstantExpr::getCast(Op, C, Ty);
272
273 // Try to reuse existing cast, or insert one.
274 return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
275}
276
277/// InsertBinop - Insert the specified binary operator, doing a small amount
278/// of work to avoid inserting an obviously redundant operation, and hoisting
279/// to an outer loop when the opportunity is there and it is safe.
280Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
281 Value *LHS, Value *RHS,
282 SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
283 // Fold a binop with constant operands.
284 if (Constant *CLHS = dyn_cast<Constant>(LHS))
285 if (Constant *CRHS = dyn_cast<Constant>(RHS))
286 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL))
287 return Res;
288
289 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
290 unsigned ScanLimit = 6;
291 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
292 // Scanning starts from the last instruction before the insertion point.
293 BasicBlock::iterator IP = Builder.GetInsertPoint();
294 if (IP != BlockBegin) {
295 --IP;
296 for (; ScanLimit; --IP, --ScanLimit) {
297 auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
298 // Ensure that no-wrap flags match.
300 if (I->hasNoSignedWrap() != any(Flags & SCEV::FlagNSW))
301 return true;
302 if (I->hasNoUnsignedWrap() != any(Flags & SCEV::FlagNUW))
303 return true;
304 }
305 // Conservatively, do not use any instruction which has any of exact
306 // flags installed.
307 if (isa<PossiblyExactOperator>(I) && I->isExact())
308 return true;
309 return false;
310 };
311 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
312 IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
313 return &*IP;
314 if (IP == BlockBegin) break;
315 }
316 }
317
318 // Save the original insertion point so we can restore it when we're done.
319 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
320 SCEVInsertPointGuard Guard(Builder, this);
321
322 if (IsSafeToHoist) {
323 // Move the insertion point out of as many loops as we can.
324 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
325 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
326 BasicBlock *Preheader = L->getLoopPreheader();
327 if (!Preheader) break;
328
329 // Ok, move up a level.
330 Builder.SetInsertPoint(Preheader->getTerminator());
331 }
332 }
333
334 // If we haven't found this binop, insert it.
335 Builder.SetCurrentDebugLocation(Loc);
336 bool IsNUW = any(Flags & SCEV::FlagNUW);
337 bool IsNSW = any(Flags & SCEV::FlagNSW);
338 // Don't use folder when expanding post-inc rewrites in LSRMode to preserve
339 // the rewrites.
340 if (LSRMode && !PostIncLoops.empty() &&
341 all_of(PostIncLoops, [&](const Loop *L) {
342 return !L->contains(Builder.GetInsertBlock());
343 })) {
344 auto *BO = BinaryOperator::Create(Opcode, LHS, RHS);
345 if (IsNUW)
346 BO->setHasNoUnsignedWrap();
347 if (IsNSW)
348 BO->setHasNoSignedWrap();
349 return Builder.Insert(BO);
350 }
351 return Builder.CreateNoWrapBinOp(Opcode, LHS, RHS, IsNUW, IsNSW);
352}
353
354/// expandAddToGEP - Expand an addition expression with a pointer type into
355/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
356/// BasicAliasAnalysis and other passes analyze the result. See the rules
357/// for getelementptr vs. inttoptr in
358/// http://llvm.org/docs/LangRef.html#pointeraliasing
359/// for details.
360///
361/// Design note: The correctness of using getelementptr here depends on
362/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
363/// they may introduce pointer arithmetic which may not be safely converted
364/// into getelementptr.
365///
366/// Design note: It might seem desirable for this function to be more
367/// loop-aware. If some of the indices are loop-invariant while others
368/// aren't, it might seem desirable to emit multiple GEPs, keeping the
369/// loop-invariant portions of the overall computation outside the loop.
370/// However, there are a few reasons this is not done here. Hoisting simple
371/// arithmetic is a low-level optimization that often isn't very
372/// important until late in the optimization process. In fact, passes
373/// like InstructionCombining will combine GEPs, even if it means
374/// pushing loop-invariant computation down into loops, so even if the
375/// GEPs were split here, the work would quickly be undone. The
376/// LoopStrengthReduction pass, which is usually run quite late (and
377/// after the last InstructionCombining pass), takes care of hoisting
378/// loop-invariant portions of expressions, after considering what
379/// can be folded using target addressing modes.
380///
381Value *SCEVExpander::expandAddToGEP(SCEVUse Offset, Value *V,
382 SCEV::NoWrapFlags Flags) {
384 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
385
386 Value *Idx = expand(Offset);
387 GEPNoWrapFlags NW = any(Flags & SCEV::FlagNUW)
389 : GEPNoWrapFlags::none();
390
391 // Fold a GEP with constant operands.
392 if (Constant *CLHS = dyn_cast<Constant>(V))
393 if (Constant *CRHS = dyn_cast<Constant>(Idx))
394 return Builder.CreatePtrAdd(CLHS, CRHS, "", NW);
395
396 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
397 unsigned ScanLimit = 6;
398 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
399 // Scanning starts from the last instruction before the insertion point.
400 BasicBlock::iterator IP = Builder.GetInsertPoint();
401 if (IP != BlockBegin) {
402 --IP;
403 for (; ScanLimit; --IP, --ScanLimit) {
404 if (auto *GEP = dyn_cast<GetElementPtrInst>(IP)) {
405 if (GEP->getPointerOperand() == V &&
406 GEP->getSourceElementType() == Builder.getInt8Ty() &&
407 GEP->getOperand(1) == Idx) {
408 rememberFlags(GEP);
409 GEP->setNoWrapFlags(GEP->getNoWrapFlags() & NW);
410 return &*IP;
411 }
412 }
413 if (IP == BlockBegin) break;
414 }
415 }
416
417 // Save the original insertion point so we can restore it when we're done.
418 SCEVInsertPointGuard Guard(Builder, this);
419
420 // Move the insertion point out of as many loops as we can.
421 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
422 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
423 BasicBlock *Preheader = L->getLoopPreheader();
424 if (!Preheader) break;
425
426 // Ok, move up a level.
427 Builder.SetInsertPoint(Preheader->getTerminator());
428 }
429
430 // Emit a GEP.
431 return Builder.CreatePtrAdd(V, Idx, "scevgep", NW);
432}
433
434/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
435/// SCEV expansion. If they are nested, this is the most nested. If they are
436/// neighboring, pick the later.
437static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
438 DominatorTree &DT) {
439 if (!A) return B;
440 if (!B) return A;
441 if (A->contains(B)) return B;
442 if (B->contains(A)) return A;
443 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
444 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
445 return A; // Arbitrarily break the tie.
446}
447
448/// getRelevantLoop - Get the most relevant loop associated with the given
449/// expression, according to PickMostRelevantLoop.
450const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
451 // Test whether we've already computed the most relevant loop for this SCEV.
452 auto Pair = RelevantLoops.try_emplace(S);
453 if (!Pair.second)
454 return Pair.first->second;
455
456 switch (S->getSCEVType()) {
457 case scConstant:
458 case scVScale:
459 return nullptr; // A constant has no relevant loops.
460 case scTruncate:
461 case scZeroExtend:
462 case scSignExtend:
463 case scPtrToAddr:
464 case scAddExpr:
465 case scMulExpr:
466 case scUDivExpr:
467 case scAddRecExpr:
468 case scUMaxExpr:
469 case scSMaxExpr:
470 case scUMinExpr:
471 case scSMinExpr:
473 const Loop *L = nullptr;
474 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
475 L = AR->getLoop();
476 for (const SCEV *Op : S->operands())
477 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
478 return RelevantLoops[S] = L;
479 }
480 case scUnknown: {
481 const SCEVUnknown *U = cast<SCEVUnknown>(S);
482 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
483 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
484 // A non-instruction has no relevant loops.
485 return nullptr;
486 }
488 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
489 }
490 llvm_unreachable("Unexpected SCEV type!");
491}
492
493namespace {
494
495/// LoopCompare - Compare loops by PickMostRelevantLoop.
496class LoopCompare {
497 DominatorTree &DT;
498public:
499 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
500
501 bool operator()(std::pair<const Loop *, SCEVUse> LHS,
502 std::pair<const Loop *, SCEVUse> RHS) const {
503 // Keep pointer operands sorted at the end.
504 if (LHS.second->getType()->isPointerTy() !=
505 RHS.second->getType()->isPointerTy())
506 return LHS.second->getType()->isPointerTy();
507
508 // Compare loops with PickMostRelevantLoop.
509 if (LHS.first != RHS.first)
510 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
511
512 // If one operand is a non-constant negative and the other is not,
513 // put the non-constant negative on the right so that a sub can
514 // be used instead of a negate and add.
515 if (LHS.second->isNonConstantNegative()) {
516 if (!RHS.second->isNonConstantNegative())
517 return false;
518 } else if (RHS.second->isNonConstantNegative())
519 return true;
520
521 // Otherwise they are equivalent according to this comparison.
522 return false;
523 }
524};
525
526}
527
528Value *SCEVExpander::visitAddExpr(SCEVUseT<const SCEVAddExpr *> S) {
529 // Recognize the canonical representation of an unsimplifed urem.
530 const SCEV *URemLHS = nullptr;
531 const SCEV *URemRHS = nullptr;
532 if (match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), SE))) {
533 Value *LHS = expand(URemLHS);
534 Value *RHS = expand(URemRHS);
535 return InsertBinop(Instruction::URem, LHS, RHS, SCEV::FlagNone,
536 /*IsSafeToHoist*/ false);
537 }
538
539 // -C + umax(C, X) --> usub.sat(X, C)
540 const SCEV *UMaxRHS = nullptr;
541 const SCEVConstant *C1, *C2;
543 m_scev_UMax(m_SCEVConstant(C2), m_SCEV(UMaxRHS)))) &&
544 C1->getAPInt() == -C2->getAPInt()) {
545 Value *LHS = expand(UMaxRHS);
546 Value *RHS = C2->getValue();
547 return Builder.CreateIntrinsic(Intrinsic::usub_sat, {S->getType()},
548 {LHS, RHS});
549 }
550
551 // Collect all the add operands in a loop, along with their associated loops.
552 // Iterate in reverse so that constants are emitted last, all else equal, and
553 // so that pointer operands are inserted first, which the code below relies on
554 // to form more involved GEPs.
556 for (SCEVUse Op : reverse(S->operands()))
557 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
558
559 // Sort by loop. Use a stable sort so that constants follow non-constants and
560 // pointer operands precede non-pointer operands.
561 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
562
563 // Emit instructions to add all the operands. Hoist as much as possible
564 // out of loops, and form meaningful getelementptrs where possible.
565 Value *Sum = nullptr;
566 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
567 const Loop *CurLoop = I->first;
568 SCEVUse Op = I->second;
569 if (!Sum) {
570 // This is the first operand. Just expand it.
571 Sum = expand(Op);
572 ++I;
573 continue;
574 }
575
576 assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
577 if (isa<PointerType>(Sum->getType())) {
578 // The running sum expression is a pointer. Try to form a getelementptr
579 // at this level with that as the base.
581 for (; I != E && I->first == CurLoop; ++I) {
582 // If the operand is SCEVUnknown and not instructions, peek through
583 // it, to enable more of it to be folded into the GEP.
584 SCEVUse X = I->second;
585 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
586 if (!isa<Instruction>(U->getValue()))
587 X = SE.getSCEV(U->getValue());
588 NewOps.push_back(X);
589 }
590 Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum, S.getNoWrapFlags());
591 } else if (Op->isNonConstantNegative()) {
592 // Instead of doing a negate and add, just do a subtract.
593 Value *W = expand(SE.getNegativeSCEV(Op));
594 Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagNone,
595 /*IsSafeToHoist*/ true);
596 ++I;
597 } else {
598 // A simple add.
599 Value *W = expand(Op);
600 // Canonicalize a constant to the RHS.
601 if (isa<Constant>(Sum))
602 std::swap(Sum, W);
603 Sum = InsertBinop(Instruction::Add, Sum, W, S.getNoWrapFlags(),
604 /*IsSafeToHoist*/ true);
605 ++I;
606 }
607 }
608
609 return Sum;
610}
611
612Value *SCEVExpander::visitMulExpr(SCEVUseT<const SCEVMulExpr *> S) {
613 Type *Ty = S->getType();
614
615 const SCEVConstant *C1, *C2;
616 const SCEV *Val;
617 // mul(PowerOf2C, (udiv X, PowerOf2C)) == (X >> C) << C
618 // -> X & (-1 << C)
620 m_scev_UDiv(m_SCEV(Val), m_SCEVConstant(C2)))) &&
621 C1 == C2 && C1->getAPInt().isPowerOf2()) {
622 Value *LHS = expand(Val);
623 unsigned ShAmtC = C1->getAPInt().logBase2();
624 unsigned BitWidth = Ty->getScalarSizeInBits();
625 APInt Mask(APInt::getBitsSetFrom(BitWidth, ShAmtC));
626 Value *Res = InsertBinop(Instruction::And, LHS, ConstantInt::get(Ty, Mask),
627 SCEV::FlagNone, /*IsSafeToHoist*/ true);
628 return Res;
629 }
630
631 // Collect all the mul operands in a loop, along with their associated loops.
632 // Iterate in reverse so that constants are emitted last, all else equal.
634 for (const SCEV *Op : reverse(S->operands()))
635 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
636
637 // Sort by loop. Use a stable sort so that constants follow non-constants.
638 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
639
640 // Emit instructions to mul all the operands. Hoist as much as possible
641 // out of loops.
642 Value *Prod = nullptr;
643 auto I = OpsAndLoops.begin();
644
645 // Expand the calculation of X pow N in the following manner:
646 // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
647 // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
648 const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() {
649 auto E = I;
650 // Calculate how many times the same operand from the same loop is included
651 // into this power.
652 uint64_t Exponent = 0;
653 const uint64_t MaxExponent = UINT64_MAX >> 1;
654 // No one sane will ever try to calculate such huge exponents, but if we
655 // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
656 // below when the power of 2 exceeds our Exponent, and we want it to be
657 // 1u << 31 at most to not deal with unsigned overflow.
658 while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
659 ++Exponent;
660 ++E;
661 }
662 assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
663
664 // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
665 // that are needed into the result.
666 Value *P = expand(I->second);
667 Value *Result = nullptr;
668 if (Exponent & 1)
669 Result = P;
670 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
671 P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagNone,
672 /*IsSafeToHoist*/ true);
673 if (Exponent & BinExp)
674 Result = Result
675 ? InsertBinop(Instruction::Mul, Result, P, SCEV::FlagNone,
676 /*IsSafeToHoist*/ true)
677 : P;
678 }
679
680 I = E;
681 assert(Result && "Nothing was expanded?");
682 return Result;
683 };
684
685 while (I != OpsAndLoops.end()) {
686 if (!Prod) {
687 // This is the first operand. Just expand it.
688 Prod = ExpandOpBinPowN();
689 } else if (I->second->isAllOnesValue()) {
690 // Instead of doing a multiply by negative one, just do a negate.
691 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
692 SCEV::FlagNone, /*IsSafeToHoist*/ true);
693 ++I;
694 } else {
695 // A simple mul.
696 Value *W = ExpandOpBinPowN();
697 // Canonicalize a constant to the RHS.
698 if (isa<Constant>(Prod)) std::swap(Prod, W);
699 const APInt *RHS;
700 if (match(W, m_Power2(RHS))) {
701 // Canonicalize Prod*(1<<C) to Prod<<C.
702 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
703 auto NWFlags = S.getNoWrapFlags();
704 // clear nsw flag if shl will produce poison value.
705 if (RHS->logBase2() == RHS->getBitWidth() - 1)
706 NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
707 Prod = InsertBinop(Instruction::Shl, Prod,
708 ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
709 /*IsSafeToHoist*/ true);
710 } else {
711 Prod = InsertBinop(Instruction::Mul, Prod, W, S.getNoWrapFlags(),
712 /*IsSafeToHoist*/ true);
713 }
714 }
715 }
716
717 return Prod;
718}
719
720Value *SCEVExpander::visitUDivExpr(SCEVUseT<const SCEVUDivExpr *> S) {
721 Value *LHS = expand(S->getLHS());
722 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
723 const APInt &RHS = SC->getAPInt();
724 if (RHS.isPowerOf2())
725 return InsertBinop(Instruction::LShr, LHS,
726 ConstantInt::get(SC->getType(), RHS.logBase2()),
727 SCEV::FlagNone, /*IsSafeToHoist*/ true);
728 }
729
730 const SCEV *RHSExpr = S->getRHS();
731 Value *RHS = expand(RHSExpr);
732 if (SafeUDivMode) {
733 bool GuaranteedNotPoison =
735 if (!GuaranteedNotPoison)
736 RHS = Builder.CreateFreeze(RHS);
737
738 // We need an umax if either RHSExpr is not known to be zero, or if it is
739 // not guaranteed to be non-poison. In the later case, the frozen poison may
740 // be 0.
741 if (!SE.isKnownNonZero(RHSExpr) || !GuaranteedNotPoison)
742 RHS = Builder.CreateIntrinsic(RHS->getType(), Intrinsic::umax,
743 {RHS, ConstantInt::get(RHS->getType(), 1)});
744 }
745 return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagNone,
746 /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
747}
748
749/// Determine if this is a well-behaved chain of instructions leading back to
750/// the PHI. If so, it may be reused by expanded expressions.
751bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
752 const Loop *L) {
753 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
754 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
755 return false;
756 // If any of the operands don't dominate the insert position, bail.
757 // Addrec operands are always loop-invariant, so this can only happen
758 // if there are instructions which haven't been hoisted.
759 if (L == IVIncInsertLoop) {
760 for (Use &Op : llvm::drop_begin(IncV->operands()))
761 if (Instruction *OInst = dyn_cast<Instruction>(Op))
762 if (!SE.DT.dominates(OInst, IVIncInsertPos))
763 return false;
764 }
765 // Advance to the next instruction.
766 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
767 if (!IncV)
768 return false;
769
770 if (IncV->mayHaveSideEffects())
771 return false;
772
773 if (IncV == PN)
774 return true;
775
776 return isNormalAddRecExprPHI(PN, IncV, L);
777}
778
779/// getIVIncOperand returns an induction variable increment's induction
780/// variable operand.
781///
782/// If allowScale is set, any type of GEP is allowed as long as the nonIV
783/// operands dominate InsertPos.
784///
785/// If allowScale is not set, ensure that a GEP increment conforms to one of the
786/// simple patterns generated by getAddRecExprPHILiterally and
787/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
789 Instruction *InsertPos,
790 bool allowScale) {
791 if (IncV == InsertPos)
792 return nullptr;
793
794 switch (IncV->getOpcode()) {
795 default:
796 return nullptr;
797 // Check for a simple Add/Sub or GEP of a loop invariant step.
798 case Instruction::Add:
799 case Instruction::Sub: {
801 if (!OInst || SE.DT.dominates(OInst, InsertPos))
802 return dyn_cast<Instruction>(IncV->getOperand(0));
803 return nullptr;
804 }
805 case Instruction::BitCast:
806 return dyn_cast<Instruction>(IncV->getOperand(0));
807 case Instruction::GetElementPtr:
808 for (Use &U : llvm::drop_begin(IncV->operands())) {
809 if (isa<Constant>(U))
810 continue;
811 if (Instruction *OInst = dyn_cast<Instruction>(U)) {
812 if (!SE.DT.dominates(OInst, InsertPos))
813 return nullptr;
814 }
815 if (allowScale) {
816 // allow any kind of GEP as long as it can be hoisted.
817 continue;
818 }
819 // GEPs produced by SCEVExpander use i8 element type.
820 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
821 return nullptr;
822 break;
823 }
824 return dyn_cast<Instruction>(IncV->getOperand(0));
825 }
826}
827
828/// If the insert point of the current builder or any of the builders on the
829/// stack of saved builders has 'I' as its insert point, update it to point to
830/// the instruction after 'I'. This is intended to be used when the instruction
831/// 'I' is being moved. If this fixup is not done and 'I' is moved to a
832/// different block, the inconsistent insert point (with a mismatched
833/// Instruction and Block) can lead to an instruction being inserted in a block
834/// other than its parent.
835void SCEVExpander::fixupInsertPoints(Instruction *I) {
837 BasicBlock::iterator NewInsertPt = std::next(It);
838 if (Builder.GetInsertPoint() == It)
839 Builder.SetInsertPoint(&*NewInsertPt);
840 for (auto *InsertPtGuard : InsertPointGuards)
841 if (InsertPtGuard->GetInsertPoint() == It)
842 InsertPtGuard->SetInsertPoint(NewInsertPt);
843}
844
845/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
846/// it available to other uses in this loop. Recursively hoist any operands,
847/// until we reach a value that dominates InsertPos.
849 bool RecomputePoisonFlags) {
850 auto FixupPoisonFlags = [this](Instruction *I) {
851 // Drop flags that are potentially inferred from old context and infer flags
852 // in new context.
853 rememberFlags(I);
854 I->dropPoisonGeneratingFlags();
855 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
856 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
857 auto *BO = cast<BinaryOperator>(I);
858 BO->setHasNoUnsignedWrap(
860 BO->setHasNoSignedWrap(
862 }
863 };
864
865 if (SE.DT.dominates(IncV, InsertPos)) {
866 if (RecomputePoisonFlags)
867 FixupPoisonFlags(IncV);
868 return true;
869 }
870
871 // InsertPos must itself dominate IncV so that IncV's new position satisfies
872 // its existing users.
873 if (isa<PHINode>(InsertPos) ||
874 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
875 return false;
876
877 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
878 return false;
879
880 // Check that the chain of IV operands leading back to Phi can be hoisted.
882 for(;;) {
883 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
884 if (!Oper)
885 return false;
886 // IncV is safe to hoist.
887 IVIncs.push_back(IncV);
888 IncV = Oper;
889 if (SE.DT.dominates(IncV, InsertPos))
890 break;
891 }
892 for (Instruction *I : llvm::reverse(IVIncs)) {
893 fixupInsertPoints(I);
894 I->moveBefore(InsertPos->getIterator());
895 if (RecomputePoisonFlags)
896 FixupPoisonFlags(I);
897 }
898 return true;
899}
900
902 PHINode *WidePhi,
903 Instruction *OrigInc,
904 Instruction *WideInc) {
905 return match(OrigInc, m_c_BinOp(m_Specific(OrigPhi), m_Value())) &&
906 match(WideInc, m_c_BinOp(m_Specific(WidePhi), m_Value())) &&
907 OrigInc->getOpcode() == WideInc->getOpcode();
908}
909
910/// Determine if this cyclic phi is in a form that would have been generated by
911/// LSR. We don't care if the phi was actually expanded in this pass, as long
912/// as it is in a low-cost form, for example, no implied multiplication. This
913/// should match any patterns generated by getAddRecExprPHILiterally and
914/// expandAddtoGEP.
915bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
916 const Loop *L) {
917 for(Instruction *IVOper = IncV;
918 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
919 /*allowScale=*/false));) {
920 if (IVOper == PN)
921 return true;
922 }
923 return false;
924}
925
926/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
927/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
928/// need to materialize IV increments elsewhere to handle difficult situations.
929Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
930 bool useSubtract) {
931 Value *IncV;
932 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
933 if (PN->getType()->isPointerTy()) {
934 // TODO: Change name to IVName.iv.next.
935 IncV = Builder.CreatePtrAdd(PN, StepV, "scevgep");
936 } else {
937 IncV = useSubtract ?
938 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
939 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
940 }
941 return IncV;
942}
943
944/// Check whether we can cheaply express the requested SCEV in terms of
945/// the available PHI SCEV by truncation and/or inversion of the step.
947 const SCEVAddRecExpr *Phi,
948 const SCEVAddRecExpr *Requested,
949 bool &InvertStep) {
950 // We can't transform to match a pointer PHI.
951 Type *PhiTy = Phi->getType();
952 Type *RequestedTy = Requested->getType();
953 if (PhiTy->isPointerTy() || RequestedTy->isPointerTy())
954 return false;
955
956 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
957 return false;
958
959 // Try truncate it if necessary.
960 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
961 if (!Phi)
962 return false;
963
964 // Check whether truncation will help.
965 if (Phi == Requested) {
966 InvertStep = false;
967 return true;
968 }
969
970 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
971 if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
972 InvertStep = true;
973 return true;
974 }
975
976 return false;
977}
978
979static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
980 if (!isa<IntegerType>(AR->getType()))
981 return false;
982
983 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
984 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
985 const SCEV *Step = AR->getStepRecurrence(SE);
986 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
987 SE.getSignExtendExpr(AR, WideTy));
988 const SCEV *ExtendAfterOp =
989 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
990 return ExtendAfterOp == OpAfterExtend;
991}
992
993static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
994 if (!isa<IntegerType>(AR->getType()))
995 return false;
996
997 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
998 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
999 const SCEV *Step = AR->getStepRecurrence(SE);
1000 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1001 SE.getZeroExtendExpr(AR, WideTy));
1002 const SCEV *ExtendAfterOp =
1003 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1004 return ExtendAfterOp == OpAfterExtend;
1005}
1006
1007/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1008/// the base addrec, which is the addrec without any non-loop-dominating
1009/// values, and return the PHI.
1010PHINode *
1011SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1012 const Loop *L, Type *&TruncTy,
1013 bool &InvertStep) {
1014 assert((!IVIncInsertLoop || IVIncInsertPos) &&
1015 "Uninitialized insert position");
1016
1017 // Reuse a previously-inserted PHI, if present.
1018 BasicBlock *LatchBlock = L->getLoopLatch();
1019 if (LatchBlock) {
1020 PHINode *AddRecPhiMatch = nullptr;
1021 Instruction *IncV = nullptr;
1022 TruncTy = nullptr;
1023 InvertStep = false;
1024
1025 // Only try partially matching scevs that need truncation and/or
1026 // step-inversion if we know this loop is outside the current loop.
1027 bool TryNonMatchingSCEV =
1028 IVIncInsertLoop &&
1029 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1030
1031 for (PHINode &PN : L->getHeader()->phis()) {
1032 if (!SE.isSCEVable(PN.getType()))
1033 continue;
1034
1035 // We should not look for a incomplete PHI. Getting SCEV for a incomplete
1036 // PHI has no meaning at all.
1037 if (!PN.isComplete()) {
1039 DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
1040 continue;
1041 }
1042
1043 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1044 if (!PhiSCEV)
1045 continue;
1046
1047 bool IsMatchingSCEV = PhiSCEV == Normalized;
1048 // We only handle truncation and inversion of phi recurrences for the
1049 // expanded expression if the expanded expression's loop dominates the
1050 // loop we insert to. Check now, so we can bail out early.
1051 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1052 continue;
1053
1054 // TODO: this possibly can be reworked to avoid this cast at all.
1055 Instruction *TempIncV =
1057 if (!TempIncV)
1058 continue;
1059
1060 // Check whether we can reuse this PHI node.
1061 if (LSRMode) {
1062 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1063 continue;
1064 } else {
1065 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1066 continue;
1067 }
1068
1069 // Stop if we have found an exact match SCEV.
1070 if (IsMatchingSCEV) {
1071 IncV = TempIncV;
1072 TruncTy = nullptr;
1073 InvertStep = false;
1074 AddRecPhiMatch = &PN;
1075 break;
1076 }
1077
1078 // Try whether the phi can be translated into the requested form
1079 // (truncated and/or offset by a constant).
1080 if ((!TruncTy || InvertStep) &&
1081 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1082 // Record the phi node. But don't stop we might find an exact match
1083 // later.
1084 AddRecPhiMatch = &PN;
1085 IncV = TempIncV;
1086 TruncTy = Normalized->getType();
1087 }
1088 }
1089
1090 if (AddRecPhiMatch) {
1091 // Ok, the add recurrence looks usable.
1092 // Remember this PHI, even in post-inc mode.
1093 InsertedValues.insert(AddRecPhiMatch);
1094 // Remember the increment.
1095 rememberInstruction(IncV);
1096 // Those values were not actually inserted but re-used.
1097 ReusedValues.insert(AddRecPhiMatch);
1098 ReusedValues.insert(IncV);
1099 return AddRecPhiMatch;
1100 }
1101 }
1102
1103 // Save the original insertion point so we can restore it when we're done.
1104 SCEVInsertPointGuard Guard(Builder, this);
1105
1106 // Another AddRec may need to be recursively expanded below. For example, if
1107 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1108 // loop. Remove this loop from the PostIncLoops set before expanding such
1109 // AddRecs. Otherwise, we cannot find a valid position for the step
1110 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1111 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1112 // so it's not worth implementing SmallPtrSet::swap.
1113 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1114 PostIncLoops.clear();
1115
1116 // Expand code for the start value into the loop preheader.
1117 assert(L->getLoopPreheader() &&
1118 "Can't expand add recurrences without a loop preheader!");
1119 Value *StartV =
1120 expand(Normalized->getStart(), L->getLoopPreheader()->getTerminator());
1121
1122 // StartV must have been be inserted into L's preheader to dominate the new
1123 // phi.
1124 assert(!isa<Instruction>(StartV) ||
1125 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1126 L->getHeader()));
1127
1128 // Expand code for the step value. Do this before creating the PHI so that PHI
1129 // reuse code doesn't see an incomplete PHI.
1130 const SCEV *Step = Normalized->getStepRecurrence(SE);
1131 Type *ExpandTy = Normalized->getType();
1132 // If the stride is negative, insert a sub instead of an add for the increment
1133 // (unless it's a constant, because subtracts of constants are canonicalized
1134 // to adds).
1135 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1136 if (useSubtract)
1137 Step = SE.getNegativeSCEV(Step);
1138 // Expand the step somewhere that dominates the loop header.
1139 Value *StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1140
1141 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1142 // we actually do emit an addition. It does not apply if we emit a
1143 // subtraction.
1144 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1145 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1146
1147 // Create the PHI.
1148 BasicBlock *Header = L->getHeader();
1149 Builder.SetInsertPoint(Header, Header->begin());
1150 PHINode *PN =
1151 Builder.CreatePHI(ExpandTy, pred_size(Header), Twine(IVName) + ".iv");
1152
1153 // Create the step instructions and populate the PHI.
1154 for (BasicBlock *Pred : predecessors(Header)) {
1155 // Add a start value.
1156 if (!L->contains(Pred)) {
1157 PN->addIncoming(StartV, Pred);
1158 continue;
1159 }
1160
1161 // Create a step value and add it to the PHI.
1162 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1163 // instructions at IVIncInsertPos.
1164 Instruction *InsertPos = L == IVIncInsertLoop ?
1165 IVIncInsertPos : Pred->getTerminator();
1166 Builder.SetInsertPoint(InsertPos);
1167 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1168
1170 if (IncrementIsNUW)
1171 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1172 if (IncrementIsNSW)
1173 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1174 }
1175 PN->addIncoming(IncV, Pred);
1176 }
1177
1178 // After expanding subexpressions, restore the PostIncLoops set so the caller
1179 // can ensure that IVIncrement dominates the current uses.
1180 PostIncLoops = SavedPostIncLoops;
1181
1182 // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
1183 // effective when we are able to use an IV inserted here, so record it.
1184 InsertedValues.insert(PN);
1185 InsertedIVs.push_back(PN);
1186 return PN;
1187}
1188
1189Value *
1190SCEVExpander::expandAddRecExprLiterally(SCEVUseT<const SCEVAddRecExpr *> S) {
1191 const Loop *L = S->getLoop();
1192
1193 // Determine a normalized form of this expression, which is the expression
1194 // before any post-inc adjustment is made.
1195 const SCEVAddRecExpr *Normalized = S;
1196 if (PostIncLoops.count(L)) {
1198 Loops.insert(L);
1199 Normalized = cast<SCEVAddRecExpr>(
1200 normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false));
1201 }
1202
1203 [[maybe_unused]] const SCEV *Start = Normalized->getStart();
1204 const SCEV *Step = Normalized->getStepRecurrence(SE);
1205 assert(SE.properlyDominates(Start, L->getHeader()) &&
1206 "Start does not properly dominate loop header");
1207 assert(SE.dominates(Step, L->getHeader()) && "Step not dominate loop header");
1208
1209 // In some cases, we decide to reuse an existing phi node but need to truncate
1210 // it and/or invert the step.
1211 Type *TruncTy = nullptr;
1212 bool InvertStep = false;
1213 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1214
1215 // Accommodate post-inc mode, if necessary.
1216 Value *Result;
1217 if (!PostIncLoops.count(L))
1218 Result = PN;
1219 else {
1220 // In PostInc mode, use the post-incremented value.
1221 BasicBlock *LatchBlock = L->getLoopLatch();
1222 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1223 Result = PN->getIncomingValueForBlock(LatchBlock);
1224
1225 // We might be introducing a new use of the post-inc IV that is not poison
1226 // safe, in which case we should drop poison generating flags. Only keep
1227 // those flags for which SCEV has proven that they always hold.
1228 if (isa<OverflowingBinaryOperator>(Result)) {
1229 auto *I = cast<Instruction>(Result);
1230 if (!S->hasNoUnsignedWrap())
1231 I->setHasNoUnsignedWrap(false);
1232 if (!S->hasNoSignedWrap())
1233 I->setHasNoSignedWrap(false);
1234 }
1235
1236 // For an expansion to use the postinc form, the client must call
1237 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1238 // or dominated by IVIncInsertPos.
1239 if (isa<Instruction>(Result) &&
1240 !SE.DT.dominates(cast<Instruction>(Result),
1241 &*Builder.GetInsertPoint())) {
1242 // The induction variable's postinc expansion does not dominate this use.
1243 // IVUsers tries to prevent this case, so it is rare. However, it can
1244 // happen when an IVUser outside the loop is not dominated by the latch
1245 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1246 // all cases. Consider a phi outside whose operand is replaced during
1247 // expansion with the value of the postinc user. Without fundamentally
1248 // changing the way postinc users are tracked, the only remedy is
1249 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1250 // but hopefully expandCodeFor handles that.
1251 bool useSubtract =
1252 !S->getType()->isPointerTy() && Step->isNonConstantNegative();
1253 if (useSubtract)
1254 Step = SE.getNegativeSCEV(Step);
1255 Value *StepV;
1256 {
1257 // Expand the step somewhere that dominates the loop header.
1258 SCEVInsertPointGuard Guard(Builder, this);
1259 StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1260 }
1261 Result = expandIVInc(PN, StepV, L, useSubtract);
1262 }
1263 }
1264
1265 // We have decided to reuse an induction variable of a dominating loop. Apply
1266 // truncation and/or inversion of the step.
1267 if (TruncTy) {
1268 if (TruncTy != Result->getType() || InvertStep)
1269 Result = fixupLCSSAFormFor(Result);
1270 // Truncate the result.
1271 if (TruncTy != Result->getType())
1272 Result = Builder.CreateTrunc(Result, TruncTy);
1273
1274 // Invert the result.
1275 if (InvertStep)
1276 Result = Builder.CreateSub(expand(Normalized->getStart()), Result);
1277 }
1278
1279 return Result;
1280}
1281
1282Value *SCEVExpander::tryToReuseLCSSAPhi(SCEVUseT<const SCEVAddRecExpr *> S) {
1283 Type *STy = S->getType();
1284 const Loop *L = S->getLoop();
1285 BasicBlock *EB = L->getExitBlock();
1286 if (!EB || !EB->getSinglePredecessor() ||
1287 !SE.DT.dominates(EB, Builder.GetInsertBlock()))
1288 return nullptr;
1289
1290 // Helper to check if the diff between S and ExitSCEV is simple enough to
1291 // allow reusing the LCSSA phi.
1292 auto CanReuse = [&](const SCEV *ExitSCEV) -> const SCEV * {
1293 if (isa<SCEVCouldNotCompute>(ExitSCEV))
1294 return nullptr;
1295 const SCEV *Diff = SE.getMinusSCEV(S, ExitSCEV);
1296 const SCEV *Op = Diff;
1301 return nullptr;
1302 return Diff;
1303 };
1304
1305 for (auto &PN : EB->phis()) {
1306 if (!SE.isSCEVable(PN.getType()))
1307 continue;
1308 auto *ExitSCEV = SE.getSCEV(&PN);
1309 if (!isa<SCEVAddRecExpr>(ExitSCEV))
1310 continue;
1311 Type *PhiTy = PN.getType();
1312 const SCEV *Diff = nullptr;
1313 if (STy->isIntegerTy() && PhiTy->isPointerTy() &&
1314 DL.getAddressType(PhiTy) == STy) {
1315 const SCEV *AddrSCEV = SE.getPtrToAddrExpr(ExitSCEV);
1316 Diff = CanReuse(AddrSCEV);
1317 } else if (STy == PhiTy) {
1318 Diff = CanReuse(ExitSCEV);
1319 }
1320 if (!Diff)
1321 continue;
1322
1323 assert(Diff->getType()->isIntegerTy() &&
1324 "difference must be of integer type");
1325 Value *DiffV = expand(Diff);
1326 Value *BaseV = fixupLCSSAFormFor(&PN);
1327 if (PhiTy->isPointerTy()) {
1328 if (STy->isPointerTy())
1329 return Builder.CreatePtrAdd(BaseV, DiffV);
1330 BaseV = Builder.CreatePtrToAddr(BaseV);
1331 }
1332 return Builder.CreateAdd(BaseV, DiffV);
1333 }
1334
1335 return nullptr;
1336}
1337
1338Value *SCEVExpander::visitAddRecExpr(SCEVUseT<const SCEVAddRecExpr *> S) {
1339 // In canonical mode we compute the addrec as an expression of a canonical IV
1340 // using evaluateAtIteration and expand the resulting SCEV expression. This
1341 // way we avoid introducing new IVs to carry on the computation of the addrec
1342 // throughout the loop.
1343 //
1344 // For nested addrecs evaluateAtIteration might need a canonical IV of a
1345 // type wider than the addrec itself. Emitting a canonical IV of the
1346 // proper type might produce non-legal types, for example expanding an i64
1347 // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
1348 // back to non-canonical mode for nested addrecs.
1349 if (!CanonicalMode || (S->getNumOperands() > 2))
1350 return expandAddRecExprLiterally(S);
1351
1352 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1353 const Loop *L = S->getLoop();
1354
1355 // First check for an existing canonical IV in a suitable type.
1356 PHINode *CanonicalIV = nullptr;
1357 if (PHINode *PN = L->getCanonicalInductionVariable())
1358 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1359 CanonicalIV = PN;
1360
1361 // Rewrite an AddRec in terms of the canonical induction variable, if
1362 // its type is more narrow.
1363 if (CanonicalIV &&
1364 SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
1365 !S->getType()->isPointerTy()) {
1366 SmallVector<SCEVUse, 4> NewOps(S->getNumOperands());
1367 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1368 NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType());
1369 Value *V = expand(
1370 SE.getAddRecExpr(NewOps, S->getLoop(), S.getNoWrapFlags(SCEV::FlagNW)));
1371 BasicBlock::iterator NewInsertPt =
1373 &*Builder.GetInsertPoint())
1374 : Builder.GetInsertPoint();
1375 V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
1376 return V;
1377 }
1378
1379 // If S is expanded outside the defining loop, check if there is a
1380 // matching LCSSA phi node for it.
1381 if (Value *V = tryToReuseLCSSAPhi(S))
1382 return V;
1383
1384 // {X,+,F} --> X + {0,+,F}
1385 if (!S->getStart()->isZero()) {
1386 if (isa<PointerType>(S->getType())) {
1387 Value *StartV = expand(SE.getPointerBase(S));
1388 return expandAddToGEP(SE.removePointerBase(S), StartV,
1390 }
1391
1392 SmallVector<SCEVUse, 4> NewOps(S->operands());
1393 NewOps[0] = SE.getConstant(Ty, 0);
1394 const SCEV *Rest =
1395 SE.getAddRecExpr(NewOps, L, S.getNoWrapFlags(SCEV::FlagNW));
1396
1397 // Just do a normal add. Pre-expand the operands to suppress folding.
1398 //
1399 // The LHS and RHS values are factored out of the expand call to make the
1400 // output independent of the argument evaluation order.
1401 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1402 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1403 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1404 }
1405
1406 // If we don't yet have a canonical IV, create one.
1407 if (!CanonicalIV) {
1408 // Create and insert the PHI node for the induction variable in the
1409 // specified loop.
1410 BasicBlock *Header = L->getHeader();
1411 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1412 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar");
1413 CanonicalIV->insertBefore(Header->begin());
1414 rememberInstruction(CanonicalIV);
1415
1416 SmallPtrSet<BasicBlock *, 4> PredSeen;
1417 Constant *One = ConstantInt::get(Ty, 1);
1418 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1419 BasicBlock *HP = *HPI;
1420 if (!PredSeen.insert(HP).second) {
1421 // There must be an incoming value for each predecessor, even the
1422 // duplicates!
1423 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1424 continue;
1425 }
1426
1427 if (L->contains(HP)) {
1428 // Insert a unit add instruction right before the terminator
1429 // corresponding to the back-edge.
1430 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1431 "indvar.next",
1432 HP->getTerminator()->getIterator());
1433 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1434 rememberInstruction(Add);
1435 CanonicalIV->addIncoming(Add, HP);
1436 } else {
1437 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1438 }
1439 }
1440 }
1441
1442 // {0,+,1} --> Insert a canonical induction variable into the loop!
1443 if (S->isAffine() && S->getOperand(1)->isOne()) {
1444 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1445 "IVs with types different from the canonical IV should "
1446 "already have been handled!");
1447 return CanonicalIV;
1448 }
1449
1450 // {0,+,F} --> {0,+,1} * F
1451
1452 // If this is a simple linear addrec, emit it now as a special case.
1453 if (S->isAffine()) // {0,+,F} --> i*F
1454 return
1455 expand(SE.getTruncateOrNoop(
1456 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1457 SE.getNoopOrAnyExtend(S->getOperand(1),
1458 CanonicalIV->getType())),
1459 Ty));
1460
1461 // If this is a chain of recurrences, turn it into a closed form, using the
1462 // folders, then expandCodeFor the closed form. This allows the folders to
1463 // simplify the expression without having to build a bunch of special code
1464 // into this folder.
1465 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1466
1467 // Promote S up to the canonical IV type, if the cast is foldable.
1468 const SCEV *NewS = S;
1469 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1470 if (isa<SCEVAddRecExpr>(Ext))
1471 NewS = Ext;
1472
1473 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1474
1475 // Truncate the result down to the original type, if needed.
1476 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1477 return expand(T);
1478}
1479
1480/// Return true if \p CI computes the same value as a `ptrtoaddr` of its
1481/// pointer operand to \p Ty.
1482static bool canReuseCastForPtrToAddr(const CastInst *CI, Type *Ty,
1483 const DataLayout &DL) {
1484 if (CI->getType() != Ty)
1485 return false;
1486 if (CI->getOpcode() == CastInst::PtrToAddr)
1487 return true;
1488 if (CI->getOpcode() != CastInst::PtrToInt)
1489 return false;
1490 unsigned AS = CI->getSrcTy()->getPointerAddressSpace();
1491 return DL.getPointerSizeInBits(AS) == DL.getIndexSizeInBits(AS);
1492}
1493
1495 Value *PtrOp, Type *Ty, const DataLayout &DL,
1496 function_ref<bool(const CastInst *)> Dominates) {
1497 // Constants have no use list to scan.
1498 if (isa<Constant>(PtrOp))
1499 return nullptr;
1500 for (User *U : PtrOp->users()) {
1501 auto *CI = dyn_cast<CastInst>(U);
1502 if (!CI || !canReuseCastForPtrToAddr(CI, Ty, DL))
1503 continue;
1504 if (Dominates(CI))
1505 return CI;
1506 }
1507 return nullptr;
1508}
1509
1510Value *SCEVExpander::visitPtrToAddrExpr(SCEVUseT<const SCEVPtrToAddrExpr *> S) {
1511 Value *V = expand(S->getOperand());
1512 Type *Ty = S->getType();
1513
1514 // ptrtoaddr and ptrtoint can produce the same value, so try to reuse either.
1515 BasicBlock::iterator BIP = Builder.GetInsertPoint();
1516 if (CastInst *CI =
1517 findReusableCastForPtrToAddr(V, Ty, DL, [&](const CastInst *CI) {
1518 return &*BIP != CI && SE.DT.dominates(CI, &*BIP);
1519 }))
1520 return CI;
1521
1522 return ReuseOrCreateCast(V, Ty, CastInst::PtrToAddr,
1523 GetOptimalInsertionPointForCastOf(V));
1524}
1525
1526Value *SCEVExpander::visitTruncateExpr(SCEVUseT<const SCEVTruncateExpr *> S) {
1527 Type *Ty = S->getType();
1528
1529 // When truncating a ptrtoaddr, check for existing ptrtoint instructions that
1530 // convert directly to the target type, to avoid generating redundant
1531 // ptrtoaddr + trunc sequences.
1532 if (auto *PtrToAddr = dyn_cast<SCEVPtrToAddrExpr>(S->getOperand())) {
1533 Value *PtrOp = expand(PtrToAddr->getOperand());
1534 if (!isa<Constant>(PtrOp)) {
1535 BasicBlock::iterator BIP = Builder.GetInsertPoint();
1536 for (User *U : PtrOp->users()) {
1537 auto *CI = dyn_cast<CastInst>(U);
1538 if (CI && CI->getType() == Ty &&
1539 CI->getOpcode() == CastInst::PtrToInt && &*BIP != CI &&
1540 SE.DT.dominates(CI, &*BIP))
1541 return CI;
1542 }
1543 }
1544 }
1545
1546 Value *V = expand(S->getOperand());
1547 return Builder.CreateTrunc(V, S->getType());
1548}
1549
1550Value *
1551SCEVExpander::visitZeroExtendExpr(SCEVUseT<const SCEVZeroExtendExpr *> S) {
1552 Value *V = expand(S->getOperand());
1553 return Builder.CreateZExt(V, S->getType(), "",
1554 SE.isKnownNonNegative(S->getOperand()));
1555}
1556
1557Value *
1558SCEVExpander::visitSignExtendExpr(SCEVUseT<const SCEVSignExtendExpr *> S) {
1559 Value *V = expand(S->getOperand());
1560 return Builder.CreateSExt(V, S->getType());
1561}
1562
1563Value *SCEVExpander::expandMinMaxExpr(SCEVUseT<const SCEVNAryExpr *> S,
1564 Intrinsic::ID IntrinID, Twine Name,
1565 bool IsSequential) {
1566 bool PrevSafeMode = SafeUDivMode;
1567 SafeUDivMode |= IsSequential;
1568 Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1569 Type *Ty = LHS->getType();
1570 if (IsSequential)
1571 LHS = Builder.CreateFreeze(LHS);
1572 for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1573 SafeUDivMode = (IsSequential && i != 0) || PrevSafeMode;
1574 Value *RHS = expand(S->getOperand(i));
1575 if (IsSequential && i != 0)
1576 RHS = Builder.CreateFreeze(RHS);
1577 Value *Sel;
1578 if (Ty->isIntegerTy())
1579 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
1580 /*FMFSource=*/nullptr, Name);
1581 else {
1582 Value *ICmp =
1583 Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
1584 Sel = Builder.CreateSelectWithUnknownProfile(ICmp, LHS, RHS,
1585 "scev-expander", Name);
1586 }
1587 LHS = Sel;
1588 }
1589 SafeUDivMode = PrevSafeMode;
1590 return LHS;
1591}
1592
1593Value *SCEVExpander::visitSMaxExpr(SCEVUseT<const SCEVSMaxExpr *> S) {
1594 return expandMinMaxExpr(S, Intrinsic::smax, "smax");
1595}
1596
1597Value *SCEVExpander::visitUMaxExpr(SCEVUseT<const SCEVUMaxExpr *> S) {
1598 return expandMinMaxExpr(S, Intrinsic::umax, "umax");
1599}
1600
1601Value *SCEVExpander::visitSMinExpr(SCEVUseT<const SCEVSMinExpr *> S) {
1602 return expandMinMaxExpr(S, Intrinsic::smin, "smin");
1603}
1604
1605Value *SCEVExpander::visitUMinExpr(SCEVUseT<const SCEVUMinExpr *> S) {
1606 return expandMinMaxExpr(S, Intrinsic::umin, "umin");
1607}
1608
1609Value *SCEVExpander::visitSequentialUMinExpr(
1611 return expandMinMaxExpr(S, Intrinsic::umin, "umin",
1612 /*IsSequential*/ true);
1613}
1614
1615Value *SCEVExpander::visitVScale(SCEVUseT<const SCEVVScale *> S) {
1616 return Builder.CreateVScale(S->getType());
1617}
1618
1621 setInsertPoint(IP);
1622 return expandCodeFor(SH, Ty);
1623}
1624
1626 // Expand the code for this SCEV.
1627 Value *V = expand(SH);
1628
1629 if (Ty && Ty != V->getType()) {
1630 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1631 "non-trivial casts should be done with the SCEVs directly!");
1632 V = InsertNoopCastOfTo(V, Ty);
1633 }
1634 return V;
1635}
1636
1637Value *SCEVExpander::FindValueInExprValueMap(
1638 SCEVUse S, const Instruction *InsertPt,
1639 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
1640 // If the expansion is not in CanonicalMode, and the SCEV contains any
1641 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1642 if (!CanonicalMode && SE.containsAddRecurrence(S))
1643 return nullptr;
1644
1645 // If S is a constant or unknown, it may be worse to reuse an existing Value.
1647 return nullptr;
1648
1649 for (Value *V : SE.getSCEVValues(S)) {
1650 Instruction *EntInst = dyn_cast<Instruction>(V);
1651 if (!EntInst)
1652 continue;
1653
1654 // Choose a Value from the set which dominates the InsertPt.
1655 // InsertPt should be inside the Value's parent loop so as not to break
1656 // the LCSSA form.
1657 assert(EntInst->getFunction() == InsertPt->getFunction());
1658 if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) ||
1659 !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1660 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1661 continue;
1662
1663 // Make sure reusing the instruction is poison-safe.
1664 if (SE.canReuseInstruction(S, EntInst, DropPoisonGeneratingInsts))
1665 return V;
1666 DropPoisonGeneratingInsts.clear();
1667 }
1668 return nullptr;
1669}
1670
1671Value *SCEVExpander::findExistingExpansionAndDropPoisonFlags(
1672 SCEVUse S, const Instruction *InsertPt) {
1673 SmallVector<Instruction *> DropPoisonGeneratingInsts;
1674 Value *V = FindValueInExprValueMap(S, InsertPt, DropPoisonGeneratingInsts);
1675 if (!V)
1676 return nullptr;
1677 for (Instruction *I : DropPoisonGeneratingInsts) {
1678 rememberFlags(I);
1680 }
1681 return V;
1682}
1683
1684// The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1685// or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1686// and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1687// literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1688// the expansion will try to reuse Value from ExprValueMap, and only when it
1689// fails, expand the SCEV literally.
1690Value *SCEVExpander::expand(SCEVUse S) {
1691 // Compute an insertion point for this SCEV object. Hoist the instructions
1692 // as far out in the loop nest as possible.
1693 BasicBlock::iterator OrigInsertPt = Builder.GetInsertPoint();
1694 BasicBlock::iterator InsertPt = OrigInsertPt;
1695
1696 // We can move insertion point only if there is no div or rem operations
1697 // otherwise we are risky to move it over the check for zero denominator.
1698 auto SafeToHoist = [](const SCEV *S) {
1699 return !SCEVExprContains(S, [](const SCEV *S) {
1700 if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1701 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1702 // Division by non-zero constants can be hoisted.
1703 return SC->getValue()->isZero();
1704 // All other divisions should not be moved as they may be
1705 // divisions by zero and should be kept within the
1706 // conditions of the surrounding loops that guard their
1707 // execution (see PR35406).
1708 return true;
1709 }
1710 return false;
1711 });
1712 };
1713 if (SafeToHoist(S)) {
1714 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1715 L = L->getParentLoop()) {
1716 if (SE.isLoopInvariant(S, L)) {
1717 if (!L) break;
1718 if (BasicBlock *Preheader = L->getLoopPreheader()) {
1719 InsertPt = Preheader->getTerminator()->getIterator();
1720 } else {
1721 // LSR sets the insertion point for AddRec start/step values to the
1722 // block start to simplify value reuse, even though it's an invalid
1723 // position. SCEVExpander must correct for this in all cases.
1724 InsertPt = L->getHeader()->getFirstInsertionPt();
1725 }
1726 } else {
1727 // If the SCEV is computable at this level, insert it into the header
1728 // after the PHIs (and after any other instructions that we've inserted
1729 // there) so that it is guaranteed to dominate any user inside the loop.
1730 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1731 InsertPt = L->getHeader()->getFirstInsertionPt();
1732
1733 while (InsertPt != Builder.GetInsertPoint() &&
1734 (isInsertedInstruction(&*InsertPt))) {
1735 InsertPt = std::next(InsertPt);
1736 }
1737 break;
1738 }
1739 }
1740 }
1741
1742 // Check to see if we already expanded this here.
1743 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1744 if (I != InsertedExpressions.end())
1745 return I->second;
1746
1747 SCEVInsertPointGuard Guard(Builder, this);
1748 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1749
1750 // Expand the expression into instructions.
1751 Value *V = findExistingExpansionAndDropPoisonFlags(S, &*InsertPt);
1752 BasicBlock::iterator CacheAt = InsertPt;
1753 if (!V && InsertPt != OrigInsertPt && PostIncLoops.empty()) {
1754 // Hoisting the insertion point can move it above a value that already
1755 // computes S. Such a value is still usable: it only has to dominate the
1756 // point we were asked to expand at, which is where the result is used.
1757 V = findExistingExpansionAndDropPoisonFlags(S, &*OrigInsertPt);
1758 if (V)
1759 CacheAt = OrigInsertPt;
1760 }
1761 if (!V) {
1762 V = visit(S);
1763 V = fixupLCSSAFormFor(V);
1764 }
1765 // Remember the expanded value for this SCEV at this location.
1766 //
1767 // This is independent of PostIncLoops. The mapped value simply materializes
1768 // the expression at this insertion point. If the mapped value happened to be
1769 // a postinc expansion, it could be reused by a non-postinc user, but only if
1770 // its insertion point was already at the head of the loop.
1771 InsertedExpressions[std::make_pair(S, &*CacheAt)] = V;
1772 return V;
1773}
1774
1775void SCEVExpander::rememberInstruction(Value *I) {
1776 auto DoInsert = [this](Value *V) {
1777 if (!PostIncLoops.empty())
1778 InsertedPostIncValues.insert(V);
1779 else
1780 InsertedValues.insert(V);
1781 };
1782 DoInsert(I);
1783}
1784
1785void SCEVExpander::rememberFlags(Instruction *I) {
1786 // If we already have flags for the instruction, keep the existing ones.
1787 OrigFlags.try_emplace(I, PoisonFlags(I));
1788}
1789
1792 I->dropPoisonGeneratingAnnotations();
1793 // See if we can re-infer from first principles any of the flags we just
1794 // dropped.
1795 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
1796 if (SE.isSCEVable(OBO->getType()))
1797 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1798 auto *BO = cast<BinaryOperator>(I);
1799 BO->setHasNoUnsignedWrap(
1801 BO->setHasNoSignedWrap(
1803 }
1804 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(I)) {
1805 auto *Src = NNI->getOperand(0);
1807 Constant::getNullValue(Src->getType()), I,
1808 SE.getDataLayout())
1809 .value_or(false))
1810 NNI->setNonNeg(true);
1811 }
1812}
1813
1814void SCEVExpander::replaceCongruentIVInc(
1815 PHINode *&Phi, PHINode *&OrigPhi, Loop *L, const DominatorTree *DT,
1817 BasicBlock *LatchBlock = L->getLoopLatch();
1818 if (!LatchBlock)
1819 return;
1820
1821 Instruction *OrigInc =
1822 dyn_cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1823 Instruction *IsomorphicInc =
1824 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1825 if (!OrigInc || !IsomorphicInc)
1826 return;
1827
1828 // If this phi has the same width but is more canonical, replace the
1829 // original with it. As part of the "more canonical" determination,
1830 // respect a prior decision to use an IV chain.
1831 if (OrigPhi->getType() == Phi->getType()) {
1832 bool Chained = ChainedPhis.contains(Phi);
1833 if (!(Chained || isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1834 (Chained || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1835 std::swap(OrigPhi, Phi);
1836 std::swap(OrigInc, IsomorphicInc);
1837 }
1838 }
1839
1840 // Replacing the congruent phi is sufficient because acyclic
1841 // redundancy elimination, CSE/GVN, should handle the
1842 // rest. However, once SCEV proves that a phi is congruent,
1843 // it's often the head of an IV user cycle that is isomorphic
1844 // with the original phi. It's worth eagerly cleaning up the
1845 // common case of a single IV increment so that DeleteDeadPHIs
1846 // can remove cycles that had postinc uses.
1847 // Because we may potentially introduce a new use of OrigIV that didn't
1848 // exist before at this point, its poison flags need readjustment.
1849 const SCEV *TruncExpr =
1850 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1851 if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) ||
1852 !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc))
1853 return;
1854
1855 bool BothHaveNUW = false;
1856 bool BothHaveNSW = false;
1857 auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1858 auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1859 if (OBOIncV && OBOIsomorphic) {
1860 BothHaveNUW =
1861 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1862 BothHaveNSW =
1863 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1864 }
1865
1866 if (!hoistIVInc(OrigInc, IsomorphicInc,
1867 /*RecomputePoisonFlags*/ true))
1868 return;
1869
1870 // We are replacing with a wider increment. If both OrigInc and IsomorphicInc
1871 // are NUW/NSW, then we can preserve them on the wider increment; the narrower
1872 // IsomorphicInc would wrap before the wider OrigInc, so the replacement won't
1873 // make IsomorphicInc's uses more poisonous.
1874 assert(OrigInc->getType()->getScalarSizeInBits() >=
1875 IsomorphicInc->getType()->getScalarSizeInBits() &&
1876 "Should only replace an increment with a wider one.");
1877 if (BothHaveNUW || BothHaveNSW) {
1878 OrigInc->setHasNoUnsignedWrap(OBOIncV->hasNoUnsignedWrap() || BothHaveNUW);
1879 OrigInc->setHasNoSignedWrap(OBOIncV->hasNoSignedWrap() || BothHaveNSW);
1880 }
1881
1882 SCEV_DEBUG_WITH_TYPE(DebugType,
1883 dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1884 << *IsomorphicInc << '\n');
1885 Value *NewInc = OrigInc;
1886 if (OrigInc->getType() != IsomorphicInc->getType()) {
1888 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1889 IP = PN->getParent()->getFirstInsertionPt();
1890 else
1891 IP = OrigInc->getNextNode()->getIterator();
1892
1893 IRBuilder<> Builder(IP->getParent(), IP);
1894 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1895 NewInc =
1896 Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1897 }
1898 IsomorphicInc->replaceAllUsesWith(NewInc);
1899 DeadInsts.emplace_back(IsomorphicInc);
1900}
1901
1902/// replaceCongruentIVs - Check for congruent phis in this loop header and
1903/// replace them with their most canonical representative. Return the number of
1904/// phis eliminated.
1905///
1906/// This does not depend on any SCEVExpander state but should be used in
1907/// the same context that SCEVExpander is used.
1908unsigned
1911 const TargetTransformInfo *TTI) {
1912 // Find integer phis in order of increasing width.
1914 llvm::make_pointer_range(L->getHeader()->phis()));
1915
1916 if (TTI)
1917 // Use stable_sort to preserve order of equivalent PHIs, so the order
1918 // of the sorted Phis is the same from run to run on the same loop.
1919 llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
1920 // Put pointers at the back and make sure pointer < pointer = false.
1921 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1922 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1923 return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1924 LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
1925 });
1926
1927 unsigned NumElim = 0;
1929 // Process phis from wide to narrow. Map wide phis to their truncation
1930 // so narrow phis can reuse them.
1931 for (PHINode *Phi : Phis) {
1932 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1933 if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1934 return V;
1935 if (!SE.isSCEVable(PN->getType()))
1936 return nullptr;
1937 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1938 if (!Const)
1939 return nullptr;
1940 return Const->getValue();
1941 };
1942
1943 // Fold constant phis. They may be congruent to other constant phis and
1944 // would confuse the logic below that expects proper IVs.
1945 if (Value *V = SimplifyPHINode(Phi)) {
1946 if (V->getType() != Phi->getType())
1947 continue;
1948 SE.forgetValue(Phi);
1949 Phi->replaceAllUsesWith(V);
1950 DeadInsts.emplace_back(Phi);
1951 ++NumElim;
1952 SCEV_DEBUG_WITH_TYPE(DebugType,
1953 dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
1954 << '\n');
1955 continue;
1956 }
1957
1958 if (!SE.isSCEVable(Phi->getType()))
1959 continue;
1960
1961 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1962 if (!OrigPhiRef) {
1963 OrigPhiRef = Phi;
1964 if (Phi->getType()->isIntegerTy() && TTI &&
1965 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1966 // Make sure we only rewrite using simple induction variables;
1967 // otherwise, we can make the trip count of a loop unanalyzable
1968 // to SCEV.
1969 const SCEV *PhiExpr = SE.getSCEV(Phi);
1970 if (isa<SCEVAddRecExpr>(PhiExpr)) {
1971 // This phi can be freely truncated to the narrowest phi type. Map the
1972 // truncated expression to it so it will be reused for narrow types.
1973 const SCEV *TruncExpr =
1974 SE.getTruncateExpr(PhiExpr, Phis.back()->getType());
1975 ExprToIVMap[TruncExpr] = Phi;
1976 }
1977 }
1978 continue;
1979 }
1980
1981 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1982 // sense.
1983 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1984 continue;
1985
1986 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1987 SCEV_DEBUG_WITH_TYPE(DebugType,
1988 dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
1989 << '\n');
1991 DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
1992 ++NumElim;
1993 Value *NewIV = OrigPhiRef;
1994 if (OrigPhiRef->getType() != Phi->getType()) {
1995 IRBuilder<> Builder(L->getHeader(),
1996 L->getHeader()->getFirstInsertionPt());
1997 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1998 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1999 }
2000 Phi->replaceAllUsesWith(NewIV);
2001 DeadInsts.emplace_back(Phi);
2002 }
2003 return NumElim;
2004}
2005
2007 const Instruction *At,
2008 Loop *L) {
2009 using namespace llvm::PatternMatch;
2010
2011 SmallVector<BasicBlock *, 4> ExitingBlocks;
2012 L->getExitingBlocks(ExitingBlocks);
2013
2014 // Look for suitable value in simple conditions at the loop exits.
2015 for (BasicBlock *BB : ExitingBlocks) {
2016 CmpPredicate Pred;
2017 Instruction *LHS, *RHS;
2018
2019 if (!match(BB->getTerminator(),
2020 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
2022 continue;
2023
2024 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
2025 return true;
2026
2027 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2028 return true;
2029 }
2030
2031 // Use expand's logic which is used for reusing a previous Value in
2032 // ExprValueMap. Note that we don't currently model the cost of
2033 // needing to drop poison generating flags on the instruction if we
2034 // want to reuse it. We effectively assume that has zero cost.
2035 SmallVector<Instruction *> DropPoisonGeneratingInsts;
2036 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr;
2037}
2038
2039template<typename T> static InstructionCost costAndCollectOperands(
2042 SmallVectorImpl<SCEVOperand> &Worklist) {
2043
2044 const T *S = cast<T>(WorkItem.S);
2045 InstructionCost Cost = 0;
2046 // Object to help map SCEV operands to expanded IR instructions.
2047 struct OperationIndices {
2048 OperationIndices(unsigned Opc, size_t min, size_t max) :
2049 Opcode(Opc), MinIdx(min), MaxIdx(max) { }
2050 unsigned Opcode;
2051 size_t MinIdx;
2052 size_t MaxIdx;
2053 };
2054
2055 // Collect the operations of all the instructions that will be needed to
2056 // expand the SCEVExpr. This is so that when we come to cost the operands,
2057 // we know what the generated user(s) will be.
2059
2060 auto CastCost = [&](unsigned Opcode) -> InstructionCost {
2061 Operations.emplace_back(Opcode, 0, 0);
2062 return TTI.getCastInstrCost(Opcode, S->getType(),
2063 S->getOperand(0)->getType(),
2065 };
2066
2067 auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
2068 unsigned MinIdx = 0,
2069 unsigned MaxIdx = 1) -> InstructionCost {
2070 Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2071 return NumRequired *
2072 TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
2073 };
2074
2075 auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
2076 unsigned MaxIdx) -> InstructionCost {
2077 Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2078 Type *OpType = S->getType();
2079 return NumRequired * TTI.getCmpSelInstrCost(
2080 Opcode, OpType, CmpInst::makeCmpResultType(OpType),
2082 };
2083
2084 switch (S->getSCEVType()) {
2085 case scCouldNotCompute:
2086 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2087 case scUnknown:
2088 case scConstant:
2089 case scVScale:
2090 return 0;
2091 case scPtrToAddr:
2092 Cost = CastCost(Instruction::PtrToAddr);
2093 break;
2094 case scTruncate:
2095 Cost = CastCost(Instruction::Trunc);
2096 break;
2097 case scZeroExtend:
2098 Cost = CastCost(Instruction::ZExt);
2099 break;
2100 case scSignExtend:
2101 Cost = CastCost(Instruction::SExt);
2102 break;
2103 case scUDivExpr: {
2104 unsigned Opcode = Instruction::UDiv;
2105 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
2106 if (SC->getAPInt().isPowerOf2())
2107 Opcode = Instruction::LShr;
2108 Cost = ArithCost(Opcode, 1);
2109 break;
2110 }
2111 case scAddExpr:
2112 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2113 break;
2114 case scMulExpr: {
2115 // Match the actual expansion in visitMulExpr: multiply by -1 is
2116 // expanded as a negate (sub 0, x), and multiply by a power of 2 is
2117 // expanded as a shift. Only handle the common two-operand case with a
2118 // constant LHS; for everything else fall back to the pessimistic
2119 // all-multiplies estimate.
2120 // TODO: this is still pessimistic for the general case because of the
2121 // Bin Pow algorithm actually used by the expander, see
2122 // SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
2123 unsigned OpCode = Instruction::Mul;
2124 if (S->getNumOperands() == 2)
2125 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(0))) {
2126 if (SC->getAPInt().isAllOnes()) // -1
2127 OpCode = Instruction::Sub;
2128 else if (SC->getAPInt().isPowerOf2())
2129 OpCode = Instruction::Shl;
2130 }
2131 Cost = ArithCost(OpCode, S->getNumOperands() - 1);
2132 break;
2133 }
2134 case scSMaxExpr:
2135 case scUMaxExpr:
2136 case scSMinExpr:
2137 case scUMinExpr:
2138 case scSequentialUMinExpr: {
2139 // FIXME: should this ask the cost for Intrinsic's?
2140 // The reduction tree.
2141 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
2142 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
2143 switch (S->getSCEVType()) {
2144 case scSequentialUMinExpr: {
2145 // The safety net against poison.
2146 // FIXME: this is broken.
2147 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
2148 Cost += ArithCost(Instruction::Or,
2149 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
2150 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
2151 break;
2152 }
2153 default:
2155 "Unhandled SCEV expression type?");
2156 break;
2157 }
2158 break;
2159 }
2160 case scAddRecExpr: {
2161 // Addrec expands to a phi and add per recurrence.
2162 unsigned NumRecurrences = S->getNumOperands() - 1;
2163 Cost += TTI.getCFInstrCost(Instruction::PHI, CostKind) * NumRecurrences;
2164 Cost +=
2165 TTI.getArithmeticInstrCost(Instruction::Add, S->getType(), CostKind) *
2166 NumRecurrences;
2167 // AR start is used in phi.
2168 Worklist.emplace_back(Instruction::PHI, 0, S->getOperand(0));
2169 // Other operands are used in add.
2170 for (const SCEV *Op : S->operands().drop_front())
2171 Worklist.emplace_back(Instruction::Add, 1, Op);
2172 break;
2173 }
2174 }
2175
2176 for (auto &CostOp : Operations) {
2177 for (auto SCEVOp : enumerate(S->operands())) {
2178 // Clamp the index to account for multiple IR operations being chained.
2179 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2180 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2181 Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
2182 }
2183 }
2184 return Cost;
2185}
2186
2187bool SCEVExpander::isHighCostExpansionHelper(
2188 const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
2189 InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
2191 SmallVectorImpl<SCEVOperand> &Worklist) {
2192 if (Cost > Budget)
2193 return true; // Already run out of budget, give up.
2194
2195 const SCEV *S = WorkItem.S;
2196 // Was the cost of expansion of this expression already accounted for?
2197 if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
2198 return false; // We have already accounted for this expression.
2199
2200 // If we can find an existing value for this scev available at the point "At"
2201 // then consider the expression cheap.
2202 if (hasRelatedExistingExpansion(S, &At, L))
2203 return false; // Consider the expression to be free.
2204
2206 L->getHeader()->getParent()->hasMinSize()
2209
2210 switch (S->getSCEVType()) {
2211 case scCouldNotCompute:
2212 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2213 case scUnknown:
2214 case scVScale:
2215 // Assume to be zero-cost.
2216 return false;
2217 case scConstant: {
2218 // Only evalulate the costs of constants when optimizing for size.
2220 return false;
2221 const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
2222 Type *Ty = S->getType();
2224 WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
2225 return Cost > Budget;
2226 }
2227 case scTruncate:
2228 case scPtrToAddr:
2229 case scZeroExtend:
2230 case scSignExtend: {
2231 Cost +=
2233 return false; // Will answer upon next entry into this function.
2234 }
2235 case scUDivExpr: {
2236 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2237 // HowManyLessThans produced to compute a precise expression, rather than a
2238 // UDiv from the user's code. If we can't find a UDiv in the code with some
2239 // simple searching, we need to account for it's cost.
2240
2241 // At the beginning of this function we already tried to find existing
2242 // value for plain 'S'. Now try to lookup 'S + 1' since it is common
2243 // pattern involving division. This is just a simple search heuristic.
2245 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
2246 return false; // Consider it to be free.
2247
2248 Cost +=
2250 return false; // Will answer upon next entry into this function.
2251 }
2252 case scAddExpr:
2253 case scMulExpr:
2254 case scUMaxExpr:
2255 case scSMaxExpr:
2256 case scUMinExpr:
2257 case scSMinExpr:
2258 case scSequentialUMinExpr: {
2259 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2260 "Nary expr should have more than 1 operand.");
2261 // The simple nary expr will require one less op (or pair of ops)
2262 // than the number of it's terms.
2263 Cost +=
2265 return Cost > Budget;
2266 }
2267 case scAddRecExpr: {
2268 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2269 "Polynomial should be at least linear");
2271 WorkItem, TTI, CostKind, Worklist);
2272 return Cost > Budget;
2273 }
2274 }
2275 llvm_unreachable("Unknown SCEV kind!");
2276}
2277
2279 Instruction *IP) {
2280 assert(IP);
2281 switch (Pred->getKind()) {
2286 case SCEVPredicate::P_Wrap: {
2287 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2288 return expandWrapPredicate(AddRecPred, IP);
2289 }
2290 }
2291 llvm_unreachable("Unknown SCEV predicate type");
2292}
2293
2295 Instruction *IP) {
2296 Value *Expr0 = expand(Pred->getLHS(), IP);
2297 Value *Expr1 = expand(Pred->getRHS(), IP);
2298
2299 Builder.SetInsertPoint(IP);
2300 auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
2301 auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
2302 return I;
2303}
2304
2306 Instruction *Loc, bool Signed) {
2307 assert(AR->isAffine() && "Cannot generate RT check for "
2308 "non-affine expression");
2309
2310 // FIXME: It is highly suspicious that we're ignoring the predicates here.
2312 const SCEV *ExitCount =
2313 SE.getPredicatedSymbolicMaxBackedgeTakenCount(AR->getLoop(), Pred);
2314
2315 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
2316
2317 const SCEV *Step = AR->getStepRecurrence(SE);
2318 const SCEV *Start = AR->getStart();
2319
2320 Type *ARTy = AR->getType();
2321 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2322 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2323
2324 // The expression {Start,+,Step} has nusw/nssw if
2325 // Step < 0, Start - |Step| * Backedge <= Start
2326 // Step >= 0, Start + |Step| * Backedge > Start
2327 // and |Step| * Backedge doesn't unsigned overflow.
2328
2329 Builder.SetInsertPoint(Loc);
2330 Value *TripCountVal = expand(ExitCount, Loc);
2331
2332 IntegerType *Ty =
2333 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2334
2335 Value *StepValue = expand(Step, Loc);
2336 Value *NegStepValue = expand(SE.getNegativeSCEV(Step), Loc);
2337 Value *StartValue = expand(Start, Loc);
2338
2339 ConstantInt *Zero =
2340 ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
2341
2342 Builder.SetInsertPoint(Loc);
2343 // Compute |Step|
2344 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2345 Value *AbsStep = Builder.CreateSelectWithUnknownProfile(
2346 StepCompare, NegStepValue, StepValue, "scev-expander");
2347
2348 // Compute |Step| * Backedge
2349 // Compute:
2350 // 1. Start + |Step| * Backedge < Start
2351 // 2. Start - |Step| * Backedge > Start
2352 //
2353 // And select either 1. or 2. depending on whether step is positive or
2354 // negative. If Step is known to be positive or negative, only create
2355 // either 1. or 2.
2356 auto ComputeEndCheck = [&]() -> Value * {
2357 // Check to see if we already expanded this here.
2358 Value *MulV, *OfMul;
2359 auto Key = std::make_tuple(TripCountVal, AbsStep, Loc);
2360 auto I = InsertedOverflowChecks.find(Key);
2361 if (I != InsertedOverflowChecks.end()) {
2362 MulV = I->second.first;
2363 OfMul = I->second.second;
2364 } else {
2365 // Get the backedge taken count and truncate or extended to the AR type.
2366 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2367 Value *Mul = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, Ty,
2368 {AbsStep, TruncTripCount},
2369 /*FMFSource=*/nullptr, "mul");
2370 MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2371 OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2372
2373 // The type Ty is already encoded in AbsStep.
2374 InsertedOverflowChecks[Key] = std::pair<Value *, Value *>(MulV, OfMul);
2375 }
2376
2377 Value *Add = nullptr, *Sub = nullptr;
2378 bool NeedPosCheck = !SE.isKnownNegative(Step);
2379 bool NeedNegCheck = !SE.isKnownPositive(Step);
2380
2381 if (isa<PointerType>(ARTy)) {
2382 Value *NegMulV = Builder.CreateNeg(MulV);
2383 if (NeedPosCheck)
2384 Add = Builder.CreatePtrAdd(StartValue, MulV);
2385 if (NeedNegCheck)
2386 Sub = Builder.CreatePtrAdd(StartValue, NegMulV);
2387 } else {
2388 if (NeedPosCheck)
2389 Add = Builder.CreateAdd(StartValue, MulV);
2390 if (NeedNegCheck)
2391 Sub = Builder.CreateSub(StartValue, MulV);
2392 }
2393
2394 Value *EndCompareLT = nullptr;
2395 Value *EndCompareGT = nullptr;
2396 Value *EndCheck = nullptr;
2397 if (NeedPosCheck)
2398 EndCheck = EndCompareLT = Builder.CreateICmp(
2400 if (NeedNegCheck)
2401 EndCheck = EndCompareGT = Builder.CreateICmp(
2403 if (NeedPosCheck && NeedNegCheck) {
2404 // Select the answer based on the sign of Step.
2405 EndCheck = Builder.CreateSelectWithUnknownProfile(
2406 StepCompare, EndCompareGT, EndCompareLT, "scev-expander");
2407 }
2408 return Builder.CreateOr(EndCheck, OfMul);
2409 };
2410 Value *EndCheck = ComputeEndCheck();
2411
2412 // If the backedge taken count type is larger than the AR type,
2413 // check that we don't drop any bits by truncating it. If we are
2414 // dropping bits, then we have overflow (unless the step is zero).
2415 if (SrcBits > DstBits) {
2416 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2417 auto *BackedgeCheck =
2418 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2419 ConstantInt::get(Loc->getContext(), MaxVal));
2420 BackedgeCheck = Builder.CreateAnd(
2421 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2422
2423 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2424 }
2425
2426 return EndCheck;
2427}
2428
2430 Instruction *IP) {
2431 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2432 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2433
2434 // Add a check for NUSW
2435 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2436 NUSWCheck = generateOverflowCheck(A, IP, false);
2437
2438 // Add a check for NSSW
2439 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2440 NSSWCheck = generateOverflowCheck(A, IP, true);
2441
2442 if (NUSWCheck && NSSWCheck)
2443 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2444
2445 if (NUSWCheck)
2446 return NUSWCheck;
2447
2448 if (NSSWCheck)
2449 return NSSWCheck;
2450
2451 return ConstantInt::getFalse(IP->getContext());
2452}
2453
2455 Instruction *IP) {
2456 // Loop over all checks in this set.
2457 SmallVector<Value *> Checks;
2458 for (const auto *Pred : Union->getPredicates()) {
2459 Checks.push_back(expandCodeForPredicate(Pred, IP));
2460 Builder.SetInsertPoint(IP);
2461 }
2462
2463 if (Checks.empty())
2464 return ConstantInt::getFalse(IP->getContext());
2465 return Builder.CreateOr(Checks);
2466}
2467
2468Value *SCEVExpander::fixupLCSSAFormFor(Value *V) {
2469 auto *DefI = dyn_cast<Instruction>(V);
2470 if (!PreserveLCSSA || !DefI)
2471 return V;
2472
2473 BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
2474 Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent());
2475 Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent());
2476 if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2477 return V;
2478
2479 // Create a temporary instruction to at the current insertion point, so we
2480 // can hand it off to the helper to create LCSSA PHIs if required for the
2481 // new use.
2482 // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
2483 // would accept a insertion point and return an LCSSA phi for that
2484 // insertion point, so there is no need to insert & remove the temporary
2485 // instruction.
2486 Type *ToTy;
2487 if (DefI->getType()->isIntegerTy())
2488 ToTy = PointerType::get(DefI->getContext(), 0);
2489 else
2490 ToTy = Type::getInt32Ty(DefI->getContext());
2491 Instruction *User =
2492 CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt);
2493 llvm::scope_exit RemoveUserOnExit([User]() { User->eraseFromParent(); });
2494
2496 ToUpdate.push_back(DefI);
2497 SmallVector<PHINode *, 16> PHIsToRemove;
2498 SmallVector<PHINode *, 16> InsertedPHIs;
2499 formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove,
2500 &InsertedPHIs);
2501 for (PHINode *PN : InsertedPHIs)
2502 rememberInstruction(PN);
2503 for (PHINode *PN : PHIsToRemove) {
2504 if (!PN->use_empty())
2505 continue;
2506 InsertedValues.erase(PN);
2507 InsertedPostIncValues.erase(PN);
2508 PN->eraseFromParent();
2509 }
2510
2511 return User->getOperand(0);
2512}
2513
2514namespace {
2515// Search for a SCEV subexpression that is not safe to expand. Any expression
2516// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2517// UDiv expressions. We don't know if the UDiv is derived from an IR divide
2518// instruction, but the important thing is that we prove the denominator is
2519// nonzero before expansion.
2520//
2521// IVUsers already checks that IV-derived expressions are safe. So this check is
2522// only needed when the expression includes some subexpression that is not IV
2523// derived.
2524//
2525// Currently, we only allow division by a value provably non-zero here.
2526//
2527// We cannot generally expand recurrences unless the step dominates the loop
2528// header. The expander handles the special case of affine recurrences by
2529// scaling the recurrence outside the loop, but this technique isn't generally
2530// applicable. Expanding a nested recurrence outside a loop requires computing
2531// binomial coefficients. This could be done, but the recurrence has to be in a
2532// perfectly reduced form, which can't be guaranteed.
2533struct SCEVFindUnsafe {
2534 ScalarEvolution &SE;
2535 bool CanonicalMode;
2536 bool IsUnsafe = false;
2537
2538 SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
2539 : SE(SE), CanonicalMode(CanonicalMode) {}
2540
2541 bool follow(const SCEV *S) {
2542 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2543 if (!SE.isKnownNonZero(D->getRHS()) ||
2544 !SE.isGuaranteedNotToBePoison(D->getRHS())) {
2545 IsUnsafe = true;
2546 return false;
2547 }
2548 }
2549 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2550 // For non-affine addrecs or in non-canonical mode we need a preheader
2551 // to insert into.
2552 if (!AR->getLoop()->getLoopPreheader() &&
2553 (!CanonicalMode || !AR->isAffine())) {
2554 IsUnsafe = true;
2555 return false;
2556 }
2557 }
2558 return true;
2559 }
2560 bool isDone() const { return IsUnsafe; }
2561};
2562} // namespace
2563
2565 SCEVFindUnsafe Search(SE, CanonicalMode);
2566 visitAll(S, Search);
2567 return !Search.IsUnsafe;
2568}
2569
2571 const Instruction *InsertionPoint) const {
2572 if (!isSafeToExpand(S))
2573 return false;
2574 // We have to prove that the expanded site of S dominates InsertionPoint.
2575 // This is easy when not in the same block, but hard when S is an instruction
2576 // to be expanded somewhere inside the same block as our insertion point.
2577 // What we really need here is something analogous to an OrderedBasicBlock,
2578 // but for the moment, we paper over the problem by handling two common and
2579 // cheap to check cases.
2580 if (SE.properlyDominates(S, InsertionPoint->getParent()))
2581 return true;
2582 if (SE.dominates(S, InsertionPoint->getParent())) {
2583 if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2584 return true;
2585 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2586 if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
2587 return true;
2588 }
2589 return false;
2590}
2591
2593 // Result is used, nothing to remove.
2594 if (ResultUsed)
2595 return;
2596
2597 // Restore original poison flags.
2598 for (auto [I, Flags] : Expander.OrigFlags)
2599 Flags.apply(I);
2600
2601 auto InsertedInstructions = Expander.getAllInsertedInstructions();
2602#ifndef NDEBUG
2604 InsertedInstructions);
2605 (void)InsertedSet;
2606#endif
2607 // Remove sets with value handles.
2608 Expander.clear();
2609
2610 // Remove all inserted instructions.
2611 for (Instruction *I : reverse(InsertedInstructions)) {
2612#ifndef NDEBUG
2613 assert(all_of(I->users(),
2614 [&InsertedSet](Value *U) {
2615 return InsertedSet.contains(cast<Instruction>(U));
2616 }) &&
2617 "removed instruction should only be used by instructions inserted "
2618 "during expansion");
2619#endif
2620 assert(!I->getType()->isVoidTy() &&
2621 "inserted instruction should have non-void types");
2622 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
2623 I->eraseFromParent();
2624 }
2625}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static Expected< BitVector > expand(StringRef S, StringRef Original)
Hexagon Common GEP
Hexagon Hardware Loops
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
This file contains some templates that are useful if you are working with the STL at all.
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static const Loop * PickMostRelevantLoop(const Loop *A, const Loop *B, DominatorTree &DT)
PickMostRelevantLoop - Given two loops pick the one that's most relevant for SCEV expansion.
static InstructionCost costAndCollectOperands(const SCEVOperand &WorkItem, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, SmallVectorImpl< SCEVOperand > &Worklist)
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
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...
#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
static bool canReuseCastForPtrToAddr(const CastInst *CI, Type *Ty, const DataLayout &DL)
Return true if CI computes the same value as a ptrtoaddr of its pointer operand to Ty.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
unsigned logBase2() const
Definition APInt.h:1781
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Type * getSrcTy() const
Return the source type, as a convenience.
Definition InstrTypes.h:679
static LLVM_ABI 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.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags none()
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
ICmpInst::Predicate getPredicate() const
Returns the comparison predicate underlying the intrinsic.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
ConstantInt * getValue() const
const APInt & getAPInt() const
LLVM_ABI Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
LLVM_ABI bool hasRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Determine whether there is an existing expansion of S that can be reused.
SmallVector< Instruction *, 32 > getAllInsertedInstructions() const
Return a vector containing all instructions inserted during expansion.
LLVM_ABI bool isSafeToExpand(const SCEV *S) const
Return true if the given expression is safe to expand in the sense that all materialized values are s...
LLVM_ABI bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
LLVM_ABI unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
static LLVM_ABI void dropPoisonGeneratingAnnotationsAndReinfer(ScalarEvolution &SE, Instruction *I)
Drop poison-generating flags from I, then try re-infer via SCEV.
LLVM_ABI Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
static LLVM_ABI CastInst * findReusableCastForPtrToAddr(Value *PtrOp, Type *Ty, const DataLayout &DL, function_ref< bool(const CastInst *)> Dominates)
Find an existing cast among PtrOp's users that computes the same value as a ptrtoaddr of PtrOp to Ty ...
LLVM_ABI bool hoistIVInc(Instruction *IncV, Instruction *InsertPos, bool RecomputePoisonFlags=false)
Utility for hoisting IncV (with all subexpressions requried for its computation) before InsertPos.
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
static LLVM_ABI bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi, PHINode *WidePhi, Instruction *OrigInc, Instruction *WideInc)
Return true if both increments directly increment the corresponding IV PHI nodes and have the same op...
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
LLVM_ABI Value * expandComparePredicate(const SCEVComparePredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
LLVM_ABI BasicBlock::iterator findInsertPointAfter(Instruction *I, Instruction *MustDominate) const
Returns a suitable insert point after I, that dominates MustDominate.
void setInsertPoint(Instruction *IP)
Set the current insertion point.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an assumption made on an AddRec expression.
This class represents an analyzed expression in the program.
SCEVNoWrapFlags NoWrapFlags
static constexpr auto FlagNUW
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
The main scalar evolution driver.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlags Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr) const
Return the expected cost of materialization for the given integer immediate of the specified type for...
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ None
The cast is not used with a load/store of any kind.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr bool any(E Val)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVPtrToAddrExpr, Op0_t > m_scev_PtrToAddr(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVUMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_UMax(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
auto pred_size(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE, bool CheckInvertible=true)
Normalize S to be post-increment for all loops present in Loops.
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
constexpr unsigned BitWidth
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
Definition LCSSA.cpp:328
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
SmallPtrSet< const Loop *, 2 > PostIncLoopSet
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
LLVM_ABI void apply(Instruction *I)
LLVM_ABI PoisonFlags(const Instruction *I)
struct for holding enough information to help calculate the cost of the given SCEV when expanded into...
const SCEV * S
The SCEV operand to be costed.
unsigned ParentOpcode
LLVM instruction opcode that uses the operand.
int OperandIdx
The use index of an expanded instruction.
SCEVNoWrapFlags getNoWrapFlags(SCEVNoWrapFlags Mask=SCEVNoWrapFlags::FlagsMask) const
Return the no-wrap flags for this SCEVUse, which is the union of the use-specific flags and the under...