1009b1c42SEd Schouten //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements some loop unrolling utilities. It does not define any
10009b1c42SEd Schouten // actual pass or policy, but provides a single function to perform loop
11009b1c42SEd Schouten // unrolling.
12009b1c42SEd Schouten //
13009b1c42SEd Schouten // The process of unrolling can produce extraneous basic blocks linked with
14009b1c42SEd Schouten // unconditional branches. This will be corrected in the future.
15cf099d11SDimitry Andric //
16009b1c42SEd Schouten //===----------------------------------------------------------------------===//
17009b1c42SEd Schouten
18cfca06d7SDimitry Andric #include "llvm/ADT/ArrayRef.h"
19cfca06d7SDimitry Andric #include "llvm/ADT/DenseMap.h"
20cfca06d7SDimitry Andric #include "llvm/ADT/STLExtras.h"
21ac9a064cSDimitry Andric #include "llvm/ADT/ScopedHashTable.h"
22cfca06d7SDimitry Andric #include "llvm/ADT/SetVector.h"
23cfca06d7SDimitry Andric #include "llvm/ADT/SmallVector.h"
24009b1c42SEd Schouten #include "llvm/ADT/Statistic.h"
25cfca06d7SDimitry Andric #include "llvm/ADT/StringRef.h"
26cfca06d7SDimitry Andric #include "llvm/ADT/Twine.h"
27cfca06d7SDimitry Andric #include "llvm/ADT/ilist_iterator.h"
28ac9a064cSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
2967c32a98SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
30cfca06d7SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
31cf099d11SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
32cfca06d7SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
3330815c53SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
34ac9a064cSDimitry Andric #include "llvm/Analysis/MemorySSA.h"
35044eb2f6SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
36d39c594dSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
374a16efa3SDimitry Andric #include "llvm/IR/BasicBlock.h"
38cfca06d7SDimitry Andric #include "llvm/IR/CFG.h"
39cfca06d7SDimitry Andric #include "llvm/IR/Constants.h"
4071d5a254SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
41cfca06d7SDimitry Andric #include "llvm/IR/DebugLoc.h"
42cfca06d7SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
435a5ac124SDimitry Andric #include "llvm/IR/Dominators.h"
44cfca06d7SDimitry Andric #include "llvm/IR/Function.h"
45cfca06d7SDimitry Andric #include "llvm/IR/Instruction.h"
46cfca06d7SDimitry Andric #include "llvm/IR/Instructions.h"
47b915e9e0SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
48cfca06d7SDimitry Andric #include "llvm/IR/Metadata.h"
49cfca06d7SDimitry Andric #include "llvm/IR/Module.h"
507fa27ce4SDimitry Andric #include "llvm/IR/PatternMatch.h"
51cfca06d7SDimitry Andric #include "llvm/IR/Use.h"
52cfca06d7SDimitry Andric #include "llvm/IR/User.h"
53cfca06d7SDimitry Andric #include "llvm/IR/ValueHandle.h"
54cfca06d7SDimitry Andric #include "llvm/IR/ValueMap.h"
55cfca06d7SDimitry Andric #include "llvm/Support/Casting.h"
56706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
57009b1c42SEd Schouten #include "llvm/Support/Debug.h"
58cfca06d7SDimitry Andric #include "llvm/Support/GenericDomTree.h"
59cfca06d7SDimitry Andric #include "llvm/Support/MathExtras.h"
6059850d08SRoman Divacky #include "llvm/Support/raw_ostream.h"
61009b1c42SEd Schouten #include "llvm/Transforms/Utils/BasicBlockUtils.h"
62009b1c42SEd Schouten #include "llvm/Transforms/Utils/Cloning.h"
63706b4fc4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
6401095a5dSDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h"
655ca98fd9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
6630815c53SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
677ab83427SDimitry Andric #include "llvm/Transforms/Utils/UnrollLoop.h"
68cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
69cfca06d7SDimitry Andric #include <algorithm>
70cfca06d7SDimitry Andric #include <assert.h>
71e3b55780SDimitry Andric #include <numeric>
72cfca06d7SDimitry Andric #include <type_traits>
73cfca06d7SDimitry Andric #include <vector>
74cfca06d7SDimitry Andric
75cfca06d7SDimitry Andric namespace llvm {
76cfca06d7SDimitry Andric class DataLayout;
77cfca06d7SDimitry Andric class Value;
78cfca06d7SDimitry Andric } // namespace llvm
79cfca06d7SDimitry Andric
80009b1c42SEd Schouten using namespace llvm;
81009b1c42SEd Schouten
825ca98fd9SDimitry Andric #define DEBUG_TYPE "loop-unroll"
835ca98fd9SDimitry Andric
84009b1c42SEd Schouten // TODO: Should these be here or in LoopUnroll?
85009b1c42SEd Schouten STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
86009b1c42SEd Schouten STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
87cfca06d7SDimitry Andric STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
88cfca06d7SDimitry Andric "latch (completely or otherwise)");
89009b1c42SEd Schouten
9001095a5dSDimitry Andric static cl::opt<bool>
91b915e9e0SDimitry Andric UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
9201095a5dSDimitry Andric cl::desc("Allow runtime unrolled loops to be unrolled "
9301095a5dSDimitry Andric "with epilog instead of prolog."));
9401095a5dSDimitry Andric
9571d5a254SDimitry Andric static cl::opt<bool>
9671d5a254SDimitry Andric UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
9771d5a254SDimitry Andric cl::desc("Verify domtree after unrolling"),
98d8e91e46SDimitry Andric #ifdef EXPENSIVE_CHECKS
9971d5a254SDimitry Andric cl::init(true)
100d8e91e46SDimitry Andric #else
101d8e91e46SDimitry Andric cl::init(false)
10271d5a254SDimitry Andric #endif
10371d5a254SDimitry Andric );
10471d5a254SDimitry Andric
1056f8fc217SDimitry Andric static cl::opt<bool>
1066f8fc217SDimitry Andric UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
1076f8fc217SDimitry Andric cl::desc("Verify loopinfo after unrolling"),
1086f8fc217SDimitry Andric #ifdef EXPENSIVE_CHECKS
1096f8fc217SDimitry Andric cl::init(true)
1106f8fc217SDimitry Andric #else
1116f8fc217SDimitry Andric cl::init(false)
1126f8fc217SDimitry Andric #endif
1136f8fc217SDimitry Andric );
1146f8fc217SDimitry Andric
1156f8fc217SDimitry Andric
11601095a5dSDimitry Andric /// Check if unrolling created a situation where we need to insert phi nodes to
11701095a5dSDimitry Andric /// preserve LCSSA form.
11801095a5dSDimitry Andric /// \param Blocks is a vector of basic blocks representing unrolled loop.
11901095a5dSDimitry Andric /// \param L is the outer loop.
12001095a5dSDimitry Andric /// It's possible that some of the blocks are in L, and some are not. In this
12101095a5dSDimitry Andric /// case, if there is a use is outside L, and definition is inside L, we need to
12201095a5dSDimitry Andric /// insert a phi-node, otherwise LCSSA will be broken.
12301095a5dSDimitry Andric /// The function is just a helper function for llvm::UnrollLoop that returns
12401095a5dSDimitry Andric /// true if this situation occurs, indicating that LCSSA needs to be fixed.
needToInsertPhisForLCSSA(Loop * L,const std::vector<BasicBlock * > & Blocks,LoopInfo * LI)125b60736ecSDimitry Andric static bool needToInsertPhisForLCSSA(Loop *L,
126b60736ecSDimitry Andric const std::vector<BasicBlock *> &Blocks,
12701095a5dSDimitry Andric LoopInfo *LI) {
12801095a5dSDimitry Andric for (BasicBlock *BB : Blocks) {
12901095a5dSDimitry Andric if (LI->getLoopFor(BB) == L)
13001095a5dSDimitry Andric continue;
13101095a5dSDimitry Andric for (Instruction &I : *BB) {
13201095a5dSDimitry Andric for (Use &U : I.operands()) {
133b60736ecSDimitry Andric if (const auto *Def = dyn_cast<Instruction>(U)) {
13401095a5dSDimitry Andric Loop *DefLoop = LI->getLoopFor(Def->getParent());
13501095a5dSDimitry Andric if (!DefLoop)
13601095a5dSDimitry Andric continue;
13701095a5dSDimitry Andric if (DefLoop->contains(L))
13801095a5dSDimitry Andric return true;
13901095a5dSDimitry Andric }
14001095a5dSDimitry Andric }
14101095a5dSDimitry Andric }
14201095a5dSDimitry Andric }
14301095a5dSDimitry Andric return false;
14401095a5dSDimitry Andric }
14501095a5dSDimitry Andric
146581a6d85SDimitry Andric /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
147581a6d85SDimitry Andric /// and adds a mapping from the original loop to the new loop to NewLoops.
148581a6d85SDimitry Andric /// Returns nullptr if no new loop was created and a pointer to the
149581a6d85SDimitry Andric /// original loop OriginalBB was part of otherwise.
addClonedBlockToLoopInfo(BasicBlock * OriginalBB,BasicBlock * ClonedBB,LoopInfo * LI,NewLoopsMap & NewLoops)150581a6d85SDimitry Andric const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
151581a6d85SDimitry Andric BasicBlock *ClonedBB, LoopInfo *LI,
152581a6d85SDimitry Andric NewLoopsMap &NewLoops) {
153581a6d85SDimitry Andric // Figure out which loop New is in.
154581a6d85SDimitry Andric const Loop *OldLoop = LI->getLoopFor(OriginalBB);
155581a6d85SDimitry Andric assert(OldLoop && "Should (at least) be in the loop being unrolled!");
156581a6d85SDimitry Andric
157581a6d85SDimitry Andric Loop *&NewLoop = NewLoops[OldLoop];
158581a6d85SDimitry Andric if (!NewLoop) {
159581a6d85SDimitry Andric // Found a new sub-loop.
160581a6d85SDimitry Andric assert(OriginalBB == OldLoop->getHeader() &&
161581a6d85SDimitry Andric "Header should be first in RPO");
162581a6d85SDimitry Andric
163044eb2f6SDimitry Andric NewLoop = LI->AllocateLoop();
164581a6d85SDimitry Andric Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
165c60b9581SDimitry Andric
166c60b9581SDimitry Andric if (NewLoopParent)
167581a6d85SDimitry Andric NewLoopParent->addChildLoop(NewLoop);
168c60b9581SDimitry Andric else
169c60b9581SDimitry Andric LI->addTopLevelLoop(NewLoop);
170c60b9581SDimitry Andric
171581a6d85SDimitry Andric NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
172581a6d85SDimitry Andric return OldLoop;
173581a6d85SDimitry Andric } else {
174581a6d85SDimitry Andric NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
175581a6d85SDimitry Andric return nullptr;
176581a6d85SDimitry Andric }
177581a6d85SDimitry Andric }
178581a6d85SDimitry Andric
17971d5a254SDimitry Andric /// The function chooses which type of unroll (epilog or prolog) is more
18071d5a254SDimitry Andric /// profitabale.
18171d5a254SDimitry Andric /// Epilog unroll is more profitable when there is PHI that starts from
18271d5a254SDimitry Andric /// constant. In this case epilog will leave PHI start from constant,
18371d5a254SDimitry Andric /// but prolog will convert it to non-constant.
18471d5a254SDimitry Andric ///
18571d5a254SDimitry Andric /// loop:
18671d5a254SDimitry Andric /// PN = PHI [I, Latch], [CI, PreHeader]
18771d5a254SDimitry Andric /// I = foo(PN)
18871d5a254SDimitry Andric /// ...
18971d5a254SDimitry Andric ///
19071d5a254SDimitry Andric /// Epilog unroll case.
19171d5a254SDimitry Andric /// loop:
19271d5a254SDimitry Andric /// PN = PHI [I2, Latch], [CI, PreHeader]
19371d5a254SDimitry Andric /// I1 = foo(PN)
19471d5a254SDimitry Andric /// I2 = foo(I1)
19571d5a254SDimitry Andric /// ...
19671d5a254SDimitry Andric /// Prolog unroll case.
19771d5a254SDimitry Andric /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
19871d5a254SDimitry Andric /// loop:
19971d5a254SDimitry Andric /// PN = PHI [I2, Latch], [NewPN, PreHeader]
20071d5a254SDimitry Andric /// I1 = foo(PN)
20171d5a254SDimitry Andric /// I2 = foo(I1)
20271d5a254SDimitry Andric /// ...
20371d5a254SDimitry Andric ///
isEpilogProfitable(Loop * L)20471d5a254SDimitry Andric static bool isEpilogProfitable(Loop *L) {
20571d5a254SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader();
20671d5a254SDimitry Andric BasicBlock *Header = L->getHeader();
20771d5a254SDimitry Andric assert(PreHeader && Header);
208eb11fae6SDimitry Andric for (const PHINode &PN : Header->phis()) {
209eb11fae6SDimitry Andric if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
21071d5a254SDimitry Andric return true;
21171d5a254SDimitry Andric }
21271d5a254SDimitry Andric return false;
21371d5a254SDimitry Andric }
21471d5a254SDimitry Andric
215ac9a064cSDimitry Andric struct LoadValue {
216ac9a064cSDimitry Andric Instruction *DefI = nullptr;
217ac9a064cSDimitry Andric unsigned Generation = 0;
218ac9a064cSDimitry Andric LoadValue() = default;
LoadValueLoadValue219ac9a064cSDimitry Andric LoadValue(Instruction *Inst, unsigned Generation)
220ac9a064cSDimitry Andric : DefI(Inst), Generation(Generation) {}
221ac9a064cSDimitry Andric };
222ac9a064cSDimitry Andric
223ac9a064cSDimitry Andric class StackNode {
224ac9a064cSDimitry Andric ScopedHashTable<const SCEV *, LoadValue>::ScopeTy LoadScope;
225ac9a064cSDimitry Andric unsigned CurrentGeneration;
226ac9a064cSDimitry Andric unsigned ChildGeneration;
227ac9a064cSDimitry Andric DomTreeNode *Node;
228ac9a064cSDimitry Andric DomTreeNode::const_iterator ChildIter;
229ac9a064cSDimitry Andric DomTreeNode::const_iterator EndIter;
230ac9a064cSDimitry Andric bool Processed = false;
231ac9a064cSDimitry Andric
232ac9a064cSDimitry Andric public:
StackNode(ScopedHashTable<const SCEV *,LoadValue> & AvailableLoads,unsigned cg,DomTreeNode * N,DomTreeNode::const_iterator Child,DomTreeNode::const_iterator End)233ac9a064cSDimitry Andric StackNode(ScopedHashTable<const SCEV *, LoadValue> &AvailableLoads,
234ac9a064cSDimitry Andric unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child,
235ac9a064cSDimitry Andric DomTreeNode::const_iterator End)
236ac9a064cSDimitry Andric : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
237ac9a064cSDimitry Andric Node(N), ChildIter(Child), EndIter(End) {}
238ac9a064cSDimitry Andric // Accessors.
currentGeneration() const239ac9a064cSDimitry Andric unsigned currentGeneration() const { return CurrentGeneration; }
childGeneration() const240ac9a064cSDimitry Andric unsigned childGeneration() const { return ChildGeneration; }
childGeneration(unsigned generation)241ac9a064cSDimitry Andric void childGeneration(unsigned generation) { ChildGeneration = generation; }
node()242ac9a064cSDimitry Andric DomTreeNode *node() { return Node; }
childIter() const243ac9a064cSDimitry Andric DomTreeNode::const_iterator childIter() const { return ChildIter; }
244ac9a064cSDimitry Andric
nextChild()245ac9a064cSDimitry Andric DomTreeNode *nextChild() {
246ac9a064cSDimitry Andric DomTreeNode *Child = *ChildIter;
247ac9a064cSDimitry Andric ++ChildIter;
248ac9a064cSDimitry Andric return Child;
249ac9a064cSDimitry Andric }
250ac9a064cSDimitry Andric
end() const251ac9a064cSDimitry Andric DomTreeNode::const_iterator end() const { return EndIter; }
isProcessed() const252ac9a064cSDimitry Andric bool isProcessed() const { return Processed; }
process()253ac9a064cSDimitry Andric void process() { Processed = true; }
254ac9a064cSDimitry Andric };
255ac9a064cSDimitry Andric
getMatchingValue(LoadValue LV,LoadInst * LI,unsigned CurrentGeneration,BatchAAResults & BAA,function_ref<MemorySSA * ()> GetMSSA)256ac9a064cSDimitry Andric Value *getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration,
257ac9a064cSDimitry Andric BatchAAResults &BAA,
258ac9a064cSDimitry Andric function_ref<MemorySSA *()> GetMSSA) {
259ac9a064cSDimitry Andric if (!LV.DefI)
260ac9a064cSDimitry Andric return nullptr;
261ac9a064cSDimitry Andric if (LV.DefI->getType() != LI->getType())
262ac9a064cSDimitry Andric return nullptr;
263ac9a064cSDimitry Andric if (LV.Generation != CurrentGeneration) {
264ac9a064cSDimitry Andric MemorySSA *MSSA = GetMSSA();
265ac9a064cSDimitry Andric if (!MSSA)
266ac9a064cSDimitry Andric return nullptr;
267ac9a064cSDimitry Andric auto *EarlierMA = MSSA->getMemoryAccess(LV.DefI);
268ac9a064cSDimitry Andric MemoryAccess *LaterDef =
269ac9a064cSDimitry Andric MSSA->getWalker()->getClobberingMemoryAccess(LI, BAA);
270ac9a064cSDimitry Andric if (!MSSA->dominates(LaterDef, EarlierMA))
271ac9a064cSDimitry Andric return nullptr;
272ac9a064cSDimitry Andric }
273ac9a064cSDimitry Andric return LV.DefI;
274ac9a064cSDimitry Andric }
275ac9a064cSDimitry Andric
loadCSE(Loop * L,DominatorTree & DT,ScalarEvolution & SE,LoopInfo & LI,BatchAAResults & BAA,function_ref<MemorySSA * ()> GetMSSA)276ac9a064cSDimitry Andric void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI,
277ac9a064cSDimitry Andric BatchAAResults &BAA, function_ref<MemorySSA *()> GetMSSA) {
278ac9a064cSDimitry Andric ScopedHashTable<const SCEV *, LoadValue> AvailableLoads;
279ac9a064cSDimitry Andric SmallVector<std::unique_ptr<StackNode>> NodesToProcess;
280ac9a064cSDimitry Andric DomTreeNode *HeaderD = DT.getNode(L->getHeader());
281ac9a064cSDimitry Andric NodesToProcess.emplace_back(new StackNode(AvailableLoads, 0, HeaderD,
282ac9a064cSDimitry Andric HeaderD->begin(), HeaderD->end()));
283ac9a064cSDimitry Andric
284ac9a064cSDimitry Andric unsigned CurrentGeneration = 0;
285ac9a064cSDimitry Andric while (!NodesToProcess.empty()) {
286ac9a064cSDimitry Andric StackNode *NodeToProcess = &*NodesToProcess.back();
287ac9a064cSDimitry Andric
288ac9a064cSDimitry Andric CurrentGeneration = NodeToProcess->currentGeneration();
289ac9a064cSDimitry Andric
290ac9a064cSDimitry Andric if (!NodeToProcess->isProcessed()) {
291ac9a064cSDimitry Andric // Process the node.
292ac9a064cSDimitry Andric
293ac9a064cSDimitry Andric // If this block has a single predecessor, then the predecessor is the
294ac9a064cSDimitry Andric // parent
295ac9a064cSDimitry Andric // of the domtree node and all of the live out memory values are still
296ac9a064cSDimitry Andric // current in this block. If this block has multiple predecessors, then
297ac9a064cSDimitry Andric // they could have invalidated the live-out memory values of our parent
298ac9a064cSDimitry Andric // value. For now, just be conservative and invalidate memory if this
299ac9a064cSDimitry Andric // block has multiple predecessors.
300ac9a064cSDimitry Andric if (!NodeToProcess->node()->getBlock()->getSinglePredecessor())
301ac9a064cSDimitry Andric ++CurrentGeneration;
302ac9a064cSDimitry Andric for (auto &I : make_early_inc_range(*NodeToProcess->node()->getBlock())) {
303ac9a064cSDimitry Andric
304ac9a064cSDimitry Andric auto *Load = dyn_cast<LoadInst>(&I);
305ac9a064cSDimitry Andric if (!Load || !Load->isSimple()) {
306ac9a064cSDimitry Andric if (I.mayWriteToMemory())
307ac9a064cSDimitry Andric CurrentGeneration++;
308ac9a064cSDimitry Andric continue;
309ac9a064cSDimitry Andric }
310ac9a064cSDimitry Andric
311ac9a064cSDimitry Andric const SCEV *PtrSCEV = SE.getSCEV(Load->getPointerOperand());
312ac9a064cSDimitry Andric LoadValue LV = AvailableLoads.lookup(PtrSCEV);
313ac9a064cSDimitry Andric if (Value *M =
314ac9a064cSDimitry Andric getMatchingValue(LV, Load, CurrentGeneration, BAA, GetMSSA)) {
315ac9a064cSDimitry Andric if (LI.replacementPreservesLCSSAForm(Load, M)) {
316ac9a064cSDimitry Andric Load->replaceAllUsesWith(M);
317ac9a064cSDimitry Andric Load->eraseFromParent();
318ac9a064cSDimitry Andric }
319ac9a064cSDimitry Andric } else {
320ac9a064cSDimitry Andric AvailableLoads.insert(PtrSCEV, LoadValue(Load, CurrentGeneration));
321ac9a064cSDimitry Andric }
322ac9a064cSDimitry Andric }
323ac9a064cSDimitry Andric NodeToProcess->childGeneration(CurrentGeneration);
324ac9a064cSDimitry Andric NodeToProcess->process();
325ac9a064cSDimitry Andric } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
326ac9a064cSDimitry Andric // Push the next child onto the stack.
327ac9a064cSDimitry Andric DomTreeNode *Child = NodeToProcess->nextChild();
328ac9a064cSDimitry Andric if (!L->contains(Child->getBlock()))
329ac9a064cSDimitry Andric continue;
330ac9a064cSDimitry Andric NodesToProcess.emplace_back(
331ac9a064cSDimitry Andric new StackNode(AvailableLoads, NodeToProcess->childGeneration(), Child,
332ac9a064cSDimitry Andric Child->begin(), Child->end()));
333ac9a064cSDimitry Andric } else {
334ac9a064cSDimitry Andric // It has been processed, and there are no more children to process,
335ac9a064cSDimitry Andric // so delete it and pop it off the stack.
336ac9a064cSDimitry Andric NodesToProcess.pop_back();
337ac9a064cSDimitry Andric }
338ac9a064cSDimitry Andric }
339ac9a064cSDimitry Andric }
340ac9a064cSDimitry Andric
341eb11fae6SDimitry Andric /// Perform some cleanup and simplifications on loops after unrolling. It is
342eb11fae6SDimitry Andric /// useful to simplify the IV's in the new loop, as well as do a quick
343eb11fae6SDimitry Andric /// simplify/dce pass of the instructions.
simplifyLoopAfterUnroll(Loop * L,bool SimplifyIVs,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,const TargetTransformInfo * TTI,AAResults * AA)344eb11fae6SDimitry Andric void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
345eb11fae6SDimitry Andric ScalarEvolution *SE, DominatorTree *DT,
346cfca06d7SDimitry Andric AssumptionCache *AC,
347ac9a064cSDimitry Andric const TargetTransformInfo *TTI,
348ac9a064cSDimitry Andric AAResults *AA) {
3497fa27ce4SDimitry Andric using namespace llvm::PatternMatch;
3507fa27ce4SDimitry Andric
351eb11fae6SDimitry Andric // Simplify any new induction variables in the partially unrolled loop.
352eb11fae6SDimitry Andric if (SE && SimplifyIVs) {
353eb11fae6SDimitry Andric SmallVector<WeakTrackingVH, 16> DeadInsts;
354cfca06d7SDimitry Andric simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
355eb11fae6SDimitry Andric
356eb11fae6SDimitry Andric // Aggressively clean up dead instructions that simplifyLoopIVs already
357eb11fae6SDimitry Andric // identified. Any remaining should be cleaned up below.
358cfca06d7SDimitry Andric while (!DeadInsts.empty()) {
359cfca06d7SDimitry Andric Value *V = DeadInsts.pop_back_val();
360cfca06d7SDimitry Andric if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
361eb11fae6SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(Inst);
362eb11fae6SDimitry Andric }
363ac9a064cSDimitry Andric
364ac9a064cSDimitry Andric if (AA) {
365ac9a064cSDimitry Andric std::unique_ptr<MemorySSA> MSSA = nullptr;
366ac9a064cSDimitry Andric BatchAAResults BAA(*AA);
367ac9a064cSDimitry Andric loadCSE(L, *DT, *SE, *LI, BAA, [L, AA, DT, &MSSA]() -> MemorySSA * {
368ac9a064cSDimitry Andric if (!MSSA)
369ac9a064cSDimitry Andric MSSA.reset(new MemorySSA(*L, AA, DT));
370ac9a064cSDimitry Andric return &*MSSA;
371ac9a064cSDimitry Andric });
372ac9a064cSDimitry Andric }
373cfca06d7SDimitry Andric }
374eb11fae6SDimitry Andric
375344a3780SDimitry Andric // At this point, the code is well formed. Perform constprop, instsimplify,
376344a3780SDimitry Andric // and dce.
377ac9a064cSDimitry Andric const DataLayout &DL = L->getHeader()->getDataLayout();
378344a3780SDimitry Andric SmallVector<WeakTrackingVH, 16> DeadInsts;
379d8e91e46SDimitry Andric for (BasicBlock *BB : L->getBlocks()) {
380ac9a064cSDimitry Andric // Remove repeated debug instructions after loop unrolling.
381ac9a064cSDimitry Andric if (BB->getParent()->getSubprogram())
382ac9a064cSDimitry Andric RemoveRedundantDbgInstrs(BB);
383ac9a064cSDimitry Andric
384c0981da4SDimitry Andric for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
385145449b1SDimitry Andric if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
386c0981da4SDimitry Andric if (LI->replacementPreservesLCSSAForm(&Inst, V))
387c0981da4SDimitry Andric Inst.replaceAllUsesWith(V);
388c0981da4SDimitry Andric if (isInstructionTriviallyDead(&Inst))
389c0981da4SDimitry Andric DeadInsts.emplace_back(&Inst);
3907fa27ce4SDimitry Andric
3917fa27ce4SDimitry Andric // Fold ((add X, C1), C2) to (add X, C1+C2). This is very common in
3927fa27ce4SDimitry Andric // unrolled loops, and handling this early allows following code to
3937fa27ce4SDimitry Andric // identify the IV as a "simple recurrence" without first folding away
3947fa27ce4SDimitry Andric // a long chain of adds.
3957fa27ce4SDimitry Andric {
3967fa27ce4SDimitry Andric Value *X;
3977fa27ce4SDimitry Andric const APInt *C1, *C2;
3987fa27ce4SDimitry Andric if (match(&Inst, m_Add(m_Add(m_Value(X), m_APInt(C1)), m_APInt(C2)))) {
3997fa27ce4SDimitry Andric auto *InnerI = dyn_cast<Instruction>(Inst.getOperand(0));
4007fa27ce4SDimitry Andric auto *InnerOBO = cast<OverflowingBinaryOperator>(Inst.getOperand(0));
4017fa27ce4SDimitry Andric bool SignedOverflow;
4027fa27ce4SDimitry Andric APInt NewC = C1->sadd_ov(*C2, SignedOverflow);
4037fa27ce4SDimitry Andric Inst.setOperand(0, X);
4047fa27ce4SDimitry Andric Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
4057fa27ce4SDimitry Andric Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
4067fa27ce4SDimitry Andric InnerOBO->hasNoUnsignedWrap());
4077fa27ce4SDimitry Andric Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
4087fa27ce4SDimitry Andric InnerOBO->hasNoSignedWrap() &&
4097fa27ce4SDimitry Andric !SignedOverflow);
4107fa27ce4SDimitry Andric if (InnerI && isInstructionTriviallyDead(InnerI))
4117fa27ce4SDimitry Andric DeadInsts.emplace_back(InnerI);
4127fa27ce4SDimitry Andric }
4137fa27ce4SDimitry Andric }
414eb11fae6SDimitry Andric }
415344a3780SDimitry Andric // We can't do recursive deletion until we're done iterating, as we might
416344a3780SDimitry Andric // have a phi which (potentially indirectly) uses instructions later in
417344a3780SDimitry Andric // the block we're iterating through.
418344a3780SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
419eb11fae6SDimitry Andric }
420eb11fae6SDimitry Andric }
421eb11fae6SDimitry Andric
422ac9a064cSDimitry Andric // Loops containing convergent instructions that are uncontrolled or controlled
423ac9a064cSDimitry Andric // from outside the loop must have a count that divides their TripMultiple.
424ac9a064cSDimitry Andric LLVM_ATTRIBUTE_USED
canHaveUnrollRemainder(const Loop * L)425ac9a064cSDimitry Andric static bool canHaveUnrollRemainder(const Loop *L) {
426ac9a064cSDimitry Andric if (getLoopConvergenceHeart(L))
427ac9a064cSDimitry Andric return false;
428ac9a064cSDimitry Andric
429ac9a064cSDimitry Andric // Check for uncontrolled convergent operations.
430ac9a064cSDimitry Andric for (auto &BB : L->blocks()) {
431ac9a064cSDimitry Andric for (auto &I : *BB) {
432ac9a064cSDimitry Andric if (isa<ConvergenceControlInst>(I))
433ac9a064cSDimitry Andric return true;
434ac9a064cSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I))
435ac9a064cSDimitry Andric if (CB->isConvergent())
436ac9a064cSDimitry Andric return CB->getConvergenceControlToken();
437ac9a064cSDimitry Andric }
438ac9a064cSDimitry Andric }
439ac9a064cSDimitry Andric return true;
440ac9a064cSDimitry Andric }
441ac9a064cSDimitry Andric
442044eb2f6SDimitry Andric /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
443009b1c42SEd Schouten /// can only fail when the loop's latch block is not terminated by a conditional
444009b1c42SEd Schouten /// branch instruction. However, if the trip count (and multiple) are not known,
445009b1c42SEd Schouten /// loop unrolling will mostly produce more code that is no faster.
446009b1c42SEd Schouten ///
447344a3780SDimitry Andric /// If Runtime is true then UnrollLoop will try to insert a prologue or
448344a3780SDimitry Andric /// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
449344a3780SDimitry Andric /// will not runtime-unroll the loop if computing the run-time trip count will
450344a3780SDimitry Andric /// be expensive and AllowExpensiveTripCount is false.
451b915e9e0SDimitry Andric ///
452009b1c42SEd Schouten /// The LoopInfo Analysis that is passed will be kept consistent.
453009b1c42SEd Schouten ///
454dd58ef01SDimitry Andric /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
455dd58ef01SDimitry Andric /// DominatorTree if they are non-null.
456d8e91e46SDimitry Andric ///
457d8e91e46SDimitry Andric /// If RemainderLoop is non-null, it will receive the remainder loop (if
458d8e91e46SDimitry Andric /// required and not fully unrolled).
459ac9a064cSDimitry Andric LoopUnrollResult
UnrollLoop(Loop * L,UnrollLoopOptions ULO,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,const TargetTransformInfo * TTI,OptimizationRemarkEmitter * ORE,bool PreserveLCSSA,Loop ** RemainderLoop,AAResults * AA)460ac9a064cSDimitry Andric llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
461ac9a064cSDimitry Andric ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC,
462ac9a064cSDimitry Andric const TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE,
463ac9a064cSDimitry Andric bool PreserveLCSSA, Loop **RemainderLoop, AAResults *AA) {
464344a3780SDimitry Andric assert(DT && "DomTree is required");
465b915e9e0SDimitry Andric
466b60736ecSDimitry Andric if (!L->getLoopPreheader()) {
467eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
468044eb2f6SDimitry Andric return LoopUnrollResult::Unmodified;
469907da171SRoman Divacky }
470907da171SRoman Divacky
471b60736ecSDimitry Andric if (!L->getLoopLatch()) {
472eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
473044eb2f6SDimitry Andric return LoopUnrollResult::Unmodified;
474907da171SRoman Divacky }
475907da171SRoman Divacky
47663faed5bSDimitry Andric // Loops with indirectbr cannot be cloned.
47763faed5bSDimitry Andric if (!L->isSafeToClone()) {
478eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
479044eb2f6SDimitry Andric return LoopUnrollResult::Unmodified;
48063faed5bSDimitry Andric }
48163faed5bSDimitry Andric
482b60736ecSDimitry Andric if (L->getHeader()->hasAddressTaken()) {
483cf099d11SDimitry Andric // The loop-rotate pass can be helpful to avoid this in many cases.
484eb11fae6SDimitry Andric LLVM_DEBUG(
485eb11fae6SDimitry Andric dbgs() << " Won't unroll loop: address of header block is taken.\n");
486044eb2f6SDimitry Andric return LoopUnrollResult::Unmodified;
487cf099d11SDimitry Andric }
488cf099d11SDimitry Andric
489e6d15924SDimitry Andric assert(ULO.Count > 0);
490b915e9e0SDimitry Andric
491b60736ecSDimitry Andric // All these values should be taken only after peeling because they might have
492b60736ecSDimitry Andric // changed.
493b60736ecSDimitry Andric BasicBlock *Preheader = L->getLoopPreheader();
494b60736ecSDimitry Andric BasicBlock *Header = L->getHeader();
495b60736ecSDimitry Andric BasicBlock *LatchBlock = L->getLoopLatch();
496b60736ecSDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks;
497b60736ecSDimitry Andric L->getExitBlocks(ExitBlocks);
498b60736ecSDimitry Andric std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
499b60736ecSDimitry Andric
500344a3780SDimitry Andric const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
501344a3780SDimitry Andric const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
5027fa27ce4SDimitry Andric unsigned EstimatedLoopInvocationWeight = 0;
5037fa27ce4SDimitry Andric std::optional<unsigned> OriginalTripCount =
5047fa27ce4SDimitry Andric llvm::getLoopEstimatedTripCount(L, &EstimatedLoopInvocationWeight);
505344a3780SDimitry Andric
506344a3780SDimitry Andric // Effectively "DCE" unrolled iterations that are beyond the max tripcount
507344a3780SDimitry Andric // and will never be executed.
508344a3780SDimitry Andric if (MaxTripCount && ULO.Count > MaxTripCount)
509344a3780SDimitry Andric ULO.Count = MaxTripCount;
510344a3780SDimitry Andric
511344a3780SDimitry Andric struct ExitInfo {
512344a3780SDimitry Andric unsigned TripCount;
513344a3780SDimitry Andric unsigned TripMultiple;
514344a3780SDimitry Andric unsigned BreakoutTrip;
515344a3780SDimitry Andric bool ExitOnTrue;
516e3b55780SDimitry Andric BasicBlock *FirstExitingBlock = nullptr;
517344a3780SDimitry Andric SmallVector<BasicBlock *> ExitingBlocks;
518344a3780SDimitry Andric };
519344a3780SDimitry Andric DenseMap<BasicBlock *, ExitInfo> ExitInfos;
520344a3780SDimitry Andric SmallVector<BasicBlock *, 4> ExitingBlocks;
521344a3780SDimitry Andric L->getExitingBlocks(ExitingBlocks);
522344a3780SDimitry Andric for (auto *ExitingBlock : ExitingBlocks) {
523344a3780SDimitry Andric // The folding code is not prepared to deal with non-branch instructions
524344a3780SDimitry Andric // right now.
525344a3780SDimitry Andric auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
526344a3780SDimitry Andric if (!BI)
527344a3780SDimitry Andric continue;
528344a3780SDimitry Andric
529344a3780SDimitry Andric ExitInfo &Info = ExitInfos.try_emplace(ExitingBlock).first->second;
530344a3780SDimitry Andric Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
531344a3780SDimitry Andric Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
532344a3780SDimitry Andric if (Info.TripCount != 0) {
533344a3780SDimitry Andric Info.BreakoutTrip = Info.TripCount % ULO.Count;
534344a3780SDimitry Andric Info.TripMultiple = 0;
535344a3780SDimitry Andric } else {
536344a3780SDimitry Andric Info.BreakoutTrip = Info.TripMultiple =
537e3b55780SDimitry Andric (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
538344a3780SDimitry Andric }
539344a3780SDimitry Andric Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
540344a3780SDimitry Andric Info.ExitingBlocks.push_back(ExitingBlock);
541344a3780SDimitry Andric LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
542344a3780SDimitry Andric << ": TripCount=" << Info.TripCount
543344a3780SDimitry Andric << ", TripMultiple=" << Info.TripMultiple
544344a3780SDimitry Andric << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
545344a3780SDimitry Andric }
546344a3780SDimitry Andric
547344a3780SDimitry Andric // Are we eliminating the loop control altogether? Note that we can know
548344a3780SDimitry Andric // we're eliminating the backedge without knowing exactly which iteration
549344a3780SDimitry Andric // of the unrolled body exits.
550344a3780SDimitry Andric const bool CompletelyUnroll = ULO.Count == MaxTripCount;
551344a3780SDimitry Andric
552344a3780SDimitry Andric const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
553344a3780SDimitry Andric
554344a3780SDimitry Andric // There's no point in performing runtime unrolling if this unroll count
555344a3780SDimitry Andric // results in a full unroll.
556344a3780SDimitry Andric if (CompletelyUnroll)
557344a3780SDimitry Andric ULO.Runtime = false;
558344a3780SDimitry Andric
559b60736ecSDimitry Andric // Go through all exits of L and see if there are any phi-nodes there. We just
560b60736ecSDimitry Andric // conservatively assume that they're inserted to preserve LCSSA form, which
561b60736ecSDimitry Andric // means that complete unrolling might break this form. We need to either fix
562b60736ecSDimitry Andric // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
563b60736ecSDimitry Andric // now we just recompute LCSSA for the outer loop, but it should be possible
564b60736ecSDimitry Andric // to fix it in-place.
565b60736ecSDimitry Andric bool NeedToFixLCSSA =
566b60736ecSDimitry Andric PreserveLCSSA && CompletelyUnroll &&
567b60736ecSDimitry Andric any_of(ExitBlocks,
568b60736ecSDimitry Andric [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
569b60736ecSDimitry Andric
570b60736ecSDimitry Andric // The current loop unroll pass can unroll loops that have
571b60736ecSDimitry Andric // (1) single latch; and
572b60736ecSDimitry Andric // (2a) latch is unconditional; or
573b60736ecSDimitry Andric // (2b) latch is conditional and is an exiting block
574b60736ecSDimitry Andric // FIXME: The implementation can be extended to work with more complicated
575b60736ecSDimitry Andric // cases, e.g. loops with multiple latches.
576b60736ecSDimitry Andric BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
577b60736ecSDimitry Andric
578b60736ecSDimitry Andric // A conditional branch which exits the loop, which can be optimized to an
579b60736ecSDimitry Andric // unconditional branch in the unrolled loop in some cases.
580b60736ecSDimitry Andric bool LatchIsExiting = L->isLoopExiting(LatchBlock);
581b60736ecSDimitry Andric if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
582b60736ecSDimitry Andric LLVM_DEBUG(
583b60736ecSDimitry Andric dbgs() << "Can't unroll; a conditional latch must exit the loop");
584b60736ecSDimitry Andric return LoopUnrollResult::Unmodified;
585b60736ecSDimitry Andric }
586b60736ecSDimitry Andric
587ac9a064cSDimitry Andric assert((!ULO.Runtime || canHaveUnrollRemainder(L)) &&
588344a3780SDimitry Andric "Can't runtime unroll if loop contains a convergent operation.");
589b915e9e0SDimitry Andric
59071d5a254SDimitry Andric bool EpilogProfitability =
59171d5a254SDimitry Andric UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
59271d5a254SDimitry Andric : isEpilogProfitable(L);
59371d5a254SDimitry Andric
594344a3780SDimitry Andric if (ULO.Runtime &&
595e6d15924SDimitry Andric !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
596e6d15924SDimitry Andric EpilogProfitability, ULO.UnrollRemainder,
597cfca06d7SDimitry Andric ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
598e6d15924SDimitry Andric PreserveLCSSA, RemainderLoop)) {
599e6d15924SDimitry Andric if (ULO.Force)
600344a3780SDimitry Andric ULO.Runtime = false;
60171d5a254SDimitry Andric else {
602eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
603eb11fae6SDimitry Andric "generated when assuming runtime trip count\n");
604044eb2f6SDimitry Andric return LoopUnrollResult::Unmodified;
60501095a5dSDimitry Andric }
60671d5a254SDimitry Andric }
60763faed5bSDimitry Andric
608b915e9e0SDimitry Andric using namespace ore;
6095ca98fd9SDimitry Andric // Report the unrolling decision.
610009b1c42SEd Schouten if (CompletelyUnroll) {
611eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
612344a3780SDimitry Andric << " with trip count " << ULO.Count << "!\n");
613044eb2f6SDimitry Andric if (ORE)
614044eb2f6SDimitry Andric ORE->emit([&]() {
615044eb2f6SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
616b915e9e0SDimitry Andric L->getHeader())
617b915e9e0SDimitry Andric << "completely unrolled loop with "
618344a3780SDimitry Andric << NV("UnrollCount", ULO.Count) << " iterations";
619044eb2f6SDimitry Andric });
620009b1c42SEd Schouten } else {
621eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
622e6d15924SDimitry Andric << ULO.Count);
623344a3780SDimitry Andric if (ULO.Runtime)
624eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " with run-time trip count");
625eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "!\n");
626344a3780SDimitry Andric
627344a3780SDimitry Andric if (ORE)
628344a3780SDimitry Andric ORE->emit([&]() {
629344a3780SDimitry Andric OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
630344a3780SDimitry Andric L->getHeader());
631344a3780SDimitry Andric Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
632344a3780SDimitry Andric if (ULO.Runtime)
633344a3780SDimitry Andric Diag << " with run-time trip count";
634344a3780SDimitry Andric return Diag;
635344a3780SDimitry Andric });
636009b1c42SEd Schouten }
637009b1c42SEd Schouten
638eb11fae6SDimitry Andric // We are going to make changes to this loop. SCEV may be keeping cached info
639eb11fae6SDimitry Andric // about it, in particular about backedge taken count. The changes we make
640eb11fae6SDimitry Andric // are guaranteed to invalidate this information for our loop. It is tempting
641eb11fae6SDimitry Andric // to only invalidate the loop being unrolled, but it is incorrect as long as
642eb11fae6SDimitry Andric // all exiting branches from all inner loops have impact on the outer loops,
643eb11fae6SDimitry Andric // and if something changes inside them then any of outer loops may also
644eb11fae6SDimitry Andric // change. When we forget outermost loop, we also forget all contained loops
645eb11fae6SDimitry Andric // and this is what we need here.
646e6d15924SDimitry Andric if (SE) {
647e6d15924SDimitry Andric if (ULO.ForgetAllSCEV)
648e6d15924SDimitry Andric SE->forgetAllLoops();
649e3b55780SDimitry Andric else {
650eb11fae6SDimitry Andric SE->forgetTopmostLoop(L);
651e3b55780SDimitry Andric SE->forgetBlockAndLoopDispositions();
652e3b55780SDimitry Andric }
653e6d15924SDimitry Andric }
654eb11fae6SDimitry Andric
655cfca06d7SDimitry Andric if (!LatchIsExiting)
656cfca06d7SDimitry Andric ++NumUnrolledNotLatch;
657009b1c42SEd Schouten
658009b1c42SEd Schouten // For the first iteration of the loop, we should use the precloned values for
659009b1c42SEd Schouten // PHI nodes. Insert associations now.
660d7f7719eSRoman Divacky ValueToValueMapTy LastValueMap;
661009b1c42SEd Schouten std::vector<PHINode*> OrigPHINode;
662009b1c42SEd Schouten for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
66330815c53SDimitry Andric OrigPHINode.push_back(cast<PHINode>(I));
664009b1c42SEd Schouten }
665009b1c42SEd Schouten
666009b1c42SEd Schouten std::vector<BasicBlock *> Headers;
667009b1c42SEd Schouten std::vector<BasicBlock *> Latches;
668009b1c42SEd Schouten Headers.push_back(Header);
669009b1c42SEd Schouten Latches.push_back(LatchBlock);
670e6d15924SDimitry Andric
67130815c53SDimitry Andric // The current on-the-fly SSA update requires blocks to be processed in
67230815c53SDimitry Andric // reverse postorder so that LastValueMap contains the correct value at each
67330815c53SDimitry Andric // exit.
67430815c53SDimitry Andric LoopBlocksDFS DFS(L);
67530815c53SDimitry Andric DFS.perform(LI);
67630815c53SDimitry Andric
67730815c53SDimitry Andric // Stash the DFS iterators before adding blocks to the loop.
67830815c53SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
67930815c53SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
68030815c53SDimitry Andric
68101095a5dSDimitry Andric std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
682b915e9e0SDimitry Andric
683b915e9e0SDimitry Andric // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
684b915e9e0SDimitry Andric // might break loop-simplified form for these loops (as they, e.g., would
685b915e9e0SDimitry Andric // share the same exit blocks). We'll keep track of loops for which we can
686b915e9e0SDimitry Andric // break this so that later we can re-simplify them.
687b915e9e0SDimitry Andric SmallSetVector<Loop *, 4> LoopsToSimplify;
688b915e9e0SDimitry Andric for (Loop *SubLoop : *L)
689b915e9e0SDimitry Andric LoopsToSimplify.insert(SubLoop);
690b915e9e0SDimitry Andric
691344a3780SDimitry Andric // When a FSDiscriminator is enabled, we don't need to add the multiply
692344a3780SDimitry Andric // factors to the discriminators.
693e3b55780SDimitry Andric if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
694e3b55780SDimitry Andric !EnableFSDiscriminator)
69571d5a254SDimitry Andric for (BasicBlock *BB : L->getBlocks())
69671d5a254SDimitry Andric for (Instruction &I : *BB)
6977fa27ce4SDimitry Andric if (!I.isDebugOrPseudoInst())
698d8e91e46SDimitry Andric if (const DILocation *DIL = I.getDebugLoc()) {
699e6d15924SDimitry Andric auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
700d8e91e46SDimitry Andric if (NewDIL)
701145449b1SDimitry Andric I.setDebugLoc(*NewDIL);
702d8e91e46SDimitry Andric else
703d8e91e46SDimitry Andric LLVM_DEBUG(dbgs()
704d8e91e46SDimitry Andric << "Failed to create new discriminator: "
705d8e91e46SDimitry Andric << DIL->getFilename() << " Line: " << DIL->getLine());
706d8e91e46SDimitry Andric }
70771d5a254SDimitry Andric
708b60736ecSDimitry Andric // Identify what noalias metadata is inside the loop: if it is inside the
709b60736ecSDimitry Andric // loop, the associated metadata must be cloned for each iteration.
710b60736ecSDimitry Andric SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
711b60736ecSDimitry Andric identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
712b60736ecSDimitry Andric
713c0981da4SDimitry Andric // We place the unrolled iterations immediately after the original loop
714c0981da4SDimitry Andric // latch. This is a reasonable default placement if we don't have block
715c0981da4SDimitry Andric // frequencies, and if we do, well the layout will be adjusted later.
716c0981da4SDimitry Andric auto BlockInsertPt = std::next(LatchBlock->getIterator());
717e6d15924SDimitry Andric for (unsigned It = 1; It != ULO.Count; ++It) {
718cfca06d7SDimitry Andric SmallVector<BasicBlock *, 8> NewBlocks;
71967c32a98SDimitry Andric SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
72067c32a98SDimitry Andric NewLoops[L] = L;
721009b1c42SEd Schouten
72230815c53SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
72366e41e3cSRoman Divacky ValueToValueMapTy VMap;
72466e41e3cSRoman Divacky BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
725e3b55780SDimitry Andric Header->getParent()->insert(BlockInsertPt, New);
726009b1c42SEd Schouten
72771d5a254SDimitry Andric assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
72871d5a254SDimitry Andric "Header should not be in a sub-loop");
72967c32a98SDimitry Andric // Tell LI about New.
730581a6d85SDimitry Andric const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
731eb11fae6SDimitry Andric if (OldLoop)
732581a6d85SDimitry Andric LoopsToSimplify.insert(NewLoops[OldLoop]);
73367c32a98SDimitry Andric
734ac9a064cSDimitry Andric if (*BB == Header) {
73567c32a98SDimitry Andric // Loop over all of the PHI nodes in the block, changing them to use
73667c32a98SDimitry Andric // the incoming values from the previous block.
73701095a5dSDimitry Andric for (PHINode *OrigPHI : OrigPHINode) {
73801095a5dSDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
739009b1c42SEd Schouten Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
740009b1c42SEd Schouten if (Instruction *InValI = dyn_cast<Instruction>(InVal))
7411e7804dbSRoman Divacky if (It > 1 && L->contains(InValI))
742009b1c42SEd Schouten InVal = LastValueMap[InValI];
74301095a5dSDimitry Andric VMap[OrigPHI] = InVal;
744e3b55780SDimitry Andric NewPHI->eraseFromParent();
745009b1c42SEd Schouten }
746009b1c42SEd Schouten
747ac9a064cSDimitry Andric // Eliminate copies of the loop heart intrinsic, if any.
748ac9a064cSDimitry Andric if (ULO.Heart) {
749ac9a064cSDimitry Andric auto it = VMap.find(ULO.Heart);
750ac9a064cSDimitry Andric assert(it != VMap.end());
751ac9a064cSDimitry Andric Instruction *heartCopy = cast<Instruction>(it->second);
752ac9a064cSDimitry Andric heartCopy->eraseFromParent();
753ac9a064cSDimitry Andric VMap.erase(it);
754ac9a064cSDimitry Andric }
755ac9a064cSDimitry Andric }
756ac9a064cSDimitry Andric
757009b1c42SEd Schouten // Update our running map of newest clones
758009b1c42SEd Schouten LastValueMap[*BB] = New;
75966e41e3cSRoman Divacky for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
760009b1c42SEd Schouten VI != VE; ++VI)
761009b1c42SEd Schouten LastValueMap[VI->first] = VI->second;
762009b1c42SEd Schouten
76330815c53SDimitry Andric // Add phi entries for newly created values to all exit blocks.
76401095a5dSDimitry Andric for (BasicBlock *Succ : successors(*BB)) {
76501095a5dSDimitry Andric if (L->contains(Succ))
76630815c53SDimitry Andric continue;
767eb11fae6SDimitry Andric for (PHINode &PHI : Succ->phis()) {
768eb11fae6SDimitry Andric Value *Incoming = PHI.getIncomingValueForBlock(*BB);
76930815c53SDimitry Andric ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
77030815c53SDimitry Andric if (It != LastValueMap.end())
77130815c53SDimitry Andric Incoming = It->second;
772eb11fae6SDimitry Andric PHI.addIncoming(Incoming, New);
773e3b55780SDimitry Andric SE->forgetValue(&PHI);
774009b1c42SEd Schouten }
77530815c53SDimitry Andric }
776009b1c42SEd Schouten // Keep track of new headers and latches as we create them, so that
777009b1c42SEd Schouten // we can insert the proper branches later.
778009b1c42SEd Schouten if (*BB == Header)
779009b1c42SEd Schouten Headers.push_back(New);
78030815c53SDimitry Andric if (*BB == LatchBlock)
781009b1c42SEd Schouten Latches.push_back(New);
782009b1c42SEd Schouten
783cfca06d7SDimitry Andric // Keep track of the exiting block and its successor block contained in
784cfca06d7SDimitry Andric // the loop for the current iteration.
785344a3780SDimitry Andric auto ExitInfoIt = ExitInfos.find(*BB);
786344a3780SDimitry Andric if (ExitInfoIt != ExitInfos.end())
787344a3780SDimitry Andric ExitInfoIt->second.ExitingBlocks.push_back(New);
788e6d15924SDimitry Andric
789009b1c42SEd Schouten NewBlocks.push_back(New);
79001095a5dSDimitry Andric UnrolledLoopBlocks.push_back(New);
79101095a5dSDimitry Andric
79201095a5dSDimitry Andric // Update DomTree: since we just copy the loop body, and each copy has a
79301095a5dSDimitry Andric // dedicated entry block (copy of the header block), this header's copy
79401095a5dSDimitry Andric // dominates all copied blocks. That means, dominance relations in the
79501095a5dSDimitry Andric // copied body are the same as in the original body.
79601095a5dSDimitry Andric if (*BB == Header)
79701095a5dSDimitry Andric DT->addNewBlock(New, Latches[It - 1]);
79801095a5dSDimitry Andric else {
79901095a5dSDimitry Andric auto BBDomNode = DT->getNode(*BB);
80001095a5dSDimitry Andric auto BBIDom = BBDomNode->getIDom();
80101095a5dSDimitry Andric BasicBlock *OriginalBBIDom = BBIDom->getBlock();
80201095a5dSDimitry Andric DT->addNewBlock(
80301095a5dSDimitry Andric New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
80401095a5dSDimitry Andric }
80501095a5dSDimitry Andric }
806009b1c42SEd Schouten
807009b1c42SEd Schouten // Remap all instructions in the most recent iteration
808cfca06d7SDimitry Andric remapInstructionsInBlocks(NewBlocks, LastValueMap);
809344a3780SDimitry Andric for (BasicBlock *NewBlock : NewBlocks)
810344a3780SDimitry Andric for (Instruction &I : *NewBlock)
811344a3780SDimitry Andric if (auto *II = dyn_cast<AssumeInst>(&I))
812b915e9e0SDimitry Andric AC->registerAssumption(II);
813b60736ecSDimitry Andric
814b60736ecSDimitry Andric {
815b60736ecSDimitry Andric // Identify what other metadata depends on the cloned version. After
816b60736ecSDimitry Andric // cloning, replace the metadata with the corrected version for both
817b60736ecSDimitry Andric // memory instructions and noalias intrinsics.
818b60736ecSDimitry Andric std::string ext = (Twine("It") + Twine(It)).str();
819b60736ecSDimitry Andric cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
820b60736ecSDimitry Andric Header->getContext(), ext);
821b60736ecSDimitry Andric }
822009b1c42SEd Schouten }
823009b1c42SEd Schouten
82430815c53SDimitry Andric // Loop over the PHI nodes in the original block, setting incoming values.
82501095a5dSDimitry Andric for (PHINode *PN : OrigPHINode) {
82630815c53SDimitry Andric if (CompletelyUnroll) {
82730815c53SDimitry Andric PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
828e3b55780SDimitry Andric PN->eraseFromParent();
829e6d15924SDimitry Andric } else if (ULO.Count > 1) {
830009b1c42SEd Schouten Value *InVal = PN->removeIncomingValue(LatchBlock, false);
831009b1c42SEd Schouten // If this value was defined in the loop, take the value defined by the
832009b1c42SEd Schouten // last iteration of the loop.
833009b1c42SEd Schouten if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
8341e7804dbSRoman Divacky if (L->contains(InValI))
835009b1c42SEd Schouten InVal = LastValueMap[InVal];
836009b1c42SEd Schouten }
83730815c53SDimitry Andric assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
83830815c53SDimitry Andric PN->addIncoming(InVal, Latches.back());
839009b1c42SEd Schouten }
840009b1c42SEd Schouten }
841009b1c42SEd Schouten
842cfca06d7SDimitry Andric // Connect latches of the unrolled iterations to the headers of the next
843344a3780SDimitry Andric // iteration. Currently they point to the header of the same iteration.
844009b1c42SEd Schouten for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
845009b1c42SEd Schouten unsigned j = (i + 1) % e;
846344a3780SDimitry Andric Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
847009b1c42SEd Schouten }
84871d5a254SDimitry Andric
84901095a5dSDimitry Andric // Update dominators of blocks we might reach through exits.
85001095a5dSDimitry Andric // Immediate dominator of such block might change, because we add more
85101095a5dSDimitry Andric // routes which can lead to the exit: we can now reach it from the copied
85271d5a254SDimitry Andric // iterations too.
853344a3780SDimitry Andric if (ULO.Count > 1) {
85401095a5dSDimitry Andric for (auto *BB : OriginalLoopBlocks) {
85501095a5dSDimitry Andric auto *BBDomNode = DT->getNode(BB);
85601095a5dSDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate;
857cfca06d7SDimitry Andric for (auto *ChildDomNode : BBDomNode->children()) {
85801095a5dSDimitry Andric auto *ChildBB = ChildDomNode->getBlock();
85901095a5dSDimitry Andric if (!L->contains(ChildBB))
86001095a5dSDimitry Andric ChildrenToUpdate.push_back(ChildBB);
86101095a5dSDimitry Andric }
86271d5a254SDimitry Andric // The new idom of the block will be the nearest common dominator
86371d5a254SDimitry Andric // of all copies of the previous idom. This is equivalent to the
86471d5a254SDimitry Andric // nearest common dominator of the previous idom and the first latch,
86571d5a254SDimitry Andric // which dominates all copies of the previous idom.
866344a3780SDimitry Andric BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
86701095a5dSDimitry Andric for (auto *ChildBB : ChildrenToUpdate)
86801095a5dSDimitry Andric DT->changeImmediateDominator(ChildBB, NewIDom);
86901095a5dSDimitry Andric }
87001095a5dSDimitry Andric }
871411bd29eSDimitry Andric
872344a3780SDimitry Andric assert(!UnrollVerifyDomtree ||
873eb11fae6SDimitry Andric DT->verify(DominatorTree::VerificationLevel::Fast));
87471d5a254SDimitry Andric
875e3b55780SDimitry Andric SmallVector<DominatorTree::UpdateType> DTUpdates;
876344a3780SDimitry Andric auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
877344a3780SDimitry Andric auto *Term = cast<BranchInst>(Src->getTerminator());
878344a3780SDimitry Andric const unsigned Idx = ExitOnTrue ^ WillExit;
879344a3780SDimitry Andric BasicBlock *Dest = Term->getSuccessor(Idx);
880344a3780SDimitry Andric BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
881344a3780SDimitry Andric
882344a3780SDimitry Andric // Remove predecessors from all non-Dest successors.
883344a3780SDimitry Andric DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
884344a3780SDimitry Andric
885344a3780SDimitry Andric // Replace the conditional branch with an unconditional one.
886ac9a064cSDimitry Andric BranchInst::Create(Dest, Term->getIterator());
887344a3780SDimitry Andric Term->eraseFromParent();
888344a3780SDimitry Andric
889e3b55780SDimitry Andric DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
890344a3780SDimitry Andric };
891344a3780SDimitry Andric
892344a3780SDimitry Andric auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
893e3b55780SDimitry Andric bool IsLatch) -> std::optional<bool> {
894344a3780SDimitry Andric if (CompletelyUnroll) {
895344a3780SDimitry Andric if (PreserveOnlyFirst) {
896344a3780SDimitry Andric if (i == 0)
897e3b55780SDimitry Andric return std::nullopt;
898344a3780SDimitry Andric return j == 0;
899344a3780SDimitry Andric }
900344a3780SDimitry Andric // Complete (but possibly inexact) unrolling
901344a3780SDimitry Andric if (j == 0)
902344a3780SDimitry Andric return true;
903344a3780SDimitry Andric if (Info.TripCount && j != Info.TripCount)
904344a3780SDimitry Andric return false;
905e3b55780SDimitry Andric return std::nullopt;
906344a3780SDimitry Andric }
907344a3780SDimitry Andric
908344a3780SDimitry Andric if (ULO.Runtime) {
909344a3780SDimitry Andric // If runtime unrolling inserts a prologue, information about non-latch
910344a3780SDimitry Andric // exits may be stale.
911344a3780SDimitry Andric if (IsLatch && j != 0)
912344a3780SDimitry Andric return false;
913e3b55780SDimitry Andric return std::nullopt;
914344a3780SDimitry Andric }
915344a3780SDimitry Andric
916344a3780SDimitry Andric if (j != Info.BreakoutTrip &&
917344a3780SDimitry Andric (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
918344a3780SDimitry Andric // If we know the trip count or a multiple of it, we can safely use an
919344a3780SDimitry Andric // unconditional branch for some iterations.
920344a3780SDimitry Andric return false;
921344a3780SDimitry Andric }
922e3b55780SDimitry Andric return std::nullopt;
923344a3780SDimitry Andric };
924344a3780SDimitry Andric
925344a3780SDimitry Andric // Fold branches for iterations where we know that they will exit or not
926344a3780SDimitry Andric // exit.
927e3b55780SDimitry Andric for (auto &Pair : ExitInfos) {
928e3b55780SDimitry Andric ExitInfo &Info = Pair.second;
929344a3780SDimitry Andric for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
930344a3780SDimitry Andric // The branch destination.
931344a3780SDimitry Andric unsigned j = (i + 1) % e;
932344a3780SDimitry Andric bool IsLatch = Pair.first == LatchBlock;
933e3b55780SDimitry Andric std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
934e3b55780SDimitry Andric if (!KnownWillExit) {
935e3b55780SDimitry Andric if (!Info.FirstExitingBlock)
936e3b55780SDimitry Andric Info.FirstExitingBlock = Info.ExitingBlocks[i];
937344a3780SDimitry Andric continue;
938e3b55780SDimitry Andric }
939344a3780SDimitry Andric
940344a3780SDimitry Andric // We don't fold known-exiting branches for non-latch exits here,
941344a3780SDimitry Andric // because this ensures that both all loop blocks and all exit blocks
942344a3780SDimitry Andric // remain reachable in the CFG.
943344a3780SDimitry Andric // TODO: We could fold these branches, but it would require much more
944344a3780SDimitry Andric // sophisticated updates to LoopInfo.
945e3b55780SDimitry Andric if (*KnownWillExit && !IsLatch) {
946e3b55780SDimitry Andric if (!Info.FirstExitingBlock)
947e3b55780SDimitry Andric Info.FirstExitingBlock = Info.ExitingBlocks[i];
948344a3780SDimitry Andric continue;
949e3b55780SDimitry Andric }
950344a3780SDimitry Andric
951344a3780SDimitry Andric SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
952344a3780SDimitry Andric }
953344a3780SDimitry Andric }
954344a3780SDimitry Andric
955e3b55780SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
956e3b55780SDimitry Andric DomTreeUpdater *DTUToUse = &DTU;
957e3b55780SDimitry Andric if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
958e3b55780SDimitry Andric // Manually update the DT if there's a single exiting node. In that case
959e3b55780SDimitry Andric // there's a single exit node and it is sufficient to update the nodes
960e3b55780SDimitry Andric // immediately dominated by the original exiting block. They will become
961e3b55780SDimitry Andric // dominated by the first exiting block that leaves the loop after
962e3b55780SDimitry Andric // unrolling. Note that the CFG inside the loop does not change, so there's
963e3b55780SDimitry Andric // no need to update the DT inside the unrolled loop.
964e3b55780SDimitry Andric DTUToUse = nullptr;
965e3b55780SDimitry Andric auto &[OriginalExit, Info] = *ExitInfos.begin();
966e3b55780SDimitry Andric if (!Info.FirstExitingBlock)
967e3b55780SDimitry Andric Info.FirstExitingBlock = Info.ExitingBlocks.back();
968e3b55780SDimitry Andric for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
969e3b55780SDimitry Andric if (L->contains(C->getBlock()))
970e3b55780SDimitry Andric continue;
971e3b55780SDimitry Andric C->setIDom(DT->getNode(Info.FirstExitingBlock));
972e3b55780SDimitry Andric }
973e3b55780SDimitry Andric } else {
974e3b55780SDimitry Andric DTU.applyUpdates(DTUpdates);
975e3b55780SDimitry Andric }
976e3b55780SDimitry Andric
977344a3780SDimitry Andric // When completely unrolling, the last latch becomes unreachable.
978e3b55780SDimitry Andric if (!LatchIsExiting && CompletelyUnroll) {
979e3b55780SDimitry Andric // There is no need to update the DT here, because there must be a unique
980e3b55780SDimitry Andric // latch. Hence if the latch is not exiting it must directly branch back to
981e3b55780SDimitry Andric // the original loop header and does not dominate any nodes.
982e3b55780SDimitry Andric assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
983e3b55780SDimitry Andric changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
984e3b55780SDimitry Andric }
985344a3780SDimitry Andric
986411bd29eSDimitry Andric // Merge adjacent basic blocks, if possible.
98701095a5dSDimitry Andric for (BasicBlock *Latch : Latches) {
988e6d15924SDimitry Andric BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
989e6d15924SDimitry Andric assert((Term ||
990e6d15924SDimitry Andric (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
991e6d15924SDimitry Andric "Need a branch as terminator, except when fully unrolling with "
992e6d15924SDimitry Andric "unconditional latch");
993e6d15924SDimitry Andric if (Term && Term->isUnconditional()) {
994411bd29eSDimitry Andric BasicBlock *Dest = Term->getSuccessor(0);
995e6d15924SDimitry Andric BasicBlock *Fold = Dest->getUniquePredecessor();
996e3b55780SDimitry Andric if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
997e3b55780SDimitry Andric /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
998e3b55780SDimitry Andric /*PredecessorWithTwoSuccessors=*/false,
999e3b55780SDimitry Andric DTUToUse ? nullptr : DT)) {
100001095a5dSDimitry Andric // Dest has been folded into Fold. Update our worklists accordingly.
1001411bd29eSDimitry Andric std::replace(Latches.begin(), Latches.end(), Dest, Fold);
1002b1c73532SDimitry Andric llvm::erase(UnrolledLoopBlocks, Dest);
100301095a5dSDimitry Andric }
1004411bd29eSDimitry Andric }
1005009b1c42SEd Schouten }
1006e3b55780SDimitry Andric
1007e3b55780SDimitry Andric if (DTUToUse) {
10081d5ae102SDimitry Andric // Apply updates to the DomTree.
10091d5ae102SDimitry Andric DT = &DTU.getDomTree();
1010e3b55780SDimitry Andric }
10116f8fc217SDimitry Andric assert(!UnrollVerifyDomtree ||
10126f8fc217SDimitry Andric DT->verify(DominatorTree::VerificationLevel::Fast));
10136f8fc217SDimitry Andric
1014eb11fae6SDimitry Andric // At this point, the code is well formed. We now simplify the unrolled loop,
1015eb11fae6SDimitry Andric // doing constant propagation and dead code elimination as we go.
1016344a3780SDimitry Andric simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
1017ac9a064cSDimitry Andric TTI, AA);
1018b915e9e0SDimitry Andric
1019009b1c42SEd Schouten NumCompletelyUnrolled += CompletelyUnroll;
1020009b1c42SEd Schouten ++NumUnrolled;
10215ca98fd9SDimitry Andric
10225ca98fd9SDimitry Andric Loop *OuterL = L->getParentLoop();
1023dd58ef01SDimitry Andric // Update LoopInfo if the loop is completely removed.
10247fa27ce4SDimitry Andric if (CompletelyUnroll) {
1025044eb2f6SDimitry Andric LI->erase(L);
10267fa27ce4SDimitry Andric // We shouldn't try to use `L` anymore.
10277fa27ce4SDimitry Andric L = nullptr;
10287fa27ce4SDimitry Andric } else if (OriginalTripCount) {
10297fa27ce4SDimitry Andric // Update the trip count. Note that the remainder has already logic
10307fa27ce4SDimitry Andric // computing it in `UnrollRuntimeLoopRemainder`.
10317fa27ce4SDimitry Andric setLoopEstimatedTripCount(L, *OriginalTripCount / ULO.Count,
10327fa27ce4SDimitry Andric EstimatedLoopInvocationWeight);
10337fa27ce4SDimitry Andric }
1034009b1c42SEd Schouten
10356f8fc217SDimitry Andric // LoopInfo should not be valid, confirm that.
10366f8fc217SDimitry Andric if (UnrollVerifyLoopInfo)
10376f8fc217SDimitry Andric LI->verify(*DT);
10386f8fc217SDimitry Andric
103901095a5dSDimitry Andric // After complete unrolling most of the blocks should be contained in OuterL.
104001095a5dSDimitry Andric // However, some of them might happen to be out of OuterL (e.g. if they
104101095a5dSDimitry Andric // precede a loop exit). In this case we might need to insert PHI nodes in
104201095a5dSDimitry Andric // order to preserve LCSSA form.
104301095a5dSDimitry Andric // We don't need to check this if we already know that we need to fix LCSSA
104401095a5dSDimitry Andric // form.
104501095a5dSDimitry Andric // TODO: For now we just recompute LCSSA for the outer loop in this case, but
104601095a5dSDimitry Andric // it should be possible to fix it in-place.
104701095a5dSDimitry Andric if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
104801095a5dSDimitry Andric NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
104901095a5dSDimitry Andric
1050344a3780SDimitry Andric // Make sure that loop-simplify form is preserved. We want to simplify
10515ca98fd9SDimitry Andric // at least one layer outside of the loop that was unrolled so that any
10525ca98fd9SDimitry Andric // changes to the parent loop exposed by the unrolling are considered.
10535ca98fd9SDimitry Andric if (OuterL) {
1054b915e9e0SDimitry Andric // OuterL includes all loops for which we can break loop-simplify, so
1055b915e9e0SDimitry Andric // it's sufficient to simplify only it (it'll recursively simplify inner
1056b915e9e0SDimitry Andric // loops too).
105771d5a254SDimitry Andric if (NeedToFixLCSSA) {
105871d5a254SDimitry Andric // LCSSA must be performed on the outermost affected loop. The unrolled
105971d5a254SDimitry Andric // loop's last loop latch is guaranteed to be in the outermost loop
1060044eb2f6SDimitry Andric // after LoopInfo's been updated by LoopInfo::erase.
106171d5a254SDimitry Andric Loop *LatchLoop = LI->getLoopFor(Latches.back());
106271d5a254SDimitry Andric Loop *FixLCSSALoop = OuterL;
106371d5a254SDimitry Andric if (!FixLCSSALoop->contains(LatchLoop))
106471d5a254SDimitry Andric while (FixLCSSALoop->getParentLoop() != LatchLoop)
106571d5a254SDimitry Andric FixLCSSALoop = FixLCSSALoop->getParentLoop();
106671d5a254SDimitry Andric
106771d5a254SDimitry Andric formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
106871d5a254SDimitry Andric } else if (PreserveLCSSA) {
106971d5a254SDimitry Andric assert(OuterL->isLCSSAForm(*DT) &&
107071d5a254SDimitry Andric "Loops should be in LCSSA form after loop-unroll.");
107171d5a254SDimitry Andric }
107271d5a254SDimitry Andric
1073b915e9e0SDimitry Andric // TODO: That potentially might be compile-time expensive. We should try
1074b915e9e0SDimitry Andric // to fix the loop-simplified form incrementally.
1075e6d15924SDimitry Andric simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
1076b915e9e0SDimitry Andric } else {
1077b915e9e0SDimitry Andric // Simplify loops for which we might've broken loop-simplify form.
1078b915e9e0SDimitry Andric for (Loop *SubLoop : LoopsToSimplify)
1079e6d15924SDimitry Andric simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
10805ca98fd9SDimitry Andric }
10815ca98fd9SDimitry Andric
1082044eb2f6SDimitry Andric return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1083044eb2f6SDimitry Andric : LoopUnrollResult::PartiallyUnrolled;
1084009b1c42SEd Schouten }
10855a5ac124SDimitry Andric
10865a5ac124SDimitry Andric /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
10875a5ac124SDimitry Andric /// node with the given name (for example, "llvm.loop.unroll.count"). If no
10885a5ac124SDimitry Andric /// such metadata node exists, then nullptr is returned.
GetUnrollMetadata(MDNode * LoopID,StringRef Name)10895a5ac124SDimitry Andric MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
10905a5ac124SDimitry Andric // First operand should refer to the loop id itself.
10915a5ac124SDimitry Andric assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
10925a5ac124SDimitry Andric assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
10935a5ac124SDimitry Andric
1094ac9a064cSDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1095ac9a064cSDimitry Andric MDNode *MD = dyn_cast<MDNode>(MDO);
10965a5ac124SDimitry Andric if (!MD)
10975a5ac124SDimitry Andric continue;
10985a5ac124SDimitry Andric
10995a5ac124SDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0));
11005a5ac124SDimitry Andric if (!S)
11015a5ac124SDimitry Andric continue;
11025a5ac124SDimitry Andric
1103ac9a064cSDimitry Andric if (Name == S->getString())
11045a5ac124SDimitry Andric return MD;
11055a5ac124SDimitry Andric }
11065a5ac124SDimitry Andric return nullptr;
11075a5ac124SDimitry Andric }
1108