75#define DEBUG_TYPE "loop-split-utils"
120 Partitions.emplace_back(Start, End);
125 assert(PartitionIndex < Partitions.size() &&
126 "avoidPartitionGuard() called for an unknown partition");
127 Partitions[PartitionIndex].Guarded =
false;
133 if (PartitionIndex >= Partitions.size())
135 return Partitions[PartitionIndex].VMap.get();
140 unsigned PartitionIndex)
const {
143 if (PartitionIndex == 0)
155 Value *&LatchIndOperand) {
156 ICmpInst *LatchCmp = L->getLatchCmpInst();
159 PHINode *Induction = L->getInductionVariable(*SE);
182 else if (LatchCmp->
getOperand(1) == Induction ||
204 ": cannot prove iteration ordering signedness\n");
211 if (!L->getLoopPreheader() || !L->getLoopLatch() || !L->getExitingBlock() ||
212 !L->getExitBlock() || L->getExitingBlock() != L->getLoopLatch() ||
213 !L->isLCSSAForm(*DT)) {
219 ICmpInst *LatchCmp = L->getLatchCmpInst();
220 if (!LatchCmp || LatchCmp->
getParent() != L->getLoopLatch()) {
226 const SCEV *BTC = SE->getBackedgeTakenCount(L);
235 ": no unique unit-step integer induction\n");
242 InductionIsSigned = *
Signed;
281 PHINode *Induction = L->getInductionVariable(*SE);
282 assert(Induction &&
"split() requires a successful isLegal()");
286 if (!L->hasDedicatedExits() &&
294 PartitionInfo &P0 = Partitions[0];
295 P0.Preheader = L->getLoopPreheader();
296 P0.Exit = L->getExitBlock();
298 P0.LatchIndOp = LatchIndOperand;
308 collectEscapingValues(S);
317 expandPartitionBounds(S, Expander);
327void LoopSplitUtils::collectEscapingValues(SplitState &S) {
330 BasicBlock *OrigPreheader = Partitions[0].Preheader;
336 S.OuterLoop->addBasicBlockToLoop(S.FinalExit, *LI);
345 if (&HeaderPHI == S.Induction)
347 Value *CarriedValue = HeaderPHI.getIncomingValueForBlock(Latch);
348 Value *InitialValue = HeaderPHI.getIncomingValueForBlock(OrigPreheader);
349 if (CarriedValue == InitialValue)
351 auto &EV = S.addEscaping(CarriedValue);
352 EV.CarriedHeaderPHI = &HeaderPHI;
356 CarriedInst && L->
contains(CarriedInst))
357 CarriedDefToEscapingIdx[CarriedValue] = S.Escaping.
size() - 1;
363 assert(LCSSAPhi.getNumIncomingValues() == 1 &&
364 "exit block not in LCSSA form");
365 Value *LiveOutDef = LCSSAPhi.getIncomingValue(0);
366 auto Existing = CarriedDefToEscapingIdx.
find(LiveOutDef);
367 auto &EV = Existing != CarriedDefToEscapingIdx.
end()
368 ? S.Escaping[Existing->second]
369 : S.addEscaping(LiveOutDef);
370 EV.EscapesOutside =
true;
371 LCSSAPhi.replaceAllUsesWith(LiveOutDef);
372 LCSSAPhi.eraseFromParent();
378 for (
auto &EV : S.Escaping) {
379 EV.PerPartitionDef.assign(
N,
nullptr);
380 EV.PerPartitionPHI.assign(
N,
nullptr);
381 EV.PerPartitionDef[0] = EV.Def;
382 EV.PerPartitionPHI[0] = EV.CarriedHeaderPHI;
395 EntryGuard = Preheader;
396 Preheader = NewPreheader;
400 EntryGuard->
setName(
"ls.guard0");
405void LoopSplitUtils::expandPartitionBounds(SplitState &S,
407 Type *IndTy = S.Induction->getType();
408 Instruction *EntryGuardTerm = Partitions[0].GuardBlock->getTerminator();
413 for (
unsigned I = 0;
I <
N; ++
I) {
414 PartitionInfo &
P = Partitions[
I];
419 const SCEV *PartWidth = SE->getMinusSCEV(
P.StartExpr,
P.EndExpr);
421 const APInt &
W = PartWidthConst->getAPInt();
422 P.Empty = S.Descending ?
W.isAllOnes() :
W.isOne();
425 P.StartVal = Expander.
expandCodeFor(
P.StartExpr, IndTy, EntryGuardTerm);
429 const SCEV *ClampedEndSCEV;
431 ClampedEndSCEV = InductionIsSigned
432 ? SE->getSMaxExpr(
P.EndExpr, InductionEnd)
433 : SE->getUMaxExpr(
P.EndExpr, InductionEnd);
435 ClampedEndSCEV = InductionIsSigned
436 ? SE->getSMinExpr(
P.EndExpr, InductionEnd)
437 : SE->getUMinExpr(
P.EndExpr, InductionEnd);
438 P.SelEnd = Expander.
expandCodeFor(ClampedEndSCEV, IndTy, EntryGuardTerm);
444void LoopSplitUtils::clonePartitions(SplitState &S) {
445 Function &
F = *L->getHeader()->getParent();
446 LLVMContext &Ctx =
F.getContext();
450 BasicBlock *OrigPreheader = Partitions[0].Preheader;
452 for (
unsigned I = 1;
I <
N; ++
I) {
453 PartitionInfo &
P = Partitions[
I];
456 P.VMap = std::make_unique<ValueToValueMapTy>();
458 SmallVector<BasicBlock *, 8> ClonedBlocks;
460 ".ls" + Twine(
I), LI, DT, ClonedBlocks);
469 S.OuterLoop->addBasicBlockToLoop(Exiti, *LI);
470 S.OuterLoop->addBasicBlockToLoop(Guardi, *LI);
478 ClonedInduction->setIncomingValueForBlock(PHi,
P.StartVal);
480 P.GuardBlock = Guardi;
484 P.LatchIndOp = VMap.
lookup_or(LatchIndOperand, LatchIndOperand);
486 for (
auto &EV : S.Escaping) {
487 EV.PerPartitionDef[
I] = VMap.
lookup_or(EV.Def, EV.Def);
488 if (EV.CarriedHeaderPHI)
497 bool LatchComparesPHI) {
501 Value *Bound = SelEnd;
507 Value *NewCmp =
B.CreateICmp(Pred, IndOp, Bound,
"itr.chk");
508 B.SetInsertPoint(Term);
509 B.CreateCondBr(NewCmp, PL->getHeader(), Exit);
510 Term->eraseFromParent();
511 if (Cmp->use_empty())
512 Cmp->eraseFromParent();
517void LoopSplitUtils::chainPartitions(SplitState &S) {
527 auto EntersUnconditionally = [](
const PartitionInfo &
P) {
528 return !
P.Empty && !
P.Guarded;
533 auto MergeTargetAfter = [&](
unsigned Idx) -> BasicBlock * {
534 bool IsLastPartition = Idx + 1 ==
N;
535 return IsLastPartition ? S.FinalExit : Partitions[Idx + 1].GuardBlock;
538 for (
unsigned I = 0;
I <
N; ++
I) {
539 PartitionInfo &
P = Partitions[
I];
547 B.CreateBr(MergeAfter);
548 }
else if (!
P.Guarded) {
551 B.CreateBr(
P.Preheader);
553 Value *Enter =
B.CreateICmp(GuardPred,
P.StartVal,
P.SelEnd,
"itr.chk");
554 B.CreateCondBr(Enter,
P.Preheader, MergeAfter);
559 S.Descending, S.LatchComparesPHI);
560 P.Exit->getTerminator()->setSuccessor(0, MergeAfter);
565 auto MergeTargetIDom = [&](
const PartitionInfo &
P) {
566 return EntersUnconditionally(
P) ?
P.Exit :
P.GuardBlock;
569 for (
unsigned I = 1;
I <
N; ++
I) {
570 PartitionInfo &Prev = Partitions[
I - 1];
571 PartitionInfo &Cur = Partitions[
I];
572 DT->addNewBlock(Cur.GuardBlock, MergeTargetIDom(Prev));
573 DT->changeImmediateDominator(Cur.Preheader, Cur.GuardBlock);
574 DT->addNewBlock(Cur.Exit, Cur.SubLoop->getLoopLatch());
577 DT->changeImmediateDominator(S.FinalExit, MergeTargetIDom(Partitions.back()));
582void LoopSplitUtils::reconstructSSA(SplitState &S) {
584 for (
auto &EV : S.Escaping) {
586 Updater.
Initialize(EV.Def->getType(), EV.Def->getName());
590 Value *Init = EV.CarriedHeaderPHI
591 ? EV.CarriedHeaderPHI->getIncomingValueForBlock(
592 Partitions[0].Preheader)
595 for (
unsigned I = 0;
I <
N; ++
I)
601 if (EV.EscapesOutside)
604 if (!L->contains(User))
608 if (EV.CarriedHeaderPHI)
609 for (
unsigned I = 1;
I <
N; ++
I) {
610 PHINode *CarriedPHI = EV.PerPartitionPHI[
I];
611 int PreheaderEntryIdx =
613 assert(PreheaderEntryIdx >= 0 &&
"cloned preheader edge missing");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static ICmpInst::Predicate continuePredicate(bool Signed, bool Descending, bool Inclusive)
static const SCEVAddRecExpr * analyzeInduction(Loop *L, ScalarEvolution *SE, Value *&LatchIndOperand)
static ICmpInst::Predicate guardPredicate(bool Signed, bool Descending)
static void rewriteLatch(Loop *PL, Value *IndOp, Value *SelEnd, BasicBlock *Exit, bool Signed, bool Descending, bool LatchComparesPHI)
static std::optional< bool > computeSignedness(Loop *L, const SCEVAddRecExpr *IndAR)
static void buildEntryGuard(BasicBlock *&Preheader, BasicBlock *&EntryGuard, DominatorTree *DT, LoopInfo *LI)
Class for arbitrary precision integers.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
bool isOne() const
Determine if this is a value of 1.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
iterator find(const_arg_type_t< KeyT > Val)
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
BlockT * getHeader() const
LLVM_ABI bool split()
Perform the split.
LLVM_ABI unsigned getNumPartitions() const
LLVM_ABI bool isLegal()
Analyze L and return true if it is a counted loop this utility can split: a bottom-tested single-exit...
LLVM_ABI void addPartition(const SCEV *Start, const SCEV *End)
Append an inclusive partition range [Start, End] in iteration order.
LLVM_ABI Value * getPartitionValue(Value *V, unsigned PartitionIndex) const
Return the counterpart of original-loop value V in partition PartitionIndex (0-based).
LLVM_ABI const ValueToValueMapTy * getPartitionValueMap(unsigned PartitionIndex) const
Return the original-to-clone value map for the partition at PartitionIndex, for callers that want to ...
LLVM_ABI void avoidPartitionGuard(unsigned PartitionIndex)
Suppress the entry guard for partition PartitionIndex (already added).
Represents a single loop in the control flow graph.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
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.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
void markResultUsed()
Indicate that the result of the expansion is used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
bool hasNoUnsignedWrap() const
bool hasNoSignedWrap() const
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
LLVM_ABI void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
const Use & getOperandUse(unsigned i) const
Value * getOperand(unsigned i) const
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
ValueT lookup_or(const KeyT &Val, U &&Default) const
Return the entry for the specified key, or Default.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
@ BasicBlock
Various leaf nodes.
bool match(Val *V, const Pattern &P)
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock * > &Blocks)
Clones a loop OrigLoop.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
A value that must be reconstructed after cloning because it is loop-carried (feeds a later partition)...
PHINode * CarriedHeaderPHI
The carried header PHI in partition 0, or null if Def needs no per-partition start value seeded.
Value * Def
The value as it exists in partition 0 (the original).
bool EscapesOutside
True if Def is used outside the loop and must be merged at the final exit.
EscapingValue(Value *Def)
SmallVector< Value *, 4 > PerPartitionDef
Def and CarriedHeaderPHI cloned into each partition (index 0 is the original; PerPartitionPHI[0] is u...
SmallVector< PHINode *, 4 > PerPartitionPHI
Per-split() scratch shared by the phase helpers; lives for one split() call.
SmallVector< EscapingValue, 8 > Escaping
Values that must survive across partitions (carried and/or live-out).
EscapingValue & addEscaping(Value *Def)