43 #define DEBUG_TYPE "loop-rotate" 45 STATISTIC(NumRotated,
"Number of loops rotated");
50 const unsigned MaxHeaderSize;
61 LoopRotate(
unsigned MaxHeaderSize,
LoopInfo *LI,
64 bool RotationOnly,
bool IsUtilMode)
65 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
66 SQ(SQ), RotationOnly(RotationOnly), IsUtilMode(IsUtilMode) {}
67 bool processLoop(
Loop *L);
70 bool rotateLoop(
Loop *L,
bool SimplifiedLatch);
71 bool simplifyLoopLatch(
Loop *L);
91 for (I = OrigHeader->
begin(); I !=
E; ++
I) {
92 Value *OrigHeaderVal = &*
I;
99 Value *OrigPreHeaderVal = ValueMap.
lookup(OrigHeaderVal);
120 if (!isa<PHINode>(UserInst)) {
125 if (UserBB == OrigHeader)
130 if (UserBB == OrigPreheader) {
131 U = OrigPreHeaderVal;
144 for (
auto &DbgValue : DbgValues) {
148 if (UserBB == OrigHeader)
156 if (UserBB == OrigPreheader)
157 NewVal = OrigPreHeaderVal;
178 for (
auto &Phi : Header->
phis()) {
181 return cast<Instruction>(U)->
getParent() != HeaderExit;
200 bool LoopRotate::rotateLoop(
Loop *L,
bool SimplifiedLatch) {
225 if (L->
isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode ==
false &&
239 dbgs() <<
"LoopRotation: NOT rotating - contains non-duplicatable" 240 <<
" instructions: ";
245 LLVM_DEBUG(
dbgs() <<
"LoopRotation: NOT rotating - contains convergent " 250 if (Metrics.
NumInsts > MaxHeaderSize)
268 SE->forgetTopmostLoop(L);
279 assert(NewHeader &&
"Unable to determine new loop header");
281 "Unable to determine loop header and exit blocks");
286 "New header doesn't have one pred!");
304 using DbgIntrinsicHash =
305 std::pair<std::pair<Value *, DILocalVariable *>,
DIExpression *>;
307 return {{
D->getVariableLocation(),
D->getVariable()},
D->getExpression()};
310 for (
auto I = std::next(OrigPreheader->
rbegin()),
E = OrigPreheader->
rend();
312 if (
auto *DII = dyn_cast<DbgInfoIntrinsic>(&*I))
313 DbgIntrinsics.
insert(makeHash(DII));
329 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
342 if (
auto *DII = dyn_cast<DbgInfoIntrinsic>(C))
343 if (DbgIntrinsics.
count(makeHash(DII))) {
352 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
368 if (
auto *II = dyn_cast<IntrinsicInst>(C))
369 if (II->getIntrinsicID() == Intrinsic::assume)
370 AC->registerAssumption(II);
398 if (!InsertedPHIs.
empty())
403 assert(L->
getHeader() == NewHeader &&
"Latch block is our new header");
413 DT->applyUpdates(Updates);
435 OrigPreheader, NewHeader,
444 bool SplitLatchEdge =
false;
447 Loop *PredLoop = LI->getLoopFor(ExitPred);
448 if (!PredLoop || PredLoop->
contains(Exit))
450 if (isa<IndirectBrInst>(ExitPred->getTerminator()))
459 "Despite splitting all preds, failed to split latch exit?");
463 Exit->removePredecessor(OrigPreheader,
true );
469 if (DT) DT->deleteEdge(OrigPreheader, Exit);
493 bool seenIncrement =
false;
494 bool MultiExitLoop =
false;
497 MultiExitLoop =
true;
504 if (isa<DbgInfoIntrinsic>(
I))
507 switch (
I->getOpcode()) {
510 case Instruction::GetElementPtr:
512 if (!cast<GEPOperator>(
I)->hasAllConstantIndices())
517 case Instruction::Sub:
518 case Instruction::And:
519 case Instruction::Or:
520 case Instruction::Xor:
521 case Instruction::Shl:
522 case Instruction::LShr:
523 case Instruction::AShr: {
525 !isa<Constant>(
I->getOperand(0))
527 : !isa<Constant>(
I->getOperand(1)) ?
I->getOperand(1) :
nullptr;
535 auto *UserInst = cast<Instruction>(UseI);
543 seenIncrement =
true;
546 case Instruction::Trunc:
547 case Instruction::ZExt:
548 case Instruction::SExt:
564 bool LoopRotate::simplifyLoopLatch(
Loop *L) {
585 << LastExit->
getName() <<
"\n");
591 unsigned FallThruPath = BI->
getSuccessor(0) == Latch ? 0 : 1;
601 assert(Latch->
empty() &&
"unable to evacuate Latch");
602 LI->removeBlock(Latch);
604 DT->eraseNode(Latch);
610 bool LoopRotate::processLoop(
Loop *L) {
614 bool SimplifiedLatch =
false;
620 SimplifiedLatch = simplifyLoopLatch(L);
622 bool MadeChange = rotateLoop(L, SimplifiedLatch);
624 "Loop latch should be exiting after loop-rotate.");
628 if ((MadeChange || SimplifiedLatch) && LoopMD)
631 return MadeChange || SimplifiedLatch;
639 bool RotationOnly =
true,
641 bool IsUtilMode =
true) {
642 LoopRotate LR(
Threshold, LI, TTI, AC, DT, SE, SQ, RotationOnly, IsUtilMode);
644 return LR.processLoop(L);
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr, DeferredDominance *DDT=nullptr)
Attempts to merge a block into its predecessor, if possible.
Helper class for SSA formation on a set of values defined in multiple blocks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Compute iterated dominance frontiers using a linear time algorithm.
This is the interface for a simple mod/ref and alias analysis over globals.
bool convergent
True if this function contains a call to a convergent function.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End, Loop *L)
Determine whether the instructions in this range may be safely and cheaply speculated.
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
void deleteValue()
Delete a pointer to a generic Value.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
reverse_iterator rbegin()
Value * getCondition() const
bool notDuplicatable
True if this function cannot be duplicated.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
iterator begin()
Instruction iterator methods.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This is the interface for a SCEV-based alias analysis.
Option class for critical edge splitting.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static constexpr UpdateKind Delete
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void setName(const Twine &Name)
Change the name of the value.
BlockT * getHeader() const
void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode *> &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
void findDbgValues(SmallVectorImpl< DbgValueInst *> &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
Type * getType() const
All values are typed, get the type of this value.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
use_iterator_impl< Use > use_iterator
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of to it...
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
Subclasses of this class are all able to terminate a basic block.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
bool LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI, AssumptionCache *AC, DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ, bool RotationOnly, unsigned Threshold, bool IsUtilMode)
Convert a loop into a loop with bottom test.
LLVM Basic Block Representation.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
static bool shouldRotateLoopExitingLatch(Loop *L)
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
std::pair< iterator, bool > insert(const ValueT &V)
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Interval::pred_iterator pred_end(Interval *I)
self_iterator getIterator()
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
This is the common base class for debug info intrinsics.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Implements a dense probed hash-table based set with some number of buckets stored inline...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap, SmallVectorImpl< PHINode *> *InsertedPHIs)
RewriteUsesOfClonedInstructions - We just cloned the instructions from the old header into the prehea...
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool isUnconditional() const
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
This is the interface for LLVM's primary stateless and local alias analysis.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
unsigned NumInsts
Number of instructions in the analyzed blocks.
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const BasicBlock * getParent() const
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.