1f22ef01cSRoman Divacky //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements some loop unrolling utilities. It does not define any
11f22ef01cSRoman Divacky // actual pass or policy, but provides a single function to perform loop
12f22ef01cSRoman Divacky // unrolling.
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky // The process of unrolling can produce extraneous basic blocks linked with
15f22ef01cSRoman Divacky // unconditional branches. This will be corrected in the future.
162754fe60SDimitry Andric //
17f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
18f22ef01cSRoman Divacky
1991bc56edSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
20f22ef01cSRoman Divacky #include "llvm/ADT/Statistic.h"
2139d628a0SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
222754fe60SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
236122f3e6SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
242cab237bSDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
25e580952dSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
264ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
27139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
2891bc56edSDimitry Andric #include "llvm/IR/DataLayout.h"
297a7e6055SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
30ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
31d88c1a5aSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
3291bc56edSDimitry Andric #include "llvm/IR/LLVMContext.h"
33f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
34f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
35f22ef01cSRoman Divacky #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36f22ef01cSRoman Divacky #include "llvm/Transforms/Utils/Cloning.h"
373ca95b02SDimitry Andric #include "llvm/Transforms/Utils/LoopSimplify.h"
3891bc56edSDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
396122f3e6SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
40db17bf38SDimitry Andric #include "llvm/Transforms/Utils/UnrollLoop.h"
41f22ef01cSRoman Divacky using namespace llvm;
42f22ef01cSRoman Divacky
4391bc56edSDimitry Andric #define DEBUG_TYPE "loop-unroll"
4491bc56edSDimitry Andric
45f22ef01cSRoman Divacky // TODO: Should these be here or in LoopUnroll?
46f22ef01cSRoman Divacky STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
47f22ef01cSRoman Divacky STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
48f22ef01cSRoman Divacky
493ca95b02SDimitry Andric static cl::opt<bool>
50d88c1a5aSDimitry Andric UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
513ca95b02SDimitry Andric cl::desc("Allow runtime unrolled loops to be unrolled "
523ca95b02SDimitry Andric "with epilog instead of prolog."));
533ca95b02SDimitry Andric
547a7e6055SDimitry Andric static cl::opt<bool>
557a7e6055SDimitry Andric UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
567a7e6055SDimitry Andric cl::desc("Verify domtree after unrolling"),
57*b5893f02SDimitry Andric #ifdef EXPENSIVE_CHECKS
587a7e6055SDimitry Andric cl::init(true)
59*b5893f02SDimitry Andric #else
60*b5893f02SDimitry Andric cl::init(false)
617a7e6055SDimitry Andric #endif
627a7e6055SDimitry Andric );
637a7e6055SDimitry Andric
643ca95b02SDimitry Andric /// Convert the instruction operands from referencing the current values into
653ca95b02SDimitry Andric /// those specified by VMap.
remapInstruction(Instruction * I,ValueToValueMapTy & VMap)664ba319b5SDimitry Andric void llvm::remapInstruction(Instruction *I, ValueToValueMapTy &VMap) {
67f22ef01cSRoman Divacky for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
68f22ef01cSRoman Divacky Value *Op = I->getOperand(op);
692cab237bSDimitry Andric
702cab237bSDimitry Andric // Unwrap arguments of dbg.value intrinsics.
712cab237bSDimitry Andric bool Wrapped = false;
722cab237bSDimitry Andric if (auto *V = dyn_cast<MetadataAsValue>(Op))
732cab237bSDimitry Andric if (auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) {
742cab237bSDimitry Andric Op = Unwrapped->getValue();
752cab237bSDimitry Andric Wrapped = true;
762cab237bSDimitry Andric }
772cab237bSDimitry Andric
782cab237bSDimitry Andric auto wrap = [&](Value *V) {
792cab237bSDimitry Andric auto &C = I->getContext();
802cab237bSDimitry Andric return Wrapped ? MetadataAsValue::get(C, ValueAsMetadata::get(V)) : V;
812cab237bSDimitry Andric };
822cab237bSDimitry Andric
832754fe60SDimitry Andric ValueToValueMapTy::iterator It = VMap.find(Op);
84ffd1746dSEd Schouten if (It != VMap.end())
852cab237bSDimitry Andric I->setOperand(op, wrap(It->second));
86f22ef01cSRoman Divacky }
8717a519f9SDimitry Andric
8817a519f9SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(I)) {
8917a519f9SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9017a519f9SDimitry Andric ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
9117a519f9SDimitry Andric if (It != VMap.end())
9217a519f9SDimitry Andric PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
9317a519f9SDimitry Andric }
9417a519f9SDimitry Andric }
95f22ef01cSRoman Divacky }
96f22ef01cSRoman Divacky
973ca95b02SDimitry Andric /// Folds a basic block into its predecessor if it only has one predecessor, and
983ca95b02SDimitry Andric /// that predecessor only has one successor.
994ba319b5SDimitry Andric /// The LoopInfo Analysis that is passed will be kept consistent.
foldBlockIntoPredecessor(BasicBlock * BB,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT)1004ba319b5SDimitry Andric BasicBlock *llvm::foldBlockIntoPredecessor(BasicBlock *BB, LoopInfo *LI,
1014ba319b5SDimitry Andric ScalarEvolution *SE,
1023ca95b02SDimitry Andric DominatorTree *DT) {
103f22ef01cSRoman Divacky // Merge basic blocks into their predecessor if there is only one distinct
104f22ef01cSRoman Divacky // pred, and if there is only one distinct successor of the predecessor, and
105f22ef01cSRoman Divacky // if there are no PHI nodes.
106f22ef01cSRoman Divacky BasicBlock *OnlyPred = BB->getSinglePredecessor();
10791bc56edSDimitry Andric if (!OnlyPred) return nullptr;
108f22ef01cSRoman Divacky
109f22ef01cSRoman Divacky if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
11091bc56edSDimitry Andric return nullptr;
111f22ef01cSRoman Divacky
1124ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
1134ba319b5SDimitry Andric << OnlyPred->getName() << "\n");
114f22ef01cSRoman Divacky
115f22ef01cSRoman Divacky // Resolve any PHI nodes at the start of the block. They are all
116f22ef01cSRoman Divacky // guaranteed to have exactly one entry if they exist, unless there are
117f22ef01cSRoman Divacky // multiple duplicate (but guaranteed to be equal) entries for the
118f22ef01cSRoman Divacky // incoming edges. This occurs when there are multiple edges from
119f22ef01cSRoman Divacky // OnlyPred to OnlySucc.
120f22ef01cSRoman Divacky FoldSingleEntryPHINodes(BB);
121f22ef01cSRoman Divacky
122f22ef01cSRoman Divacky // Delete the unconditional branch from the predecessor...
123f22ef01cSRoman Divacky OnlyPred->getInstList().pop_back();
124f22ef01cSRoman Divacky
125f22ef01cSRoman Divacky // Make all PHI nodes that referred to BB now refer to Pred as their
126f22ef01cSRoman Divacky // source...
127f22ef01cSRoman Divacky BB->replaceAllUsesWith(OnlyPred);
128f22ef01cSRoman Divacky
12917a519f9SDimitry Andric // Move all definitions in the successor to the predecessor...
13017a519f9SDimitry Andric OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
13117a519f9SDimitry Andric
132f785676fSDimitry Andric // OldName will be valid until erased.
133f785676fSDimitry Andric StringRef OldName = BB->getName();
134f22ef01cSRoman Divacky
1353ca95b02SDimitry Andric // Erase the old block and update dominator info.
1363ca95b02SDimitry Andric if (DT)
1373ca95b02SDimitry Andric if (DomTreeNode *DTN = DT->getNode(BB)) {
1383ca95b02SDimitry Andric DomTreeNode *PredDTN = DT->getNode(OnlyPred);
1393ca95b02SDimitry Andric SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
1403ca95b02SDimitry Andric for (auto *DI : Children)
1413ca95b02SDimitry Andric DT->changeImmediateDominator(DI, PredDTN);
1423ca95b02SDimitry Andric
1433ca95b02SDimitry Andric DT->eraseNode(BB);
1443ca95b02SDimitry Andric }
1456122f3e6SDimitry Andric
146f22ef01cSRoman Divacky LI->removeBlock(BB);
147f22ef01cSRoman Divacky
148f22ef01cSRoman Divacky // Inherit predecessor's name if it exists...
149f22ef01cSRoman Divacky if (!OldName.empty() && !OnlyPred->hasName())
150f22ef01cSRoman Divacky OnlyPred->setName(OldName);
151f22ef01cSRoman Divacky
152f785676fSDimitry Andric BB->eraseFromParent();
153f785676fSDimitry Andric
154f22ef01cSRoman Divacky return OnlyPred;
155f22ef01cSRoman Divacky }
156f22ef01cSRoman Divacky
1573ca95b02SDimitry Andric /// Check if unrolling created a situation where we need to insert phi nodes to
1583ca95b02SDimitry Andric /// preserve LCSSA form.
1593ca95b02SDimitry Andric /// \param Blocks is a vector of basic blocks representing unrolled loop.
1603ca95b02SDimitry Andric /// \param L is the outer loop.
1613ca95b02SDimitry Andric /// It's possible that some of the blocks are in L, and some are not. In this
1623ca95b02SDimitry Andric /// case, if there is a use is outside L, and definition is inside L, we need to
1633ca95b02SDimitry Andric /// insert a phi-node, otherwise LCSSA will be broken.
1643ca95b02SDimitry Andric /// The function is just a helper function for llvm::UnrollLoop that returns
1653ca95b02SDimitry Andric /// true if this situation occurs, indicating that LCSSA needs to be fixed.
needToInsertPhisForLCSSA(Loop * L,std::vector<BasicBlock * > Blocks,LoopInfo * LI)1663ca95b02SDimitry Andric static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
1673ca95b02SDimitry Andric LoopInfo *LI) {
1683ca95b02SDimitry Andric for (BasicBlock *BB : Blocks) {
1693ca95b02SDimitry Andric if (LI->getLoopFor(BB) == L)
1703ca95b02SDimitry Andric continue;
1713ca95b02SDimitry Andric for (Instruction &I : *BB) {
1723ca95b02SDimitry Andric for (Use &U : I.operands()) {
1733ca95b02SDimitry Andric if (auto Def = dyn_cast<Instruction>(U)) {
1743ca95b02SDimitry Andric Loop *DefLoop = LI->getLoopFor(Def->getParent());
1753ca95b02SDimitry Andric if (!DefLoop)
1763ca95b02SDimitry Andric continue;
1773ca95b02SDimitry Andric if (DefLoop->contains(L))
1783ca95b02SDimitry Andric return true;
1793ca95b02SDimitry Andric }
1803ca95b02SDimitry Andric }
1813ca95b02SDimitry Andric }
1823ca95b02SDimitry Andric }
1833ca95b02SDimitry Andric return false;
1843ca95b02SDimitry Andric }
1853ca95b02SDimitry Andric
186f1a29dd3SDimitry Andric /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
187f1a29dd3SDimitry Andric /// and adds a mapping from the original loop to the new loop to NewLoops.
188f1a29dd3SDimitry Andric /// Returns nullptr if no new loop was created and a pointer to the
189f1a29dd3SDimitry Andric /// original loop OriginalBB was part of otherwise.
addClonedBlockToLoopInfo(BasicBlock * OriginalBB,BasicBlock * ClonedBB,LoopInfo * LI,NewLoopsMap & NewLoops)190f1a29dd3SDimitry Andric const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
191f1a29dd3SDimitry Andric BasicBlock *ClonedBB, LoopInfo *LI,
192f1a29dd3SDimitry Andric NewLoopsMap &NewLoops) {
193f1a29dd3SDimitry Andric // Figure out which loop New is in.
194f1a29dd3SDimitry Andric const Loop *OldLoop = LI->getLoopFor(OriginalBB);
195f1a29dd3SDimitry Andric assert(OldLoop && "Should (at least) be in the loop being unrolled!");
196f1a29dd3SDimitry Andric
197f1a29dd3SDimitry Andric Loop *&NewLoop = NewLoops[OldLoop];
198f1a29dd3SDimitry Andric if (!NewLoop) {
199f1a29dd3SDimitry Andric // Found a new sub-loop.
200f1a29dd3SDimitry Andric assert(OriginalBB == OldLoop->getHeader() &&
201f1a29dd3SDimitry Andric "Header should be first in RPO");
202f1a29dd3SDimitry Andric
2032cab237bSDimitry Andric NewLoop = LI->AllocateLoop();
204f1a29dd3SDimitry Andric Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
2052bcad0d8SDimitry Andric
2062bcad0d8SDimitry Andric if (NewLoopParent)
207f1a29dd3SDimitry Andric NewLoopParent->addChildLoop(NewLoop);
2082bcad0d8SDimitry Andric else
2092bcad0d8SDimitry Andric LI->addTopLevelLoop(NewLoop);
2102bcad0d8SDimitry Andric
211f1a29dd3SDimitry Andric NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
212f1a29dd3SDimitry Andric return OldLoop;
213f1a29dd3SDimitry Andric } else {
214f1a29dd3SDimitry Andric NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
215f1a29dd3SDimitry Andric return nullptr;
216f1a29dd3SDimitry Andric }
217f1a29dd3SDimitry Andric }
218f1a29dd3SDimitry Andric
2197a7e6055SDimitry Andric /// The function chooses which type of unroll (epilog or prolog) is more
2207a7e6055SDimitry Andric /// profitabale.
2217a7e6055SDimitry Andric /// Epilog unroll is more profitable when there is PHI that starts from
2227a7e6055SDimitry Andric /// constant. In this case epilog will leave PHI start from constant,
2237a7e6055SDimitry Andric /// but prolog will convert it to non-constant.
2247a7e6055SDimitry Andric ///
2257a7e6055SDimitry Andric /// loop:
2267a7e6055SDimitry Andric /// PN = PHI [I, Latch], [CI, PreHeader]
2277a7e6055SDimitry Andric /// I = foo(PN)
2287a7e6055SDimitry Andric /// ...
2297a7e6055SDimitry Andric ///
2307a7e6055SDimitry Andric /// Epilog unroll case.
2317a7e6055SDimitry Andric /// loop:
2327a7e6055SDimitry Andric /// PN = PHI [I2, Latch], [CI, PreHeader]
2337a7e6055SDimitry Andric /// I1 = foo(PN)
2347a7e6055SDimitry Andric /// I2 = foo(I1)
2357a7e6055SDimitry Andric /// ...
2367a7e6055SDimitry Andric /// Prolog unroll case.
2377a7e6055SDimitry Andric /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
2387a7e6055SDimitry Andric /// loop:
2397a7e6055SDimitry Andric /// PN = PHI [I2, Latch], [NewPN, PreHeader]
2407a7e6055SDimitry Andric /// I1 = foo(PN)
2417a7e6055SDimitry Andric /// I2 = foo(I1)
2427a7e6055SDimitry Andric /// ...
2437a7e6055SDimitry Andric ///
isEpilogProfitable(Loop * L)2447a7e6055SDimitry Andric static bool isEpilogProfitable(Loop *L) {
2457a7e6055SDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader();
2467a7e6055SDimitry Andric BasicBlock *Header = L->getHeader();
2477a7e6055SDimitry Andric assert(PreHeader && Header);
24830785c0eSDimitry Andric for (const PHINode &PN : Header->phis()) {
24930785c0eSDimitry Andric if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
2507a7e6055SDimitry Andric return true;
2517a7e6055SDimitry Andric }
2527a7e6055SDimitry Andric return false;
2537a7e6055SDimitry Andric }
2547a7e6055SDimitry Andric
2554ba319b5SDimitry Andric /// Perform some cleanup and simplifications on loops after unrolling. It is
2564ba319b5SDimitry Andric /// useful to simplify the IV's in the new loop, as well as do a quick
2574ba319b5SDimitry Andric /// simplify/dce pass of the instructions.
simplifyLoopAfterUnroll(Loop * L,bool SimplifyIVs,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC)2584ba319b5SDimitry Andric void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
2594ba319b5SDimitry Andric ScalarEvolution *SE, DominatorTree *DT,
2604ba319b5SDimitry Andric AssumptionCache *AC) {
2614ba319b5SDimitry Andric // Simplify any new induction variables in the partially unrolled loop.
2624ba319b5SDimitry Andric if (SE && SimplifyIVs) {
2634ba319b5SDimitry Andric SmallVector<WeakTrackingVH, 16> DeadInsts;
2644ba319b5SDimitry Andric simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
2654ba319b5SDimitry Andric
2664ba319b5SDimitry Andric // Aggressively clean up dead instructions that simplifyLoopIVs already
2674ba319b5SDimitry Andric // identified. Any remaining should be cleaned up below.
2684ba319b5SDimitry Andric while (!DeadInsts.empty())
2694ba319b5SDimitry Andric if (Instruction *Inst =
2704ba319b5SDimitry Andric dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
2714ba319b5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(Inst);
2724ba319b5SDimitry Andric }
2734ba319b5SDimitry Andric
2744ba319b5SDimitry Andric // At this point, the code is well formed. We now do a quick sweep over the
2754ba319b5SDimitry Andric // inserted code, doing constant propagation and dead code elimination as we
2764ba319b5SDimitry Andric // go.
2774ba319b5SDimitry Andric const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
278*b5893f02SDimitry Andric for (BasicBlock *BB : L->getBlocks()) {
2794ba319b5SDimitry Andric for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2804ba319b5SDimitry Andric Instruction *Inst = &*I++;
2814ba319b5SDimitry Andric
2824ba319b5SDimitry Andric if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC}))
2834ba319b5SDimitry Andric if (LI->replacementPreservesLCSSAForm(Inst, V))
2844ba319b5SDimitry Andric Inst->replaceAllUsesWith(V);
2854ba319b5SDimitry Andric if (isInstructionTriviallyDead(Inst))
2864ba319b5SDimitry Andric BB->getInstList().erase(Inst);
2874ba319b5SDimitry Andric }
2884ba319b5SDimitry Andric }
2894ba319b5SDimitry Andric
2904ba319b5SDimitry Andric // TODO: after peeling or unrolling, previously loop variant conditions are
2914ba319b5SDimitry Andric // likely to fold to constants, eagerly propagating those here will require
2924ba319b5SDimitry Andric // fewer cleanup passes to be run. Alternatively, a LoopEarlyCSE might be
2934ba319b5SDimitry Andric // appropriate.
2944ba319b5SDimitry Andric }
2954ba319b5SDimitry Andric
2962cab237bSDimitry Andric /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
297f22ef01cSRoman Divacky /// can only fail when the loop's latch block is not terminated by a conditional
298f22ef01cSRoman Divacky /// branch instruction. However, if the trip count (and multiple) are not known,
299f22ef01cSRoman Divacky /// loop unrolling will mostly produce more code that is no faster.
300f22ef01cSRoman Divacky ///
301d88c1a5aSDimitry Andric /// TripCount is the upper bound of the iteration on which control exits
302d88c1a5aSDimitry Andric /// LatchBlock. Control may exit the loop prior to TripCount iterations either
303d88c1a5aSDimitry Andric /// via an early branch in other loop block or via LatchBlock terminator. This
304d88c1a5aSDimitry Andric /// is relaxed from the general definition of trip count which is the number of
305d88c1a5aSDimitry Andric /// times the loop header executes. Note that UnrollLoop assumes that the loop
306d88c1a5aSDimitry Andric /// counter test is in LatchBlock in order to remove unnecesssary instances of
307d88c1a5aSDimitry Andric /// the test. If control can exit the loop from the LatchBlock's terminator
308d88c1a5aSDimitry Andric /// prior to TripCount iterations, flag PreserveCondBr needs to be set.
309d88c1a5aSDimitry Andric ///
310d88c1a5aSDimitry Andric /// PreserveCondBr indicates whether the conditional branch of the LatchBlock
311d88c1a5aSDimitry Andric /// needs to be preserved. It is needed when we use trip count upper bound to
312d88c1a5aSDimitry Andric /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
313d88c1a5aSDimitry Andric /// conditional branch needs to be preserved.
3146122f3e6SDimitry Andric ///
3156122f3e6SDimitry Andric /// Similarly, TripMultiple divides the number of times that the LatchBlock may
3166122f3e6SDimitry Andric /// execute without exiting the loop.
3176122f3e6SDimitry Andric ///
318ff0cc061SDimitry Andric /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
319ff0cc061SDimitry Andric /// have a runtime (i.e. not compile time constant) trip count. Unrolling these
320ff0cc061SDimitry Andric /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
321ff0cc061SDimitry Andric /// iterations before branching into the unrolled loop. UnrollLoop will not
322ff0cc061SDimitry Andric /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
323ff0cc061SDimitry Andric /// AllowExpensiveTripCount is false.
324ff0cc061SDimitry Andric ///
325d88c1a5aSDimitry Andric /// If we want to perform PGO-based loop peeling, PeelCount is set to the
326d88c1a5aSDimitry Andric /// number of iterations we want to peel off.
327d88c1a5aSDimitry Andric ///
328f22ef01cSRoman Divacky /// The LoopInfo Analysis that is passed will be kept consistent.
329f22ef01cSRoman Divacky ///
3307d523365SDimitry Andric /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
3317d523365SDimitry Andric /// DominatorTree if they are non-null.
332*b5893f02SDimitry Andric ///
333*b5893f02SDimitry Andric /// If RemainderLoop is non-null, it will receive the remainder loop (if
334*b5893f02SDimitry Andric /// required and not fully unrolled).
UnrollLoop(Loop * L,unsigned Count,unsigned TripCount,bool Force,bool AllowRuntime,bool AllowExpensiveTripCount,bool PreserveCondBr,bool PreserveOnlyFirst,unsigned TripMultiple,unsigned PeelCount,bool UnrollRemainder,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,bool PreserveLCSSA,Loop ** RemainderLoop)3352cab237bSDimitry Andric LoopUnrollResult llvm::UnrollLoop(
3362cab237bSDimitry Andric Loop *L, unsigned Count, unsigned TripCount, bool Force, bool AllowRuntime,
3372cab237bSDimitry Andric bool AllowExpensiveTripCount, bool PreserveCondBr, bool PreserveOnlyFirst,
3382cab237bSDimitry Andric unsigned TripMultiple, unsigned PeelCount, bool UnrollRemainder,
3392cab237bSDimitry Andric LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC,
340*b5893f02SDimitry Andric OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop) {
341d88c1a5aSDimitry Andric
342f22ef01cSRoman Divacky BasicBlock *Preheader = L->getLoopPreheader();
343f22ef01cSRoman Divacky if (!Preheader) {
3444ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
3452cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
346f22ef01cSRoman Divacky }
347f22ef01cSRoman Divacky
348f22ef01cSRoman Divacky BasicBlock *LatchBlock = L->getLoopLatch();
349f22ef01cSRoman Divacky if (!LatchBlock) {
3504ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
3512cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
352f22ef01cSRoman Divacky }
353f22ef01cSRoman Divacky
354dff0c46cSDimitry Andric // Loops with indirectbr cannot be cloned.
355dff0c46cSDimitry Andric if (!L->isSafeToClone()) {
3564ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
3572cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
358dff0c46cSDimitry Andric }
359dff0c46cSDimitry Andric
36051690af2SDimitry Andric // The current loop unroll pass can only unroll loops with a single latch
36151690af2SDimitry Andric // that's a conditional branch exiting the loop.
36251690af2SDimitry Andric // FIXME: The implementation can be extended to work with more complicated
36351690af2SDimitry Andric // cases, e.g. loops with multiple latches.
364f22ef01cSRoman Divacky BasicBlock *Header = L->getHeader();
365f22ef01cSRoman Divacky BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
366f22ef01cSRoman Divacky
367f22ef01cSRoman Divacky if (!BI || BI->isUnconditional()) {
368f22ef01cSRoman Divacky // The loop-rotate pass can be helpful to avoid this in many cases.
3694ba319b5SDimitry Andric LLVM_DEBUG(
3704ba319b5SDimitry Andric dbgs()
3714ba319b5SDimitry Andric << " Can't unroll; loop not terminated by a conditional branch.\n");
3722cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
373f22ef01cSRoman Divacky }
374f22ef01cSRoman Divacky
37551690af2SDimitry Andric auto CheckSuccessors = [&](unsigned S1, unsigned S2) {
37651690af2SDimitry Andric return BI->getSuccessor(S1) == Header && !L->contains(BI->getSuccessor(S2));
37751690af2SDimitry Andric };
37851690af2SDimitry Andric
37951690af2SDimitry Andric if (!CheckSuccessors(0, 1) && !CheckSuccessors(1, 0)) {
3804ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Can't unroll; only loops with one conditional latch"
38151690af2SDimitry Andric " exiting the loop can be unrolled\n");
3822cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
38351690af2SDimitry Andric }
38451690af2SDimitry Andric
3852754fe60SDimitry Andric if (Header->hasAddressTaken()) {
3862754fe60SDimitry Andric // The loop-rotate pass can be helpful to avoid this in many cases.
3874ba319b5SDimitry Andric LLVM_DEBUG(
3884ba319b5SDimitry Andric dbgs() << " Won't unroll loop: address of header block is taken.\n");
3892cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
3902754fe60SDimitry Andric }
3912754fe60SDimitry Andric
392f22ef01cSRoman Divacky if (TripCount != 0)
3934ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
394f22ef01cSRoman Divacky if (TripMultiple != 1)
3954ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
396f22ef01cSRoman Divacky
397f22ef01cSRoman Divacky // Effectively "DCE" unrolled iterations that are beyond the tripcount
398f22ef01cSRoman Divacky // and will never be executed.
399f22ef01cSRoman Divacky if (TripCount != 0 && Count > TripCount)
400f22ef01cSRoman Divacky Count = TripCount;
401f22ef01cSRoman Divacky
402d88c1a5aSDimitry Andric // Don't enter the unroll code if there is nothing to do.
4037a7e6055SDimitry Andric if (TripCount == 0 && Count < 2 && PeelCount == 0) {
4044ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n");
4052cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
4067a7e6055SDimitry Andric }
407dff0c46cSDimitry Andric
408f22ef01cSRoman Divacky assert(Count > 0);
409f22ef01cSRoman Divacky assert(TripMultiple > 0);
410f22ef01cSRoman Divacky assert(TripCount == 0 || TripCount % TripMultiple == 0);
411f22ef01cSRoman Divacky
412f22ef01cSRoman Divacky // Are we eliminating the loop control altogether?
413f22ef01cSRoman Divacky bool CompletelyUnroll = Count == TripCount;
4147d523365SDimitry Andric SmallVector<BasicBlock *, 4> ExitBlocks;
4157d523365SDimitry Andric L->getExitBlocks(ExitBlocks);
4163ca95b02SDimitry Andric std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
4173ca95b02SDimitry Andric
4183ca95b02SDimitry Andric // Go through all exits of L and see if there are any phi-nodes there. We just
4193ca95b02SDimitry Andric // conservatively assume that they're inserted to preserve LCSSA form, which
4203ca95b02SDimitry Andric // means that complete unrolling might break this form. We need to either fix
4213ca95b02SDimitry Andric // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
4223ca95b02SDimitry Andric // now we just recompute LCSSA for the outer loop, but it should be possible
4233ca95b02SDimitry Andric // to fix it in-place.
4243ca95b02SDimitry Andric bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
425d88c1a5aSDimitry Andric any_of(ExitBlocks, [](const BasicBlock *BB) {
426d88c1a5aSDimitry Andric return isa<PHINode>(BB->begin());
427d88c1a5aSDimitry Andric });
428f22ef01cSRoman Divacky
429dff0c46cSDimitry Andric // We assume a run-time trip count if the compiler cannot
430dff0c46cSDimitry Andric // figure out the loop trip count and the unroll-runtime
431dff0c46cSDimitry Andric // flag is specified.
432dff0c46cSDimitry Andric bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
433dff0c46cSDimitry Andric
434d88c1a5aSDimitry Andric assert((!RuntimeTripCount || !PeelCount) &&
435d88c1a5aSDimitry Andric "Did not expect runtime trip-count unrolling "
436d88c1a5aSDimitry Andric "and peeling for the same loop");
437d88c1a5aSDimitry Andric
4384ba319b5SDimitry Andric bool Peeled = false;
4392cab237bSDimitry Andric if (PeelCount) {
4404ba319b5SDimitry Andric Peeled = peelLoop(L, PeelCount, LI, SE, DT, AC, PreserveLCSSA);
4412cab237bSDimitry Andric
4422cab237bSDimitry Andric // Successful peeling may result in a change in the loop preheader/trip
4432cab237bSDimitry Andric // counts. If we later unroll the loop, we want these to be updated.
4442cab237bSDimitry Andric if (Peeled) {
4452cab237bSDimitry Andric BasicBlock *ExitingBlock = L->getExitingBlock();
4462cab237bSDimitry Andric assert(ExitingBlock && "Loop without exiting block?");
4472cab237bSDimitry Andric Preheader = L->getLoopPreheader();
4482cab237bSDimitry Andric TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
4492cab237bSDimitry Andric TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
4502cab237bSDimitry Andric }
4512cab237bSDimitry Andric }
452d88c1a5aSDimitry Andric
4533ca95b02SDimitry Andric // Loops containing convergent instructions must have a count that divides
4543ca95b02SDimitry Andric // their TripMultiple.
4554ba319b5SDimitry Andric LLVM_DEBUG(
4563ca95b02SDimitry Andric {
4573ca95b02SDimitry Andric bool HasConvergent = false;
4583ca95b02SDimitry Andric for (auto &BB : L->blocks())
4593ca95b02SDimitry Andric for (auto &I : *BB)
4603ca95b02SDimitry Andric if (auto CS = CallSite(&I))
4613ca95b02SDimitry Andric HasConvergent |= CS.isConvergent();
4623ca95b02SDimitry Andric assert((!HasConvergent || TripMultiple % Count == 0) &&
4633ca95b02SDimitry Andric "Unroll count must divide trip multiple if loop contains a "
4643ca95b02SDimitry Andric "convergent operation.");
4653ca95b02SDimitry Andric });
466d88c1a5aSDimitry Andric
4677a7e6055SDimitry Andric bool EpilogProfitability =
4687a7e6055SDimitry Andric UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
4697a7e6055SDimitry Andric : isEpilogProfitable(L);
4707a7e6055SDimitry Andric
4713ca95b02SDimitry Andric if (RuntimeTripCount && TripMultiple % Count != 0 &&
4723ca95b02SDimitry Andric !UnrollRuntimeLoopRemainder(L, Count, AllowExpensiveTripCount,
4732cab237bSDimitry Andric EpilogProfitability, UnrollRemainder, LI, SE,
474*b5893f02SDimitry Andric DT, AC, PreserveLCSSA, RemainderLoop)) {
4753ca95b02SDimitry Andric if (Force)
4763ca95b02SDimitry Andric RuntimeTripCount = false;
4777a7e6055SDimitry Andric else {
4784ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
4794ba319b5SDimitry Andric "generated when assuming runtime trip count\n");
4802cab237bSDimitry Andric return LoopUnrollResult::Unmodified;
4813ca95b02SDimitry Andric }
4827a7e6055SDimitry Andric }
483dff0c46cSDimitry Andric
484f22ef01cSRoman Divacky // If we know the trip count, we know the multiple...
485f22ef01cSRoman Divacky unsigned BreakoutTrip = 0;
486f22ef01cSRoman Divacky if (TripCount != 0) {
487f22ef01cSRoman Divacky BreakoutTrip = TripCount % Count;
488f22ef01cSRoman Divacky TripMultiple = 0;
489f22ef01cSRoman Divacky } else {
490f22ef01cSRoman Divacky // Figure out what multiple to use.
491f22ef01cSRoman Divacky BreakoutTrip = TripMultiple =
492f22ef01cSRoman Divacky (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
493f22ef01cSRoman Divacky }
494f22ef01cSRoman Divacky
495d88c1a5aSDimitry Andric using namespace ore;
49691bc56edSDimitry Andric // Report the unrolling decision.
497f22ef01cSRoman Divacky if (CompletelyUnroll) {
4984ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
499f22ef01cSRoman Divacky << " with trip count " << TripCount << "!\n");
5002cab237bSDimitry Andric if (ORE)
5012cab237bSDimitry Andric ORE->emit([&]() {
5022cab237bSDimitry Andric return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
503d88c1a5aSDimitry Andric L->getHeader())
504d88c1a5aSDimitry Andric << "completely unrolled loop with "
5052cab237bSDimitry Andric << NV("UnrollCount", TripCount) << " iterations";
5062cab237bSDimitry Andric });
507d88c1a5aSDimitry Andric } else if (PeelCount) {
5084ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()
509d88c1a5aSDimitry Andric << " with iteration count " << PeelCount << "!\n");
5102cab237bSDimitry Andric if (ORE)
5112cab237bSDimitry Andric ORE->emit([&]() {
5122cab237bSDimitry Andric return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
513d88c1a5aSDimitry Andric L->getHeader())
514d88c1a5aSDimitry Andric << " peeled loop by " << NV("PeelCount", PeelCount)
5152cab237bSDimitry Andric << " iterations";
5162cab237bSDimitry Andric });
517f22ef01cSRoman Divacky } else {
5182cab237bSDimitry Andric auto DiagBuilder = [&]() {
519d88c1a5aSDimitry Andric OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
520d88c1a5aSDimitry Andric L->getHeader());
5212cab237bSDimitry Andric return Diag << "unrolled loop by a factor of "
5222cab237bSDimitry Andric << NV("UnrollCount", Count);
5232cab237bSDimitry Andric };
52491bc56edSDimitry Andric
5254ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
5264ba319b5SDimitry Andric << Count);
527f22ef01cSRoman Divacky if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
5284ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
5292cab237bSDimitry Andric if (ORE)
5302cab237bSDimitry Andric ORE->emit([&]() {
5312cab237bSDimitry Andric return DiagBuilder() << " with a breakout at trip "
5322cab237bSDimitry Andric << NV("BreakoutTrip", BreakoutTrip);
5332cab237bSDimitry Andric });
534f22ef01cSRoman Divacky } else if (TripMultiple != 1) {
5354ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
5362cab237bSDimitry Andric if (ORE)
5372cab237bSDimitry Andric ORE->emit([&]() {
5382cab237bSDimitry Andric return DiagBuilder() << " with " << NV("TripMultiple", TripMultiple)
5392cab237bSDimitry Andric << " trips per branch";
5402cab237bSDimitry Andric });
541dff0c46cSDimitry Andric } else if (RuntimeTripCount) {
5424ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << " with run-time trip count");
5432cab237bSDimitry Andric if (ORE)
5442cab237bSDimitry Andric ORE->emit(
5452cab237bSDimitry Andric [&]() { return DiagBuilder() << " with run-time trip count"; });
546f22ef01cSRoman Divacky }
5474ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "!\n");
548f22ef01cSRoman Divacky }
549f22ef01cSRoman Divacky
5504ba319b5SDimitry Andric // We are going to make changes to this loop. SCEV may be keeping cached info
5514ba319b5SDimitry Andric // about it, in particular about backedge taken count. The changes we make
5524ba319b5SDimitry Andric // are guaranteed to invalidate this information for our loop. It is tempting
5534ba319b5SDimitry Andric // to only invalidate the loop being unrolled, but it is incorrect as long as
5544ba319b5SDimitry Andric // all exiting branches from all inner loops have impact on the outer loops,
5554ba319b5SDimitry Andric // and if something changes inside them then any of outer loops may also
5564ba319b5SDimitry Andric // change. When we forget outermost loop, we also forget all contained loops
5574ba319b5SDimitry Andric // and this is what we need here.
5584ba319b5SDimitry Andric if (SE)
5594ba319b5SDimitry Andric SE->forgetTopmostLoop(L);
5604ba319b5SDimitry Andric
561f22ef01cSRoman Divacky bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
562f22ef01cSRoman Divacky BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
563f22ef01cSRoman Divacky
564f22ef01cSRoman Divacky // For the first iteration of the loop, we should use the precloned values for
565f22ef01cSRoman Divacky // PHI nodes. Insert associations now.
566f22ef01cSRoman Divacky ValueToValueMapTy LastValueMap;
567f22ef01cSRoman Divacky std::vector<PHINode*> OrigPHINode;
568f22ef01cSRoman Divacky for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
5696122f3e6SDimitry Andric OrigPHINode.push_back(cast<PHINode>(I));
570f22ef01cSRoman Divacky }
571f22ef01cSRoman Divacky
572f22ef01cSRoman Divacky std::vector<BasicBlock*> Headers;
573f22ef01cSRoman Divacky std::vector<BasicBlock*> Latches;
574f22ef01cSRoman Divacky Headers.push_back(Header);
575f22ef01cSRoman Divacky Latches.push_back(LatchBlock);
576f22ef01cSRoman Divacky
5776122f3e6SDimitry Andric // The current on-the-fly SSA update requires blocks to be processed in
5786122f3e6SDimitry Andric // reverse postorder so that LastValueMap contains the correct value at each
5796122f3e6SDimitry Andric // exit.
5806122f3e6SDimitry Andric LoopBlocksDFS DFS(L);
5816122f3e6SDimitry Andric DFS.perform(LI);
5826122f3e6SDimitry Andric
5836122f3e6SDimitry Andric // Stash the DFS iterators before adding blocks to the loop.
5846122f3e6SDimitry Andric LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
5856122f3e6SDimitry Andric LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
5866122f3e6SDimitry Andric
5873ca95b02SDimitry Andric std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
588d88c1a5aSDimitry Andric
589d88c1a5aSDimitry Andric // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
590d88c1a5aSDimitry Andric // might break loop-simplified form for these loops (as they, e.g., would
591d88c1a5aSDimitry Andric // share the same exit blocks). We'll keep track of loops for which we can
592d88c1a5aSDimitry Andric // break this so that later we can re-simplify them.
593d88c1a5aSDimitry Andric SmallSetVector<Loop *, 4> LoopsToSimplify;
594d88c1a5aSDimitry Andric for (Loop *SubLoop : *L)
595d88c1a5aSDimitry Andric LoopsToSimplify.insert(SubLoop);
596d88c1a5aSDimitry Andric
5977a7e6055SDimitry Andric if (Header->getParent()->isDebugInfoForProfiling())
5987a7e6055SDimitry Andric for (BasicBlock *BB : L->getBlocks())
5997a7e6055SDimitry Andric for (Instruction &I : *BB)
6002cab237bSDimitry Andric if (!isa<DbgInfoIntrinsic>(&I))
601*b5893f02SDimitry Andric if (const DILocation *DIL = I.getDebugLoc()) {
602*b5893f02SDimitry Andric auto NewDIL = DIL->cloneWithDuplicationFactor(Count);
603*b5893f02SDimitry Andric if (NewDIL)
604*b5893f02SDimitry Andric I.setDebugLoc(NewDIL.getValue());
605*b5893f02SDimitry Andric else
606*b5893f02SDimitry Andric LLVM_DEBUG(dbgs()
607*b5893f02SDimitry Andric << "Failed to create new discriminator: "
608*b5893f02SDimitry Andric << DIL->getFilename() << " Line: " << DIL->getLine());
609*b5893f02SDimitry Andric }
6107a7e6055SDimitry Andric
611f22ef01cSRoman Divacky for (unsigned It = 1; It != Count; ++It) {
612f22ef01cSRoman Divacky std::vector<BasicBlock*> NewBlocks;
61339d628a0SDimitry Andric SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
61439d628a0SDimitry Andric NewLoops[L] = L;
615f22ef01cSRoman Divacky
6166122f3e6SDimitry Andric for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
617ffd1746dSEd Schouten ValueToValueMapTy VMap;
618ffd1746dSEd Schouten BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
619f22ef01cSRoman Divacky Header->getParent()->getBasicBlockList().push_back(New);
620f22ef01cSRoman Divacky
6217a7e6055SDimitry Andric assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
6227a7e6055SDimitry Andric "Header should not be in a sub-loop");
62339d628a0SDimitry Andric // Tell LI about New.
624f1a29dd3SDimitry Andric const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
6254ba319b5SDimitry Andric if (OldLoop)
626f1a29dd3SDimitry Andric LoopsToSimplify.insert(NewLoops[OldLoop]);
62739d628a0SDimitry Andric
628f22ef01cSRoman Divacky if (*BB == Header)
62939d628a0SDimitry Andric // Loop over all of the PHI nodes in the block, changing them to use
63039d628a0SDimitry Andric // the incoming values from the previous block.
6313ca95b02SDimitry Andric for (PHINode *OrigPHI : OrigPHINode) {
6323ca95b02SDimitry Andric PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
633f22ef01cSRoman Divacky Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
634f22ef01cSRoman Divacky if (Instruction *InValI = dyn_cast<Instruction>(InVal))
635f22ef01cSRoman Divacky if (It > 1 && L->contains(InValI))
636f22ef01cSRoman Divacky InVal = LastValueMap[InValI];
6373ca95b02SDimitry Andric VMap[OrigPHI] = InVal;
638f22ef01cSRoman Divacky New->getInstList().erase(NewPHI);
639f22ef01cSRoman Divacky }
640f22ef01cSRoman Divacky
641f22ef01cSRoman Divacky // Update our running map of newest clones
642f22ef01cSRoman Divacky LastValueMap[*BB] = New;
643ffd1746dSEd Schouten for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
644f22ef01cSRoman Divacky VI != VE; ++VI)
645f22ef01cSRoman Divacky LastValueMap[VI->first] = VI->second;
646f22ef01cSRoman Divacky
6476122f3e6SDimitry Andric // Add phi entries for newly created values to all exit blocks.
6483ca95b02SDimitry Andric for (BasicBlock *Succ : successors(*BB)) {
6493ca95b02SDimitry Andric if (L->contains(Succ))
6506122f3e6SDimitry Andric continue;
65130785c0eSDimitry Andric for (PHINode &PHI : Succ->phis()) {
65230785c0eSDimitry Andric Value *Incoming = PHI.getIncomingValueForBlock(*BB);
6536122f3e6SDimitry Andric ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
6546122f3e6SDimitry Andric if (It != LastValueMap.end())
6556122f3e6SDimitry Andric Incoming = It->second;
65630785c0eSDimitry Andric PHI.addIncoming(Incoming, New);
657f22ef01cSRoman Divacky }
6586122f3e6SDimitry Andric }
659f22ef01cSRoman Divacky // Keep track of new headers and latches as we create them, so that
660f22ef01cSRoman Divacky // we can insert the proper branches later.
661f22ef01cSRoman Divacky if (*BB == Header)
662f22ef01cSRoman Divacky Headers.push_back(New);
6636122f3e6SDimitry Andric if (*BB == LatchBlock)
664f22ef01cSRoman Divacky Latches.push_back(New);
665f22ef01cSRoman Divacky
666f22ef01cSRoman Divacky NewBlocks.push_back(New);
6673ca95b02SDimitry Andric UnrolledLoopBlocks.push_back(New);
6683ca95b02SDimitry Andric
6693ca95b02SDimitry Andric // Update DomTree: since we just copy the loop body, and each copy has a
6703ca95b02SDimitry Andric // dedicated entry block (copy of the header block), this header's copy
6713ca95b02SDimitry Andric // dominates all copied blocks. That means, dominance relations in the
6723ca95b02SDimitry Andric // copied body are the same as in the original body.
6733ca95b02SDimitry Andric if (DT) {
6743ca95b02SDimitry Andric if (*BB == Header)
6753ca95b02SDimitry Andric DT->addNewBlock(New, Latches[It - 1]);
6763ca95b02SDimitry Andric else {
6773ca95b02SDimitry Andric auto BBDomNode = DT->getNode(*BB);
6783ca95b02SDimitry Andric auto BBIDom = BBDomNode->getIDom();
6793ca95b02SDimitry Andric BasicBlock *OriginalBBIDom = BBIDom->getBlock();
6803ca95b02SDimitry Andric DT->addNewBlock(
6813ca95b02SDimitry Andric New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
6823ca95b02SDimitry Andric }
6833ca95b02SDimitry Andric }
684f22ef01cSRoman Divacky }
685f22ef01cSRoman Divacky
686f22ef01cSRoman Divacky // Remap all instructions in the most recent iteration
687d88c1a5aSDimitry Andric for (BasicBlock *NewBlock : NewBlocks) {
688d88c1a5aSDimitry Andric for (Instruction &I : *NewBlock) {
6893ca95b02SDimitry Andric ::remapInstruction(&I, LastValueMap);
690d88c1a5aSDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(&I))
691d88c1a5aSDimitry Andric if (II->getIntrinsicID() == Intrinsic::assume)
692d88c1a5aSDimitry Andric AC->registerAssumption(II);
693d88c1a5aSDimitry Andric }
694d88c1a5aSDimitry Andric }
695f22ef01cSRoman Divacky }
696f22ef01cSRoman Divacky
6976122f3e6SDimitry Andric // Loop over the PHI nodes in the original block, setting incoming values.
6983ca95b02SDimitry Andric for (PHINode *PN : OrigPHINode) {
6996122f3e6SDimitry Andric if (CompletelyUnroll) {
7006122f3e6SDimitry Andric PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
7016122f3e6SDimitry Andric Header->getInstList().erase(PN);
7026122f3e6SDimitry Andric }
7036122f3e6SDimitry Andric else if (Count > 1) {
704f22ef01cSRoman Divacky Value *InVal = PN->removeIncomingValue(LatchBlock, false);
705f22ef01cSRoman Divacky // If this value was defined in the loop, take the value defined by the
706f22ef01cSRoman Divacky // last iteration of the loop.
707f22ef01cSRoman Divacky if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
708f22ef01cSRoman Divacky if (L->contains(InValI))
709f22ef01cSRoman Divacky InVal = LastValueMap[InVal];
710f22ef01cSRoman Divacky }
7116122f3e6SDimitry Andric assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
7126122f3e6SDimitry Andric PN->addIncoming(InVal, Latches.back());
713f22ef01cSRoman Divacky }
714f22ef01cSRoman Divacky }
715f22ef01cSRoman Divacky
716f22ef01cSRoman Divacky // Now that all the basic blocks for the unrolled iterations are in place,
717f22ef01cSRoman Divacky // set up the branches to connect them.
718f22ef01cSRoman Divacky for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
719f22ef01cSRoman Divacky // The original branch was replicated in each unrolled iteration.
720f22ef01cSRoman Divacky BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
721f22ef01cSRoman Divacky
722f22ef01cSRoman Divacky // The branch destination.
723f22ef01cSRoman Divacky unsigned j = (i + 1) % e;
724f22ef01cSRoman Divacky BasicBlock *Dest = Headers[j];
725f22ef01cSRoman Divacky bool NeedConditional = true;
726f22ef01cSRoman Divacky
727dff0c46cSDimitry Andric if (RuntimeTripCount && j != 0) {
728dff0c46cSDimitry Andric NeedConditional = false;
729dff0c46cSDimitry Andric }
730dff0c46cSDimitry Andric
731f22ef01cSRoman Divacky // For a complete unroll, make the last iteration end with a branch
732f22ef01cSRoman Divacky // to the exit block.
7337d523365SDimitry Andric if (CompletelyUnroll) {
7347d523365SDimitry Andric if (j == 0)
735f22ef01cSRoman Divacky Dest = LoopExit;
736d88c1a5aSDimitry Andric // If using trip count upper bound to completely unroll, we need to keep
737d88c1a5aSDimitry Andric // the conditional branch except the last one because the loop may exit
738d88c1a5aSDimitry Andric // after any iteration.
739d88c1a5aSDimitry Andric assert(NeedConditional &&
740d88c1a5aSDimitry Andric "NeedCondition cannot be modified by both complete "
741d88c1a5aSDimitry Andric "unrolling and runtime unrolling");
742d88c1a5aSDimitry Andric NeedConditional = (PreserveCondBr && j && !(PreserveOnlyFirst && i != 0));
743d88c1a5aSDimitry Andric } else if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
744f22ef01cSRoman Divacky // If we know the trip count or a multiple of it, we can safely use an
745f22ef01cSRoman Divacky // unconditional branch for some iterations.
746f22ef01cSRoman Divacky NeedConditional = false;
747f22ef01cSRoman Divacky }
748f22ef01cSRoman Divacky
749f22ef01cSRoman Divacky if (NeedConditional) {
750f22ef01cSRoman Divacky // Update the conditional branch's successor for the following
751f22ef01cSRoman Divacky // iteration.
752f22ef01cSRoman Divacky Term->setSuccessor(!ContinueOnTrue, Dest);
753f22ef01cSRoman Divacky } else {
7546122f3e6SDimitry Andric // Remove phi operands at this loop exit
7556122f3e6SDimitry Andric if (Dest != LoopExit) {
7566122f3e6SDimitry Andric BasicBlock *BB = Latches[i];
7573ca95b02SDimitry Andric for (BasicBlock *Succ: successors(BB)) {
7583ca95b02SDimitry Andric if (Succ == Headers[i])
7596122f3e6SDimitry Andric continue;
76030785c0eSDimitry Andric for (PHINode &Phi : Succ->phis())
76130785c0eSDimitry Andric Phi.removeIncomingValue(BB, false);
7626122f3e6SDimitry Andric }
7636122f3e6SDimitry Andric }
7642754fe60SDimitry Andric // Replace the conditional branch with an unconditional one.
7652754fe60SDimitry Andric BranchInst::Create(Dest, Term);
7662754fe60SDimitry Andric Term->eraseFromParent();
767f22ef01cSRoman Divacky }
768f22ef01cSRoman Divacky }
7697a7e6055SDimitry Andric
7703ca95b02SDimitry Andric // Update dominators of blocks we might reach through exits.
7713ca95b02SDimitry Andric // Immediate dominator of such block might change, because we add more
7723ca95b02SDimitry Andric // routes which can lead to the exit: we can now reach it from the copied
7737a7e6055SDimitry Andric // iterations too.
7743ca95b02SDimitry Andric if (DT && Count > 1) {
7753ca95b02SDimitry Andric for (auto *BB : OriginalLoopBlocks) {
7763ca95b02SDimitry Andric auto *BBDomNode = DT->getNode(BB);
7773ca95b02SDimitry Andric SmallVector<BasicBlock *, 16> ChildrenToUpdate;
7783ca95b02SDimitry Andric for (auto *ChildDomNode : BBDomNode->getChildren()) {
7793ca95b02SDimitry Andric auto *ChildBB = ChildDomNode->getBlock();
7803ca95b02SDimitry Andric if (!L->contains(ChildBB))
7813ca95b02SDimitry Andric ChildrenToUpdate.push_back(ChildBB);
7823ca95b02SDimitry Andric }
7837a7e6055SDimitry Andric BasicBlock *NewIDom;
7847a7e6055SDimitry Andric if (BB == LatchBlock) {
7857a7e6055SDimitry Andric // The latch is special because we emit unconditional branches in
7867a7e6055SDimitry Andric // some cases where the original loop contained a conditional branch.
7877a7e6055SDimitry Andric // Since the latch is always at the bottom of the loop, if the latch
7887a7e6055SDimitry Andric // dominated an exit before unrolling, the new dominator of that exit
7897a7e6055SDimitry Andric // must also be a latch. Specifically, the dominator is the first
7907a7e6055SDimitry Andric // latch which ends in a conditional branch, or the last latch if
7917a7e6055SDimitry Andric // there is no such latch.
7927a7e6055SDimitry Andric NewIDom = Latches.back();
7937a7e6055SDimitry Andric for (BasicBlock *IterLatch : Latches) {
794*b5893f02SDimitry Andric Instruction *Term = IterLatch->getTerminator();
7957a7e6055SDimitry Andric if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
7967a7e6055SDimitry Andric NewIDom = IterLatch;
7977a7e6055SDimitry Andric break;
7987a7e6055SDimitry Andric }
7997a7e6055SDimitry Andric }
8007a7e6055SDimitry Andric } else {
8017a7e6055SDimitry Andric // The new idom of the block will be the nearest common dominator
8027a7e6055SDimitry Andric // of all copies of the previous idom. This is equivalent to the
8037a7e6055SDimitry Andric // nearest common dominator of the previous idom and the first latch,
8047a7e6055SDimitry Andric // which dominates all copies of the previous idom.
8057a7e6055SDimitry Andric NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
8067a7e6055SDimitry Andric }
8073ca95b02SDimitry Andric for (auto *ChildBB : ChildrenToUpdate)
8083ca95b02SDimitry Andric DT->changeImmediateDominator(ChildBB, NewIDom);
8093ca95b02SDimitry Andric }
8103ca95b02SDimitry Andric }
81117a519f9SDimitry Andric
8124ba319b5SDimitry Andric assert(!DT || !UnrollVerifyDomtree ||
8134ba319b5SDimitry Andric DT->verify(DominatorTree::VerificationLevel::Fast));
8147a7e6055SDimitry Andric
81517a519f9SDimitry Andric // Merge adjacent basic blocks, if possible.
8163ca95b02SDimitry Andric for (BasicBlock *Latch : Latches) {
8173ca95b02SDimitry Andric BranchInst *Term = cast<BranchInst>(Latch->getTerminator());
81817a519f9SDimitry Andric if (Term->isUnconditional()) {
81917a519f9SDimitry Andric BasicBlock *Dest = Term->getSuccessor(0);
8204ba319b5SDimitry Andric if (BasicBlock *Fold = foldBlockIntoPredecessor(Dest, LI, SE, DT)) {
8213ca95b02SDimitry Andric // Dest has been folded into Fold. Update our worklists accordingly.
82217a519f9SDimitry Andric std::replace(Latches.begin(), Latches.end(), Dest, Fold);
8233ca95b02SDimitry Andric UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
8243ca95b02SDimitry Andric UnrolledLoopBlocks.end(), Dest),
8253ca95b02SDimitry Andric UnrolledLoopBlocks.end());
8263ca95b02SDimitry Andric }
82717a519f9SDimitry Andric }
828f22ef01cSRoman Divacky }
829f22ef01cSRoman Divacky
8304ba319b5SDimitry Andric // At this point, the code is well formed. We now simplify the unrolled loop,
8314ba319b5SDimitry Andric // doing constant propagation and dead code elimination as we go.
8324ba319b5SDimitry Andric simplifyLoopAfterUnroll(L, !CompletelyUnroll && (Count > 1 || Peeled), LI, SE,
8334ba319b5SDimitry Andric DT, AC);
834d88c1a5aSDimitry Andric
835f22ef01cSRoman Divacky NumCompletelyUnrolled += CompletelyUnroll;
836f22ef01cSRoman Divacky ++NumUnrolled;
83791bc56edSDimitry Andric
83891bc56edSDimitry Andric Loop *OuterL = L->getParentLoop();
8397d523365SDimitry Andric // Update LoopInfo if the loop is completely removed.
8407d523365SDimitry Andric if (CompletelyUnroll)
8412cab237bSDimitry Andric LI->erase(L);
842f22ef01cSRoman Divacky
8433ca95b02SDimitry Andric // After complete unrolling most of the blocks should be contained in OuterL.
8443ca95b02SDimitry Andric // However, some of them might happen to be out of OuterL (e.g. if they
8453ca95b02SDimitry Andric // precede a loop exit). In this case we might need to insert PHI nodes in
8463ca95b02SDimitry Andric // order to preserve LCSSA form.
8473ca95b02SDimitry Andric // We don't need to check this if we already know that we need to fix LCSSA
8483ca95b02SDimitry Andric // form.
8493ca95b02SDimitry Andric // TODO: For now we just recompute LCSSA for the outer loop in this case, but
8503ca95b02SDimitry Andric // it should be possible to fix it in-place.
8513ca95b02SDimitry Andric if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
8523ca95b02SDimitry Andric NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
8533ca95b02SDimitry Andric
85491bc56edSDimitry Andric // If we have a pass and a DominatorTree we should re-simplify impacted loops
85591bc56edSDimitry Andric // to ensure subsequent analyses can rely on this form. We want to simplify
85691bc56edSDimitry Andric // at least one layer outside of the loop that was unrolled so that any
85791bc56edSDimitry Andric // changes to the parent loop exposed by the unrolling are considered.
8587d523365SDimitry Andric if (DT) {
85991bc56edSDimitry Andric if (OuterL) {
860d88c1a5aSDimitry Andric // OuterL includes all loops for which we can break loop-simplify, so
861d88c1a5aSDimitry Andric // it's sufficient to simplify only it (it'll recursively simplify inner
862d88c1a5aSDimitry Andric // loops too).
8637a7e6055SDimitry Andric if (NeedToFixLCSSA) {
8647a7e6055SDimitry Andric // LCSSA must be performed on the outermost affected loop. The unrolled
8657a7e6055SDimitry Andric // loop's last loop latch is guaranteed to be in the outermost loop
8662cab237bSDimitry Andric // after LoopInfo's been updated by LoopInfo::erase.
8677a7e6055SDimitry Andric Loop *LatchLoop = LI->getLoopFor(Latches.back());
8687a7e6055SDimitry Andric Loop *FixLCSSALoop = OuterL;
8697a7e6055SDimitry Andric if (!FixLCSSALoop->contains(LatchLoop))
8707a7e6055SDimitry Andric while (FixLCSSALoop->getParentLoop() != LatchLoop)
8717a7e6055SDimitry Andric FixLCSSALoop = FixLCSSALoop->getParentLoop();
8727a7e6055SDimitry Andric
8737a7e6055SDimitry Andric formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
8747a7e6055SDimitry Andric } else if (PreserveLCSSA) {
8757a7e6055SDimitry Andric assert(OuterL->isLCSSAForm(*DT) &&
8767a7e6055SDimitry Andric "Loops should be in LCSSA form after loop-unroll.");
8777a7e6055SDimitry Andric }
8787a7e6055SDimitry Andric
879d88c1a5aSDimitry Andric // TODO: That potentially might be compile-time expensive. We should try
880d88c1a5aSDimitry Andric // to fix the loop-simplified form incrementally.
8813ca95b02SDimitry Andric simplifyLoop(OuterL, DT, LI, SE, AC, PreserveLCSSA);
882d88c1a5aSDimitry Andric } else {
883d88c1a5aSDimitry Andric // Simplify loops for which we might've broken loop-simplify form.
884d88c1a5aSDimitry Andric for (Loop *SubLoop : LoopsToSimplify)
885d88c1a5aSDimitry Andric simplifyLoop(SubLoop, DT, LI, SE, AC, PreserveLCSSA);
88691bc56edSDimitry Andric }
88791bc56edSDimitry Andric }
88891bc56edSDimitry Andric
8892cab237bSDimitry Andric return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
8902cab237bSDimitry Andric : LoopUnrollResult::PartiallyUnrolled;
891f22ef01cSRoman Divacky }
892ff0cc061SDimitry Andric
893ff0cc061SDimitry Andric /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
894ff0cc061SDimitry Andric /// node with the given name (for example, "llvm.loop.unroll.count"). If no
895ff0cc061SDimitry Andric /// such metadata node exists, then nullptr is returned.
GetUnrollMetadata(MDNode * LoopID,StringRef Name)896ff0cc061SDimitry Andric MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
897ff0cc061SDimitry Andric // First operand should refer to the loop id itself.
898ff0cc061SDimitry Andric assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
899ff0cc061SDimitry Andric assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
900ff0cc061SDimitry Andric
901ff0cc061SDimitry Andric for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
902ff0cc061SDimitry Andric MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
903ff0cc061SDimitry Andric if (!MD)
904ff0cc061SDimitry Andric continue;
905ff0cc061SDimitry Andric
906ff0cc061SDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0));
907ff0cc061SDimitry Andric if (!S)
908ff0cc061SDimitry Andric continue;
909ff0cc061SDimitry Andric
910ff0cc061SDimitry Andric if (Name.equals(S->getString()))
911ff0cc061SDimitry Andric return MD;
912ff0cc061SDimitry Andric }
913ff0cc061SDimitry Andric return nullptr;
914ff0cc061SDimitry Andric }
915