176aa662cSKarthik Bhat //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
276aa662cSKarthik Bhat //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
676aa662cSKarthik Bhat //
776aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
876aa662cSKarthik Bhat //
976aa662cSKarthik Bhat // This file defines common loop utility functions.
1076aa662cSKarthik Bhat //
1176aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
1276aa662cSKarthik Bhat 
132f2bd8caSAdam Nemet #include "llvm/Transforms/Utils/LoopUtils.h"
147a87e8f9SFlorian Hahn #include "llvm/ADT/DenseSet.h"
157a87e8f9SFlorian Hahn #include "llvm/ADT/Optional.h"
167a87e8f9SFlorian Hahn #include "llvm/ADT/PriorityWorklist.h"
174a000883SChandler Carruth #include "llvm/ADT/ScopeExit.h"
187a87e8f9SFlorian Hahn #include "llvm/ADT/SetVector.h"
197a87e8f9SFlorian Hahn #include "llvm/ADT/SmallPtrSet.h"
207a87e8f9SFlorian Hahn #include "llvm/ADT/SmallVector.h"
2131088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
2231088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
235f436fc5SRichard Trieu #include "llvm/Analysis/DomTreeUpdater.h"
2431088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
25a21d5f1eSPhilip Reames #include "llvm/Analysis/InstructionSimplify.h"
26616657b3SFlorian Hahn #include "llvm/Analysis/LoopAccessAnalysis.h"
272f2bd8caSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
28c3ccf5d7SIgor Laevsky #include "llvm/Analysis/LoopPass.h"
296da79ce1SAlina Sbirlea #include "llvm/Analysis/MemorySSA.h"
3097468e92SAlina Sbirlea #include "llvm/Analysis/MemorySSAUpdater.h"
3123aed5efSPhilip Reames #include "llvm/Analysis/MustExecute.h"
3245d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
332f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3445d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
356bda14b3SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
36a097bc69SChad Rosier #include "llvm/Analysis/ValueTracking.h"
37744c3c32SDavide Italiano #include "llvm/IR/DIBuilder.h"
3831088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
3976aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
40744c3c32SDavide Italiano #include "llvm/IR/IntrinsicInst.h"
41af7e1588SEvgeniy Brevnov #include "llvm/IR/MDBuilder.h"
4245d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
437a87e8f9SFlorian Hahn #include "llvm/IR/Operator.h"
4476aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
4576aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
4605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
4731088a9dSChandler Carruth #include "llvm/Pass.h"
4876aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
49a097bc69SChad Rosier #include "llvm/Support/KnownBits.h"
504a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
5193175a5cSSjoerd Meijer #include "llvm/Transforms/Utils/Local.h"
52bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
5376aa662cSKarthik Bhat 
5476aa662cSKarthik Bhat using namespace llvm;
5576aa662cSKarthik Bhat using namespace llvm::PatternMatch;
5676aa662cSKarthik Bhat 
57ec7e4a9aSDavid Green static cl::opt<bool> ForceReductionIntrinsic(
58ec7e4a9aSDavid Green     "force-reduction-intrinsics", cl::Hidden,
59ec7e4a9aSDavid Green     cl::desc("Force creating reduction intrinsics for testing."),
60ec7e4a9aSDavid Green     cl::init(false));
61ec7e4a9aSDavid Green 
6276aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
6376aa662cSKarthik Bhat 
6472448525SMichael Kruse static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
654f64f1baSTim Corringham static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
6672448525SMichael Kruse 
674a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
6897468e92SAlina Sbirlea                                    MemorySSAUpdater *MSSAU,
694a000883SChandler Carruth                                    bool PreserveLCSSA) {
704a000883SChandler Carruth   bool Changed = false;
714a000883SChandler Carruth 
724a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
734a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
744a000883SChandler Carruth 
754a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
764a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
774a000883SChandler Carruth            "Must start with an empty predecessors list!");
784a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
794a000883SChandler Carruth 
804a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
814a000883SChandler Carruth     // keep track of the in-loop predecessors.
824a000883SChandler Carruth     bool IsDedicatedExit = true;
834a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
844a000883SChandler Carruth       if (L->contains(PredBB)) {
854a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
864a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
874a000883SChandler Carruth           return false;
88784929d0SCraig Topper         if (isa<CallBrInst>(PredBB->getTerminator()))
89784929d0SCraig Topper           // We cannot rewrite exiting edges from a callbr.
90784929d0SCraig Topper           return false;
914a000883SChandler Carruth 
924a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
934a000883SChandler Carruth       } else {
944a000883SChandler Carruth         IsDedicatedExit = false;
954a000883SChandler Carruth       }
964a000883SChandler Carruth 
974a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
984a000883SChandler Carruth 
994a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
1004a000883SChandler Carruth     if (IsDedicatedExit)
1014a000883SChandler Carruth       return false;
1024a000883SChandler Carruth 
1034a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
10497468e92SAlina Sbirlea         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
1054a000883SChandler Carruth 
1064a000883SChandler Carruth     if (!NewExitBB)
107d34e60caSNicola Zaghen       LLVM_DEBUG(
108d34e60caSNicola Zaghen           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
1094a000883SChandler Carruth                  << *L << "\n");
1104a000883SChandler Carruth     else
111d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
1124a000883SChandler Carruth                         << NewExitBB->getName() << "\n");
1134a000883SChandler Carruth     return true;
1144a000883SChandler Carruth   };
1154a000883SChandler Carruth 
1164a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
1174a000883SChandler Carruth   // them, but only visit each one once.
1184a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
1194a000883SChandler Carruth   for (auto *BB : L->blocks())
1204a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
1214a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
1224a000883SChandler Carruth       if (L->contains(SuccBB))
1234a000883SChandler Carruth         continue;
1244a000883SChandler Carruth 
1254a000883SChandler Carruth       // Visit each exit block exactly once.
1264a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
1274a000883SChandler Carruth         continue;
1284a000883SChandler Carruth 
1294a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
1304a000883SChandler Carruth     }
1314a000883SChandler Carruth 
1324a000883SChandler Carruth   return Changed;
1334a000883SChandler Carruth }
1344a000883SChandler Carruth 
1355f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop.
136c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
137c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
138c5b7b555SAshutosh Nema 
139c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
140c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
141c5b7b555SAshutosh Nema     // be adapted into a pointer.
142c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
143c5b7b555SAshutosh Nema       auto Users = Inst.users();
1440a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
145c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
146c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
147c5b7b555SAshutosh Nema           }))
148c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
149c5b7b555SAshutosh Nema     }
150c5b7b555SAshutosh Nema 
151c5b7b555SAshutosh Nema   return UsedOutside;
152c5b7b555SAshutosh Nema }
15331088a9dSChandler Carruth 
15431088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
15531088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
15631088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
15731088a9dSChandler Carruth   // pass manager, they must also preserve these.
15831088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
15931088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
16031088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
16131088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
16231088a9dSChandler Carruth 
16331088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
16431088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
16531088a9dSChandler Carruth   extern char &LoopSimplifyID;
16631088a9dSChandler Carruth   extern char &LCSSAID;
16731088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
16831088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
16931088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
17031088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
171c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
172c3ccf5d7SIgor Laevsky   // which preserve lcssa form
173c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
174c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
17531088a9dSChandler Carruth 
17631088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
17731088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
17831088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
17931088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
18031088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
18131088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
18231088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
18331088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
18431088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
18531088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
18631088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
18731088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
18831088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
18931088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
1906da79ce1SAlina Sbirlea   // FIXME: When all loop passes preserve MemorySSA, it can be required and
1916da79ce1SAlina Sbirlea   // preserved here instead of the individual handling in each pass.
19231088a9dSChandler Carruth }
19331088a9dSChandler Carruth 
19431088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
19531088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
19631088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
19731088a9dSChandler Carruth /// with:
19831088a9dSChandler Carruth ///
19931088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
20031088a9dSChandler Carruth ///
20131088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
20231088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
20331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
20431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
20531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
206e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
20731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
20831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
20931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
21031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
21131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2126da79ce1SAlina Sbirlea   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
21331088a9dSChandler Carruth }
214963341c8SAdam Nemet 
2153c3a7652SSerguei Katkov /// Create MDNode for input string.
2163c3a7652SSerguei Katkov static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
2173c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2183c3a7652SSerguei Katkov   Metadata *MDs[] = {
2193c3a7652SSerguei Katkov       MDString::get(Context, Name),
2203c3a7652SSerguei Katkov       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
2213c3a7652SSerguei Katkov   return MDNode::get(Context, MDs);
2223c3a7652SSerguei Katkov }
2233c3a7652SSerguei Katkov 
2243c3a7652SSerguei Katkov /// Set input string into loop metadata by keeping other values intact.
2257f8c8095SSerguei Katkov /// If the string is already in loop metadata update value if it is
2267f8c8095SSerguei Katkov /// different.
2277f8c8095SSerguei Katkov void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
2283c3a7652SSerguei Katkov                                    unsigned V) {
2293c3a7652SSerguei Katkov   SmallVector<Metadata *, 4> MDs(1);
2303c3a7652SSerguei Katkov   // If the loop already has metadata, retain it.
2313c3a7652SSerguei Katkov   MDNode *LoopID = TheLoop->getLoopID();
2323c3a7652SSerguei Katkov   if (LoopID) {
2333c3a7652SSerguei Katkov     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2343c3a7652SSerguei Katkov       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
2357f8c8095SSerguei Katkov       // If it is of form key = value, try to parse it.
2367f8c8095SSerguei Katkov       if (Node->getNumOperands() == 2) {
2377f8c8095SSerguei Katkov         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
2387f8c8095SSerguei Katkov         if (S && S->getString().equals(StringMD)) {
2397f8c8095SSerguei Katkov           ConstantInt *IntMD =
2407f8c8095SSerguei Katkov               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
2417f8c8095SSerguei Katkov           if (IntMD && IntMD->getSExtValue() == V)
2427f8c8095SSerguei Katkov             // It is already in place. Do nothing.
2437f8c8095SSerguei Katkov             return;
2447f8c8095SSerguei Katkov           // We need to update the value, so just skip it here and it will
2457f8c8095SSerguei Katkov           // be added after copying other existed nodes.
2467f8c8095SSerguei Katkov           continue;
2477f8c8095SSerguei Katkov         }
2487f8c8095SSerguei Katkov       }
2493c3a7652SSerguei Katkov       MDs.push_back(Node);
2503c3a7652SSerguei Katkov     }
2513c3a7652SSerguei Katkov   }
2523c3a7652SSerguei Katkov   // Add new metadata.
2537f8c8095SSerguei Katkov   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
2543c3a7652SSerguei Katkov   // Replace current metadata node with new one.
2553c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2563c3a7652SSerguei Katkov   MDNode *NewLoopID = MDNode::get(Context, MDs);
2573c3a7652SSerguei Katkov   // Set operand 0 to refer to the loop id itself.
2583c3a7652SSerguei Katkov   NewLoopID->replaceOperandWith(0, NewLoopID);
2593c3a7652SSerguei Katkov   TheLoop->setLoopID(NewLoopID);
2603c3a7652SSerguei Katkov }
2613c3a7652SSerguei Katkov 
26272448525SMichael Kruse /// Find string metadata for loop
26372448525SMichael Kruse ///
26472448525SMichael Kruse /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
26572448525SMichael Kruse /// operand or null otherwise.  If the string metadata is not found return
26672448525SMichael Kruse /// Optional's not-a-value.
267978ba615SMichael Kruse Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
26872448525SMichael Kruse                                                             StringRef Name) {
269978ba615SMichael Kruse   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
27072448525SMichael Kruse   if (!MD)
27172448525SMichael Kruse     return None;
272fe3def7cSAdam Nemet   switch (MD->getNumOperands()) {
273fe3def7cSAdam Nemet   case 1:
274fe3def7cSAdam Nemet     return nullptr;
275fe3def7cSAdam Nemet   case 2:
276fe3def7cSAdam Nemet     return &MD->getOperand(1);
277fe3def7cSAdam Nemet   default:
278fe3def7cSAdam Nemet     llvm_unreachable("loop metadata has 0 or 1 operand");
279963341c8SAdam Nemet   }
280fe3def7cSAdam Nemet }
28172448525SMichael Kruse 
28272448525SMichael Kruse static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
28372448525SMichael Kruse                                                    StringRef Name) {
284978ba615SMichael Kruse   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
285978ba615SMichael Kruse   if (!MD)
286fe3def7cSAdam Nemet     return None;
287978ba615SMichael Kruse   switch (MD->getNumOperands()) {
28872448525SMichael Kruse   case 1:
28972448525SMichael Kruse     // When the value is absent it is interpreted as 'attribute set'.
29072448525SMichael Kruse     return true;
29172448525SMichael Kruse   case 2:
292f9027e55SAlina Sbirlea     if (ConstantInt *IntMD =
293f9027e55SAlina Sbirlea             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
294f9027e55SAlina Sbirlea       return IntMD->getZExtValue();
295f9027e55SAlina Sbirlea     return true;
29672448525SMichael Kruse   }
29772448525SMichael Kruse   llvm_unreachable("unexpected number of options");
29872448525SMichael Kruse }
29972448525SMichael Kruse 
300c7e27538SDavid Green bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
30172448525SMichael Kruse   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
30272448525SMichael Kruse }
30372448525SMichael Kruse 
30471bd59f0SDavid Sherwood Optional<ElementCount>
30571bd59f0SDavid Sherwood llvm::getOptionalElementCountLoopAttribute(Loop *TheLoop) {
30671bd59f0SDavid Sherwood   Optional<int> Width =
30771bd59f0SDavid Sherwood       getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
30871bd59f0SDavid Sherwood 
30971bd59f0SDavid Sherwood   if (Width.hasValue()) {
31071bd59f0SDavid Sherwood     Optional<int> IsScalable = getOptionalIntLoopAttribute(
31171bd59f0SDavid Sherwood         TheLoop, "llvm.loop.vectorize.scalable.enable");
31271bd59f0SDavid Sherwood     return ElementCount::get(*Width,
31371bd59f0SDavid Sherwood                              IsScalable.hasValue() ? *IsScalable : false);
31471bd59f0SDavid Sherwood   }
31571bd59f0SDavid Sherwood 
31671bd59f0SDavid Sherwood   return None;
31771bd59f0SDavid Sherwood }
31871bd59f0SDavid Sherwood 
31972448525SMichael Kruse llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
32072448525SMichael Kruse                                                       StringRef Name) {
32172448525SMichael Kruse   const MDOperand *AttrMD =
32272448525SMichael Kruse       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
32372448525SMichael Kruse   if (!AttrMD)
32472448525SMichael Kruse     return None;
32572448525SMichael Kruse 
32672448525SMichael Kruse   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
32772448525SMichael Kruse   if (!IntMD)
32872448525SMichael Kruse     return None;
32972448525SMichael Kruse 
33072448525SMichael Kruse   return IntMD->getSExtValue();
33172448525SMichael Kruse }
33272448525SMichael Kruse 
33372448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID(
33472448525SMichael Kruse     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
33572448525SMichael Kruse     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
33672448525SMichael Kruse   if (!OrigLoopID) {
33772448525SMichael Kruse     if (AlwaysNew)
33872448525SMichael Kruse       return nullptr;
33972448525SMichael Kruse     return None;
34072448525SMichael Kruse   }
34172448525SMichael Kruse 
34272448525SMichael Kruse   assert(OrigLoopID->getOperand(0) == OrigLoopID);
34372448525SMichael Kruse 
34472448525SMichael Kruse   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
34572448525SMichael Kruse   bool InheritSomeAttrs =
34672448525SMichael Kruse       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
34772448525SMichael Kruse   SmallVector<Metadata *, 8> MDs;
34872448525SMichael Kruse   MDs.push_back(nullptr);
34972448525SMichael Kruse 
35072448525SMichael Kruse   bool Changed = false;
35172448525SMichael Kruse   if (InheritAllAttrs || InheritSomeAttrs) {
35272448525SMichael Kruse     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
35372448525SMichael Kruse       MDNode *Op = cast<MDNode>(Existing.get());
35472448525SMichael Kruse 
35572448525SMichael Kruse       auto InheritThisAttribute = [InheritSomeAttrs,
35672448525SMichael Kruse                                    InheritOptionsExceptPrefix](MDNode *Op) {
35772448525SMichael Kruse         if (!InheritSomeAttrs)
35872448525SMichael Kruse           return false;
35972448525SMichael Kruse 
36072448525SMichael Kruse         // Skip malformatted attribute metadata nodes.
36172448525SMichael Kruse         if (Op->getNumOperands() == 0)
36272448525SMichael Kruse           return true;
36372448525SMichael Kruse         Metadata *NameMD = Op->getOperand(0).get();
36472448525SMichael Kruse         if (!isa<MDString>(NameMD))
36572448525SMichael Kruse           return true;
36672448525SMichael Kruse         StringRef AttrName = cast<MDString>(NameMD)->getString();
36772448525SMichael Kruse 
36872448525SMichael Kruse         // Do not inherit excluded attributes.
36972448525SMichael Kruse         return !AttrName.startswith(InheritOptionsExceptPrefix);
37072448525SMichael Kruse       };
37172448525SMichael Kruse 
37272448525SMichael Kruse       if (InheritThisAttribute(Op))
37372448525SMichael Kruse         MDs.push_back(Op);
37472448525SMichael Kruse       else
37572448525SMichael Kruse         Changed = true;
37672448525SMichael Kruse     }
37772448525SMichael Kruse   } else {
37872448525SMichael Kruse     // Modified if we dropped at least one attribute.
37972448525SMichael Kruse     Changed = OrigLoopID->getNumOperands() > 1;
38072448525SMichael Kruse   }
38172448525SMichael Kruse 
38272448525SMichael Kruse   bool HasAnyFollowup = false;
38372448525SMichael Kruse   for (StringRef OptionName : FollowupOptions) {
384978ba615SMichael Kruse     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
38572448525SMichael Kruse     if (!FollowupNode)
38672448525SMichael Kruse       continue;
38772448525SMichael Kruse 
38872448525SMichael Kruse     HasAnyFollowup = true;
38972448525SMichael Kruse     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
39072448525SMichael Kruse       MDs.push_back(Option.get());
39172448525SMichael Kruse       Changed = true;
39272448525SMichael Kruse     }
39372448525SMichael Kruse   }
39472448525SMichael Kruse 
39572448525SMichael Kruse   // Attributes of the followup loop not specified explicity, so signal to the
39672448525SMichael Kruse   // transformation pass to add suitable attributes.
39772448525SMichael Kruse   if (!AlwaysNew && !HasAnyFollowup)
39872448525SMichael Kruse     return None;
39972448525SMichael Kruse 
40072448525SMichael Kruse   // If no attributes were added or remove, the previous loop Id can be reused.
40172448525SMichael Kruse   if (!AlwaysNew && !Changed)
40272448525SMichael Kruse     return OrigLoopID;
40372448525SMichael Kruse 
40472448525SMichael Kruse   // No attributes is equivalent to having no !llvm.loop metadata at all.
40572448525SMichael Kruse   if (MDs.size() == 1)
40672448525SMichael Kruse     return nullptr;
40772448525SMichael Kruse 
40872448525SMichael Kruse   // Build the new loop ID.
40972448525SMichael Kruse   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
41072448525SMichael Kruse   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
41172448525SMichael Kruse   return FollowupLoopID;
41272448525SMichael Kruse }
41372448525SMichael Kruse 
41472448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) {
41572448525SMichael Kruse   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
41672448525SMichael Kruse }
41772448525SMichael Kruse 
4184f64f1baSTim Corringham bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
4194f64f1baSTim Corringham   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
4204f64f1baSTim Corringham }
4214f64f1baSTim Corringham 
42272448525SMichael Kruse TransformationMode llvm::hasUnrollTransformation(Loop *L) {
42372448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
42472448525SMichael Kruse     return TM_SuppressedByUser;
42572448525SMichael Kruse 
42672448525SMichael Kruse   Optional<int> Count =
42772448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
42872448525SMichael Kruse   if (Count.hasValue())
42972448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
43072448525SMichael Kruse 
43172448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
43272448525SMichael Kruse     return TM_ForcedByUser;
43372448525SMichael Kruse 
43472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
43572448525SMichael Kruse     return TM_ForcedByUser;
43672448525SMichael Kruse 
43772448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
43872448525SMichael Kruse     return TM_Disable;
43972448525SMichael Kruse 
44072448525SMichael Kruse   return TM_Unspecified;
44172448525SMichael Kruse }
44272448525SMichael Kruse 
44372448525SMichael Kruse TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
44472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
44572448525SMichael Kruse     return TM_SuppressedByUser;
44672448525SMichael Kruse 
44772448525SMichael Kruse   Optional<int> Count =
44872448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
44972448525SMichael Kruse   if (Count.hasValue())
45072448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
45172448525SMichael Kruse 
45272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
45372448525SMichael Kruse     return TM_ForcedByUser;
45472448525SMichael Kruse 
45572448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
45672448525SMichael Kruse     return TM_Disable;
45772448525SMichael Kruse 
45872448525SMichael Kruse   return TM_Unspecified;
45972448525SMichael Kruse }
46072448525SMichael Kruse 
46172448525SMichael Kruse TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
46272448525SMichael Kruse   Optional<bool> Enable =
46372448525SMichael Kruse       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
46472448525SMichael Kruse 
46572448525SMichael Kruse   if (Enable == false)
46672448525SMichael Kruse     return TM_SuppressedByUser;
46772448525SMichael Kruse 
46871bd59f0SDavid Sherwood   Optional<ElementCount> VectorizeWidth =
46971bd59f0SDavid Sherwood       getOptionalElementCountLoopAttribute(L);
47072448525SMichael Kruse   Optional<int> InterleaveCount =
47172448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
47272448525SMichael Kruse 
47372448525SMichael Kruse   // 'Forcing' vector width and interleave count to one effectively disables
47472448525SMichael Kruse   // this tranformation.
47571bd59f0SDavid Sherwood   if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
47671bd59f0SDavid Sherwood       InterleaveCount == 1)
47772448525SMichael Kruse     return TM_SuppressedByUser;
47872448525SMichael Kruse 
47972448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
48072448525SMichael Kruse     return TM_Disable;
48172448525SMichael Kruse 
48270560a0aSMichael Kruse   if (Enable == true)
48370560a0aSMichael Kruse     return TM_ForcedByUser;
48470560a0aSMichael Kruse 
48571bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
48672448525SMichael Kruse     return TM_Disable;
48772448525SMichael Kruse 
48871bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
48972448525SMichael Kruse     return TM_Enable;
49072448525SMichael Kruse 
49172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
49272448525SMichael Kruse     return TM_Disable;
49372448525SMichael Kruse 
49472448525SMichael Kruse   return TM_Unspecified;
49572448525SMichael Kruse }
49672448525SMichael Kruse 
49772448525SMichael Kruse TransformationMode llvm::hasDistributeTransformation(Loop *L) {
49872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
49972448525SMichael Kruse     return TM_ForcedByUser;
50072448525SMichael Kruse 
50172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
50272448525SMichael Kruse     return TM_Disable;
50372448525SMichael Kruse 
50472448525SMichael Kruse   return TM_Unspecified;
50572448525SMichael Kruse }
50672448525SMichael Kruse 
50772448525SMichael Kruse TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
50872448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
50972448525SMichael Kruse     return TM_SuppressedByUser;
51072448525SMichael Kruse 
51172448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
51272448525SMichael Kruse     return TM_Disable;
51372448525SMichael Kruse 
51472448525SMichael Kruse   return TM_Unspecified;
515963341c8SAdam Nemet }
516122f984aSEvgeniy Stepanov 
5177ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
5187ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
5197ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
5207ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
5217ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
5227ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
5237ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
5247ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
5257ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
5267ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
5277ed5856aSAlina Sbirlea   };
5287ed5856aSAlina Sbirlea 
5297ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
5307ed5856aSAlina Sbirlea 
53176c5cb05SNicolai Hähnle   for (size_t I = 0; I < Worklist.size(); I++) {
53276c5cb05SNicolai Hähnle     for (DomTreeNode *Child : Worklist[I]->children())
5337ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
53476c5cb05SNicolai Hähnle   }
5357ed5856aSAlina Sbirlea 
5367ed5856aSAlina Sbirlea   return Worklist;
5377ed5856aSAlina Sbirlea }
5387ed5856aSAlina Sbirlea 
539efb130fcSAlina Sbirlea void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
540efb130fcSAlina Sbirlea                           LoopInfo *LI, MemorySSA *MSSA) {
541899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
542df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
543df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
544df3e71e0SMarcello Maggioni 
545efb130fcSAlina Sbirlea   std::unique_ptr<MemorySSAUpdater> MSSAU;
546efb130fcSAlina Sbirlea   if (MSSA)
547efb130fcSAlina Sbirlea     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
548efb130fcSAlina Sbirlea 
549df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
550df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
551df3e71e0SMarcello Maggioni   //
552df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
553df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
554df3e71e0SMarcello Maggioni 
555df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
556df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
557df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
558df3e71e0SMarcello Maggioni   if (SE)
559df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
560df3e71e0SMarcello Maggioni 
561df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
562df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
563df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
564df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
565df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
566df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
567df3e71e0SMarcello Maggioni   // preheader -> header.
568df3e71e0SMarcello Maggioni   //
569df3e71e0SMarcello Maggioni   //
570df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
571df3e71e0SMarcello Maggioni   //        |                    |   |                   |
572df3e71e0SMarcello Maggioni   //        V                    |   V                   |
573df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
574df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
575df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
576df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
577df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
578df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
579df3e71e0SMarcello Maggioni   //
580df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
581df3e71e0SMarcello Maggioni   // update without using the batch update API.
582df3e71e0SMarcello Maggioni   //
583df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
584df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
585df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
586df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
587df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
588df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
589df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
590babc224cSAtmn Patel 
591babc224cSAtmn Patel   auto *ExitBlock = L->getUniqueExitBlock();
592babc224cSAtmn Patel   if (ExitBlock) {
593babc224cSAtmn Patel     assert(ExitBlock && "Should have a unique exit block!");
594babc224cSAtmn Patel     assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
595babc224cSAtmn Patel 
596df3e71e0SMarcello Maggioni     Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
597df3e71e0SMarcello Maggioni     // Remove the old branch. The conditional branch becomes a new terminator.
598df3e71e0SMarcello Maggioni     OldBr->eraseFromParent();
599df3e71e0SMarcello Maggioni 
600df3e71e0SMarcello Maggioni     // Rewrite phis in the exit block to get their inputs from the Preheader
601df3e71e0SMarcello Maggioni     // instead of the exiting block.
602c7fc81e6SBenjamin Kramer     for (PHINode &P : ExitBlock->phis()) {
603df3e71e0SMarcello Maggioni       // Set the zero'th element of Phi to be from the preheader and remove all
604df3e71e0SMarcello Maggioni       // other incoming values. Given the loop has dedicated exits, all other
605df3e71e0SMarcello Maggioni       // incoming values must be from the exiting blocks.
606df3e71e0SMarcello Maggioni       int PredIndex = 0;
607c7fc81e6SBenjamin Kramer       P.setIncomingBlock(PredIndex, Preheader);
608df3e71e0SMarcello Maggioni       // Removes all incoming values from all other exiting blocks (including
609df3e71e0SMarcello Maggioni       // duplicate values from an exiting block).
610df3e71e0SMarcello Maggioni       // Nuke all entries except the zero'th entry which is the preheader entry.
611df3e71e0SMarcello Maggioni       // NOTE! We need to remove Incoming Values in the reverse order as done
612df3e71e0SMarcello Maggioni       // below, to keep the indices valid for deletion (removeIncomingValues
613babc224cSAtmn Patel       // updates getNumIncomingValues and shifts all values down into the
614babc224cSAtmn Patel       // operand being deleted).
615c7fc81e6SBenjamin Kramer       for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
616c7fc81e6SBenjamin Kramer         P.removeIncomingValue(e - i, false);
617df3e71e0SMarcello Maggioni 
618c7fc81e6SBenjamin Kramer       assert((P.getNumIncomingValues() == 1 &&
619c7fc81e6SBenjamin Kramer               P.getIncomingBlock(PredIndex) == Preheader) &&
620df3e71e0SMarcello Maggioni              "Should have exactly one value and that's from the preheader!");
621df3e71e0SMarcello Maggioni     }
622df3e71e0SMarcello Maggioni 
623efb130fcSAlina Sbirlea     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
624efb130fcSAlina Sbirlea     if (DT) {
625efb130fcSAlina Sbirlea       DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
626efb130fcSAlina Sbirlea       if (MSSA) {
627babc224cSAtmn Patel         MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
628babc224cSAtmn Patel                             *DT);
629efb130fcSAlina Sbirlea         if (VerifyMemorySSA)
630efb130fcSAlina Sbirlea           MSSA->verifyMemorySSA();
631efb130fcSAlina Sbirlea       }
632efb130fcSAlina Sbirlea     }
633efb130fcSAlina Sbirlea 
634df3e71e0SMarcello Maggioni     // Disconnect the loop body by branching directly to its exit.
635df3e71e0SMarcello Maggioni     Builder.SetInsertPoint(Preheader->getTerminator());
636df3e71e0SMarcello Maggioni     Builder.CreateBr(ExitBlock);
637df3e71e0SMarcello Maggioni     // Remove the old branch.
638df3e71e0SMarcello Maggioni     Preheader->getTerminator()->eraseFromParent();
639df3e71e0SMarcello Maggioni 
640df3e71e0SMarcello Maggioni     if (DT) {
641efb130fcSAlina Sbirlea       DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
642efb130fcSAlina Sbirlea       if (MSSA) {
643babc224cSAtmn Patel         MSSAU->applyUpdates(
644babc224cSAtmn Patel             {{DominatorTree::Delete, Preheader, L->getHeader()}}, *DT);
645efb130fcSAlina Sbirlea         SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
646efb130fcSAlina Sbirlea                                                      L->block_end());
647efb130fcSAlina Sbirlea         MSSAU->removeBlocks(DeadBlockSet);
648519b019aSAlina Sbirlea         if (VerifyMemorySSA)
649519b019aSAlina Sbirlea           MSSA->verifyMemorySSA();
650efb130fcSAlina Sbirlea       }
651df3e71e0SMarcello Maggioni     }
652babc224cSAtmn Patel   } else {
653babc224cSAtmn Patel     assert(L->hasNoExitBlocks() &&
654babc224cSAtmn Patel            "Loop should have either zero or one exit blocks.");
655babc224cSAtmn Patel     Builder.SetInsertPoint(OldBr);
656babc224cSAtmn Patel     Builder.CreateUnreachable();
657babc224cSAtmn Patel     Preheader->getTerminator()->eraseFromParent();
658babc224cSAtmn Patel   }
659df3e71e0SMarcello Maggioni 
660744c3c32SDavide Italiano   // Use a map to unique and a vector to guarantee deterministic ordering.
6618ee59ca6SDavide Italiano   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
662744c3c32SDavide Italiano   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
663744c3c32SDavide Italiano 
664babc224cSAtmn Patel   if (ExitBlock) {
665a757d65cSSerguei Katkov     // Given LCSSA form is satisfied, we should not have users of instructions
666a757d65cSSerguei Katkov     // within the dead loop outside of the loop. However, LCSSA doesn't take
667a757d65cSSerguei Katkov     // unreachable uses into account. We handle them here.
668a757d65cSSerguei Katkov     // We could do it after drop all references (in this case all users in the
669a757d65cSSerguei Katkov     // loop will be already eliminated and we have less work to do but according
670a757d65cSSerguei Katkov     // to API doc of User::dropAllReferences only valid operation after dropping
671a757d65cSSerguei Katkov     // references, is deletion. So let's substitute all usages of
672a757d65cSSerguei Katkov     // instruction from the loop with undef value of corresponding type first.
673a757d65cSSerguei Katkov     for (auto *Block : L->blocks())
674a757d65cSSerguei Katkov       for (Instruction &I : *Block) {
675a757d65cSSerguei Katkov         auto *Undef = UndefValue::get(I.getType());
676babc224cSAtmn Patel         for (Value::use_iterator UI = I.use_begin(), E = I.use_end();
677babc224cSAtmn Patel              UI != E;) {
678a757d65cSSerguei Katkov           Use &U = *UI;
679a757d65cSSerguei Katkov           ++UI;
680a757d65cSSerguei Katkov           if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
681a757d65cSSerguei Katkov             if (L->contains(Usr->getParent()))
682a757d65cSSerguei Katkov               continue;
683a757d65cSSerguei Katkov           // If we have a DT then we can check that uses outside a loop only in
684a757d65cSSerguei Katkov           // unreachable block.
685a757d65cSSerguei Katkov           if (DT)
686a757d65cSSerguei Katkov             assert(!DT->isReachableFromEntry(U) &&
687a757d65cSSerguei Katkov                    "Unexpected user in reachable block");
688a757d65cSSerguei Katkov           U.set(Undef);
689a757d65cSSerguei Katkov         }
690744c3c32SDavide Italiano         auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
691744c3c32SDavide Italiano         if (!DVI)
692744c3c32SDavide Italiano           continue;
693babc224cSAtmn Patel         auto Key =
694babc224cSAtmn Patel             DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
6958ee59ca6SDavide Italiano         if (Key != DeadDebugSet.end())
696744c3c32SDavide Italiano           continue;
6978ee59ca6SDavide Italiano         DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
698744c3c32SDavide Italiano         DeadDebugInst.push_back(DVI);
699a757d65cSSerguei Katkov       }
700a757d65cSSerguei Katkov 
701744c3c32SDavide Italiano     // After the loop has been deleted all the values defined and modified
702744c3c32SDavide Italiano     // inside the loop are going to be unavailable.
703744c3c32SDavide Italiano     // Since debug values in the loop have been deleted, inserting an undef
704744c3c32SDavide Italiano     // dbg.value truncates the range of any dbg.value before the loop where the
705744c3c32SDavide Italiano     // loop used to be. This is particularly important for constant values.
706744c3c32SDavide Italiano     DIBuilder DIB(*ExitBlock->getModule());
707e5be660eSRoman Lebedev     Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
708e5be660eSRoman Lebedev     assert(InsertDbgValueBefore &&
709e5be660eSRoman Lebedev            "There should be a non-PHI instruction in exit block, else these "
710e5be660eSRoman Lebedev            "instructions will have no parent.");
711744c3c32SDavide Italiano     for (auto *DVI : DeadDebugInst)
712e5be660eSRoman Lebedev       DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
713e5be660eSRoman Lebedev                                   DVI->getVariable(), DVI->getExpression(),
714e5be660eSRoman Lebedev                                   DVI->getDebugLoc(), InsertDbgValueBefore);
715babc224cSAtmn Patel   }
716744c3c32SDavide Italiano 
717df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
718df3e71e0SMarcello Maggioni   // delete it freely later.
719df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
720df3e71e0SMarcello Maggioni     Block->dropAllReferences();
721df3e71e0SMarcello Maggioni 
722efb130fcSAlina Sbirlea   if (MSSA && VerifyMemorySSA)
723efb130fcSAlina Sbirlea     MSSA->verifyMemorySSA();
724efb130fcSAlina Sbirlea 
725df3e71e0SMarcello Maggioni   if (LI) {
726df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
727df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
728df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
729df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
730df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
731df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
732df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
733df3e71e0SMarcello Maggioni 
734df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
735df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
736df3e71e0SMarcello Maggioni 
737df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
738df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
739df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
740df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
741df3e71e0SMarcello Maggioni 
742df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
7439883d7edSWhitney Tsang     // Note: LoopInfo::erase remove the given loop and relink its subloops with
7449883d7edSWhitney Tsang     // its parent. While removeLoop/removeChildLoop remove the given loop but
7459883d7edSWhitney Tsang     // not relink its subloops, which is what we want.
7469883d7edSWhitney Tsang     if (Loop *ParentLoop = L->getParentLoop()) {
7475d6c5b46SWhitney Tsang       Loop::iterator I = find(*ParentLoop, L);
7489883d7edSWhitney Tsang       assert(I != ParentLoop->end() && "Couldn't find loop");
7499883d7edSWhitney Tsang       ParentLoop->removeChildLoop(I);
7509883d7edSWhitney Tsang     } else {
7515d6c5b46SWhitney Tsang       Loop::iterator I = find(*LI, L);
7529883d7edSWhitney Tsang       assert(I != LI->end() && "Couldn't find loop");
7539883d7edSWhitney Tsang       LI->removeLoop(I);
7549883d7edSWhitney Tsang     }
7559883d7edSWhitney Tsang     LI->destroy(L);
756df3e71e0SMarcello Maggioni   }
757df3e71e0SMarcello Maggioni }
758df3e71e0SMarcello Maggioni 
759af7e1588SEvgeniy Brevnov /// Checks if \p L has single exit through latch block except possibly
760af7e1588SEvgeniy Brevnov /// "deoptimizing" exits. Returns branch instruction terminating the loop
761af7e1588SEvgeniy Brevnov /// latch if above check is successful, nullptr otherwise.
762af7e1588SEvgeniy Brevnov static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
76345c43e7dSSerguei Katkov   BasicBlock *Latch = L->getLoopLatch();
76445c43e7dSSerguei Katkov   if (!Latch)
765af7e1588SEvgeniy Brevnov     return nullptr;
766af7e1588SEvgeniy Brevnov 
76745c43e7dSSerguei Katkov   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
76845c43e7dSSerguei Katkov   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
769af7e1588SEvgeniy Brevnov     return nullptr;
77041d72a86SDehao Chen 
77141d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
77241d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
77341d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
77441d72a86SDehao Chen 
77545c43e7dSSerguei Katkov   SmallVector<BasicBlock *, 4> ExitBlocks;
77645c43e7dSSerguei Katkov   L->getUniqueNonLatchExitBlocks(ExitBlocks);
77745c43e7dSSerguei Katkov   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
778eae0d2e9SSerguei Katkov         return !EB->getTerminatingDeoptimizeCall();
77945c43e7dSSerguei Katkov       }))
780af7e1588SEvgeniy Brevnov     return nullptr;
781af7e1588SEvgeniy Brevnov 
782af7e1588SEvgeniy Brevnov   return LatchBR;
783af7e1588SEvgeniy Brevnov }
784af7e1588SEvgeniy Brevnov 
785af7e1588SEvgeniy Brevnov Optional<unsigned>
786af7e1588SEvgeniy Brevnov llvm::getLoopEstimatedTripCount(Loop *L,
787af7e1588SEvgeniy Brevnov                                 unsigned *EstimatedLoopInvocationWeight) {
788af7e1588SEvgeniy Brevnov   // Support loops with an exiting latch and other existing exists only
789af7e1588SEvgeniy Brevnov   // deoptimize.
790af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
791af7e1588SEvgeniy Brevnov   if (!LatchBranch)
79245c43e7dSSerguei Katkov     return None;
79345c43e7dSSerguei Katkov 
79441d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
79541d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
79641d72a86SDehao Chen   // we exited the loop.
797f0abe820SEvgeniy Brevnov   uint64_t BackedgeTakenWeight, LatchExitWeight;
798af7e1588SEvgeniy Brevnov   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
79941d72a86SDehao Chen     return None;
80041d72a86SDehao Chen 
801af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
802f0abe820SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
803f0abe820SEvgeniy Brevnov 
80410357e1cSEvgeniy Brevnov   if (!LatchExitWeight)
80510357e1cSEvgeniy Brevnov     return None;
80641d72a86SDehao Chen 
807af7e1588SEvgeniy Brevnov   if (EstimatedLoopInvocationWeight)
808af7e1588SEvgeniy Brevnov     *EstimatedLoopInvocationWeight = LatchExitWeight;
809af7e1588SEvgeniy Brevnov 
81010357e1cSEvgeniy Brevnov   // Estimated backedge taken count is a ratio of the backedge taken weight by
811cfe97681SEvgeniy Brevnov   // the weight of the edge exiting the loop, rounded to nearest.
81210357e1cSEvgeniy Brevnov   uint64_t BackedgeTakenCount =
81310357e1cSEvgeniy Brevnov       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
81410357e1cSEvgeniy Brevnov   // Estimated trip count is one plus estimated backedge taken count.
81510357e1cSEvgeniy Brevnov   return BackedgeTakenCount + 1;
81641d72a86SDehao Chen }
817cf9daa33SAmara Emerson 
818af7e1588SEvgeniy Brevnov bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
819af7e1588SEvgeniy Brevnov                                      unsigned EstimatedloopInvocationWeight) {
820af7e1588SEvgeniy Brevnov   // Support loops with an exiting latch and other existing exists only
821af7e1588SEvgeniy Brevnov   // deoptimize.
822af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
823af7e1588SEvgeniy Brevnov   if (!LatchBranch)
824af7e1588SEvgeniy Brevnov     return false;
825af7e1588SEvgeniy Brevnov 
826af7e1588SEvgeniy Brevnov   // Calculate taken and exit weights.
827af7e1588SEvgeniy Brevnov   unsigned LatchExitWeight = 0;
828af7e1588SEvgeniy Brevnov   unsigned BackedgeTakenWeight = 0;
829af7e1588SEvgeniy Brevnov 
830af7e1588SEvgeniy Brevnov   if (EstimatedTripCount > 0) {
831af7e1588SEvgeniy Brevnov     LatchExitWeight = EstimatedloopInvocationWeight;
832af7e1588SEvgeniy Brevnov     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
833af7e1588SEvgeniy Brevnov   }
834af7e1588SEvgeniy Brevnov 
835af7e1588SEvgeniy Brevnov   // Make a swap if back edge is taken when condition is "false".
836af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
837af7e1588SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
838af7e1588SEvgeniy Brevnov 
839af7e1588SEvgeniy Brevnov   MDBuilder MDB(LatchBranch->getContext());
840af7e1588SEvgeniy Brevnov 
841af7e1588SEvgeniy Brevnov   // Set/Update profile metadata.
842af7e1588SEvgeniy Brevnov   LatchBranch->setMetadata(
843af7e1588SEvgeniy Brevnov       LLVMContext::MD_prof,
844af7e1588SEvgeniy Brevnov       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
845af7e1588SEvgeniy Brevnov 
846af7e1588SEvgeniy Brevnov   return true;
847af7e1588SEvgeniy Brevnov }
848af7e1588SEvgeniy Brevnov 
8496cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
850395b80cdSDavid Green                                               ScalarEvolution &SE) {
851395b80cdSDavid Green   Loop *OuterL = InnerLoop->getParentLoop();
852395b80cdSDavid Green   if (!OuterL)
853395b80cdSDavid Green     return true;
854395b80cdSDavid Green 
855395b80cdSDavid Green   // Get the backedge taken count for the inner loop
856395b80cdSDavid Green   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
857395b80cdSDavid Green   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
858395b80cdSDavid Green   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
859395b80cdSDavid Green       !InnerLoopBECountSC->getType()->isIntegerTy())
860395b80cdSDavid Green     return false;
861395b80cdSDavid Green 
862395b80cdSDavid Green   // Get whether count is invariant to the outer loop
863395b80cdSDavid Green   ScalarEvolution::LoopDisposition LD =
864395b80cdSDavid Green       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
865395b80cdSDavid Green   if (LD != ScalarEvolution::LoopInvariant)
866395b80cdSDavid Green     return false;
867395b80cdSDavid Green 
868395b80cdSDavid Green   return true;
869395b80cdSDavid Green }
870395b80cdSDavid Green 
87128ffe38bSNikita Popov Value *llvm::createMinMaxOp(IRBuilderBase &Builder,
8726594dc37SVikram TV                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
8736594dc37SVikram TV                             Value *Left, Value *Right) {
8746594dc37SVikram TV   CmpInst::Predicate P = CmpInst::ICMP_NE;
8756594dc37SVikram TV   switch (RK) {
8766594dc37SVikram TV   default:
8776594dc37SVikram TV     llvm_unreachable("Unknown min/max recurrence kind");
8786594dc37SVikram TV   case RecurrenceDescriptor::MRK_UIntMin:
8796594dc37SVikram TV     P = CmpInst::ICMP_ULT;
8806594dc37SVikram TV     break;
8816594dc37SVikram TV   case RecurrenceDescriptor::MRK_UIntMax:
8826594dc37SVikram TV     P = CmpInst::ICMP_UGT;
8836594dc37SVikram TV     break;
8846594dc37SVikram TV   case RecurrenceDescriptor::MRK_SIntMin:
8856594dc37SVikram TV     P = CmpInst::ICMP_SLT;
8866594dc37SVikram TV     break;
8876594dc37SVikram TV   case RecurrenceDescriptor::MRK_SIntMax:
8886594dc37SVikram TV     P = CmpInst::ICMP_SGT;
8896594dc37SVikram TV     break;
8906594dc37SVikram TV   case RecurrenceDescriptor::MRK_FloatMin:
8916594dc37SVikram TV     P = CmpInst::FCMP_OLT;
8926594dc37SVikram TV     break;
8936594dc37SVikram TV   case RecurrenceDescriptor::MRK_FloatMax:
8946594dc37SVikram TV     P = CmpInst::FCMP_OGT;
8956594dc37SVikram TV     break;
8966594dc37SVikram TV   }
8976594dc37SVikram TV 
8986594dc37SVikram TV   // We only match FP sequences that are 'fast', so we can unconditionally
8996594dc37SVikram TV   // set it on any generated instructions.
90028ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFG(Builder);
9016594dc37SVikram TV   FastMathFlags FMF;
9026594dc37SVikram TV   FMF.setFast();
9036594dc37SVikram TV   Builder.setFastMathFlags(FMF);
90446a285adSSanjay Patel   Value *Cmp = Builder.CreateCmp(P, Left, Right, "rdx.minmax.cmp");
9056594dc37SVikram TV   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
9066594dc37SVikram TV   return Select;
9076594dc37SVikram TV }
9086594dc37SVikram TV 
90923c2182cSSimon Pilgrim // Helper to generate an ordered reduction.
91023c2182cSSimon Pilgrim Value *
91128ffe38bSNikita Popov llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
91223c2182cSSimon Pilgrim                           unsigned Op,
91323c2182cSSimon Pilgrim                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
91423c2182cSSimon Pilgrim                           ArrayRef<Value *> RedOps) {
9158d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
91623c2182cSSimon Pilgrim 
91723c2182cSSimon Pilgrim   // Extract and apply reduction ops in ascending order:
91823c2182cSSimon Pilgrim   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
91923c2182cSSimon Pilgrim   Value *Result = Acc;
92023c2182cSSimon Pilgrim   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
92123c2182cSSimon Pilgrim     Value *Ext =
92223c2182cSSimon Pilgrim         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
92323c2182cSSimon Pilgrim 
92423c2182cSSimon Pilgrim     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
92523c2182cSSimon Pilgrim       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
92623c2182cSSimon Pilgrim                                    "bin.rdx");
92723c2182cSSimon Pilgrim     } else {
92823c2182cSSimon Pilgrim       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
92923c2182cSSimon Pilgrim              "Invalid min/max");
9306594dc37SVikram TV       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
93123c2182cSSimon Pilgrim     }
93223c2182cSSimon Pilgrim 
93323c2182cSSimon Pilgrim     if (!RedOps.empty())
93423c2182cSSimon Pilgrim       propagateIRFlags(Result, RedOps);
93523c2182cSSimon Pilgrim   }
93623c2182cSSimon Pilgrim 
93723c2182cSSimon Pilgrim   return Result;
93823c2182cSSimon Pilgrim }
93923c2182cSSimon Pilgrim 
940cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
941836b0f48SAmara Emerson Value *
94228ffe38bSNikita Popov llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op,
943836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
944ad62a3a2SSanjay Patel                           ArrayRef<Value *> RedOps) {
9458d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
946cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
947cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
948cf9daa33SAmara Emerson   // round.
949cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
950cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
951cf9daa33SAmara Emerson   Value *TmpVec = Src;
9526f64dacaSBenjamin Kramer   SmallVector<int, 32> ShuffleMask(VF);
953cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
954cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
955cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
9566f64dacaSBenjamin Kramer       ShuffleMask[j] = i / 2 + j;
957cf9daa33SAmara Emerson 
958cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
9596f64dacaSBenjamin Kramer     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
960cf9daa33SAmara Emerson 
961cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
9626f64dacaSBenjamin Kramer         TmpVec, UndefValue::get(TmpVec->getType()), ShuffleMask, "rdx.shuf");
963cf9daa33SAmara Emerson 
964cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
965ad62a3a2SSanjay Patel       // The builder propagates its fast-math-flags setting.
966ad62a3a2SSanjay Patel       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
967ad62a3a2SSanjay Patel                                    "bin.rdx");
968cf9daa33SAmara Emerson     } else {
969cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
970cf9daa33SAmara Emerson              "Invalid min/max");
9716594dc37SVikram TV       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
972cf9daa33SAmara Emerson     }
973cf9daa33SAmara Emerson     if (!RedOps.empty())
974cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
975bc1148e7SSanjay Patel 
976bc1148e7SSanjay Patel     // We may compute the reassociated scalar ops in a way that does not
977bc1148e7SSanjay Patel     // preserve nsw/nuw etc. Conservatively, drop those flags.
978bc1148e7SSanjay Patel     if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec))
979bc1148e7SSanjay Patel       ReductionInst->dropPoisonGeneratingFlags();
980cf9daa33SAmara Emerson   }
981cf9daa33SAmara Emerson   // The result is in the first element of the vector.
982cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
983cf9daa33SAmara Emerson }
984cf9daa33SAmara Emerson 
985cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
986cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
987cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
98828ffe38bSNikita Popov     IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
989ad62a3a2SSanjay Patel     Value *Src, TargetTransformInfo::ReductionFlags Flags,
990cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
99100a10324SChristopher Tetreault   auto *SrcVTy = cast<VectorType>(Src->getType());
992cf9daa33SAmara Emerson 
993cf9daa33SAmara Emerson   std::function<Value *()> BuildFunc;
994cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
995cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
996cf9daa33SAmara Emerson 
997cf9daa33SAmara Emerson   switch (Opcode) {
998cf9daa33SAmara Emerson   case Instruction::Add:
999cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1000cf9daa33SAmara Emerson     break;
1001cf9daa33SAmara Emerson   case Instruction::Mul:
1002cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1003cf9daa33SAmara Emerson     break;
1004cf9daa33SAmara Emerson   case Instruction::And:
1005cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1006cf9daa33SAmara Emerson     break;
1007cf9daa33SAmara Emerson   case Instruction::Or:
1008cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1009cf9daa33SAmara Emerson     break;
1010cf9daa33SAmara Emerson   case Instruction::Xor:
1011cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1012cf9daa33SAmara Emerson     break;
1013cf9daa33SAmara Emerson   case Instruction::FAdd:
1014cf9daa33SAmara Emerson     BuildFunc = [&]() {
1015cbeb563cSSander de Smalen       auto Rdx = Builder.CreateFAddReduce(
101620b386aaSNikita Popov           ConstantFP::getNegativeZero(SrcVTy->getElementType()), Src);
1017cf9daa33SAmara Emerson       return Rdx;
1018cf9daa33SAmara Emerson     };
1019cf9daa33SAmara Emerson     break;
1020cf9daa33SAmara Emerson   case Instruction::FMul:
1021cf9daa33SAmara Emerson     BuildFunc = [&]() {
102200a10324SChristopher Tetreault       Type *Ty = SrcVTy->getElementType();
1023cbeb563cSSander de Smalen       auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
1024cf9daa33SAmara Emerson       return Rdx;
1025cf9daa33SAmara Emerson     };
1026cf9daa33SAmara Emerson     break;
1027cf9daa33SAmara Emerson   case Instruction::ICmp:
1028cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1029cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1030cf9daa33SAmara Emerson       BuildFunc = [&]() {
1031cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1032cf9daa33SAmara Emerson       };
1033cf9daa33SAmara Emerson     } else {
1034cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1035cf9daa33SAmara Emerson       BuildFunc = [&]() {
1036cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1037cf9daa33SAmara Emerson       };
1038cf9daa33SAmara Emerson     }
1039cf9daa33SAmara Emerson     break;
1040cf9daa33SAmara Emerson   case Instruction::FCmp:
1041cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1042cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
1043cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1044cf9daa33SAmara Emerson     } else {
1045cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
1046cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1047cf9daa33SAmara Emerson     }
1048cf9daa33SAmara Emerson     break;
1049cf9daa33SAmara Emerson   default:
1050cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1051cf9daa33SAmara Emerson     break;
1052cf9daa33SAmara Emerson   }
1053ec7e4a9aSDavid Green   if (ForceReductionIntrinsic ||
1054ec7e4a9aSDavid Green       TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1055cf9daa33SAmara Emerson     return BuildFunc();
1056ad62a3a2SSanjay Patel   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1057cf9daa33SAmara Emerson }
1058cf9daa33SAmara Emerson 
1059cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
106028ffe38bSNikita Popov Value *llvm::createTargetReduction(IRBuilderBase &B,
1061cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
1062cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
1063cf9daa33SAmara Emerson                                    bool NoNaN) {
1064cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
10653e069f57SSanjay Patel   using RD = RecurrenceDescriptor;
1066cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
1067cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
1068ad62a3a2SSanjay Patel 
1069ad62a3a2SSanjay Patel   // All ops in the reduction inherit fast-math-flags from the recurrence
1070ad62a3a2SSanjay Patel   // descriptor.
107128ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1072ad62a3a2SSanjay Patel   B.setFastMathFlags(Desc.getFastMathFlags());
1073ad62a3a2SSanjay Patel 
10743e069f57SSanjay Patel   RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
1075*8d18bc8eSSanjay Patel   Flags.IsMaxOp = MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax ||
1076*8d18bc8eSSanjay Patel                   MMKind == RD::MRK_FloatMax;
1077*8d18bc8eSSanjay Patel   Flags.IsSigned = MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin;
1078*8d18bc8eSSanjay Patel   return createSimpleTargetReduction(B, TTI, Desc.getRecurrenceBinOp(), Src,
1079*8d18bc8eSSanjay Patel                                      Flags);
1080cf9daa33SAmara Emerson }
1081cf9daa33SAmara Emerson 
1082a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1083a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1084a61f4b89SDinar Temirbulatov   if (!VecOp)
1085a61f4b89SDinar Temirbulatov     return;
1086a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1087a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1088a61f4b89SDinar Temirbulatov   if (!Intersection)
1089a61f4b89SDinar Temirbulatov     return;
1090a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1091a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1092a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1093a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1094a61f4b89SDinar Temirbulatov     if (!Instr)
1095a61f4b89SDinar Temirbulatov       continue;
1096a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1097a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1098cf9daa33SAmara Emerson   }
1099cf9daa33SAmara Emerson }
1100a78dc4d6SMax Kazantsev 
1101a78dc4d6SMax Kazantsev bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1102a78dc4d6SMax Kazantsev                                  ScalarEvolution &SE) {
1103a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1104a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1105a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1106a78dc4d6SMax Kazantsev }
1107a78dc4d6SMax Kazantsev 
1108a78dc4d6SMax Kazantsev bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1109a78dc4d6SMax Kazantsev                                     ScalarEvolution &SE) {
1110a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1111a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1112a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1113a78dc4d6SMax Kazantsev }
1114a78dc4d6SMax Kazantsev 
1115a78dc4d6SMax Kazantsev bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1116a78dc4d6SMax Kazantsev                              bool Signed) {
1117a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1118a78dc4d6SMax Kazantsev   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1119a78dc4d6SMax Kazantsev     APInt::getMinValue(BitWidth);
1120a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1121a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1122a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1123a78dc4d6SMax Kazantsev                                      SE.getConstant(Min));
1124a78dc4d6SMax Kazantsev }
1125a78dc4d6SMax Kazantsev 
1126a78dc4d6SMax Kazantsev bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1127a78dc4d6SMax Kazantsev                              bool Signed) {
1128a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1129a78dc4d6SMax Kazantsev   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1130a78dc4d6SMax Kazantsev     APInt::getMaxValue(BitWidth);
1131a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1132a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1133a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1134a78dc4d6SMax Kazantsev                                      SE.getConstant(Max));
1135a78dc4d6SMax Kazantsev }
113693175a5cSSjoerd Meijer 
113793175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
113893175a5cSSjoerd Meijer // rewriteLoopExitValues - Optimize IV users outside the loop.
113993175a5cSSjoerd Meijer // As a side effect, reduces the amount of IV processing within the loop.
114093175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
114193175a5cSSjoerd Meijer 
114293175a5cSSjoerd Meijer // Return true if the SCEV expansion generated by the rewriter can replace the
114393175a5cSSjoerd Meijer // original value. SCEV guarantees that it produces the same value, but the way
114493175a5cSSjoerd Meijer // it is produced may be illegal IR.  Ideally, this function will only be
114593175a5cSSjoerd Meijer // called for verification.
114693175a5cSSjoerd Meijer static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) {
114793175a5cSSjoerd Meijer   // If an SCEV expression subsumed multiple pointers, its expansion could
114893175a5cSSjoerd Meijer   // reassociate the GEP changing the base pointer. This is illegal because the
114993175a5cSSjoerd Meijer   // final address produced by a GEP chain must be inbounds relative to its
115093175a5cSSjoerd Meijer   // underlying object. Otherwise basic alias analysis, among other things,
115193175a5cSSjoerd Meijer   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
115293175a5cSSjoerd Meijer   // producing an expression involving multiple pointers. Until then, we must
115393175a5cSSjoerd Meijer   // bail out here.
115493175a5cSSjoerd Meijer   //
115589051ebaSVitaly Buka   // Retrieve the pointer operand of the GEP. Don't use getUnderlyingObject
115693175a5cSSjoerd Meijer   // because it understands lcssa phis while SCEV does not.
115793175a5cSSjoerd Meijer   Value *FromPtr = FromVal;
115893175a5cSSjoerd Meijer   Value *ToPtr = ToVal;
115993175a5cSSjoerd Meijer   if (auto *GEP = dyn_cast<GEPOperator>(FromVal))
116093175a5cSSjoerd Meijer     FromPtr = GEP->getPointerOperand();
116193175a5cSSjoerd Meijer 
116293175a5cSSjoerd Meijer   if (auto *GEP = dyn_cast<GEPOperator>(ToVal))
116393175a5cSSjoerd Meijer     ToPtr = GEP->getPointerOperand();
116493175a5cSSjoerd Meijer 
116593175a5cSSjoerd Meijer   if (FromPtr != FromVal || ToPtr != ToVal) {
116693175a5cSSjoerd Meijer     // Quickly check the common case
116793175a5cSSjoerd Meijer     if (FromPtr == ToPtr)
116893175a5cSSjoerd Meijer       return true;
116993175a5cSSjoerd Meijer 
117093175a5cSSjoerd Meijer     // SCEV may have rewritten an expression that produces the GEP's pointer
117193175a5cSSjoerd Meijer     // operand. That's ok as long as the pointer operand has the same base
117289051ebaSVitaly Buka     // pointer. Unlike getUnderlyingObject(), getPointerBase() will find the
117393175a5cSSjoerd Meijer     // base of a recurrence. This handles the case in which SCEV expansion
117493175a5cSSjoerd Meijer     // converts a pointer type recurrence into a nonrecurrent pointer base
117593175a5cSSjoerd Meijer     // indexed by an integer recurrence.
117693175a5cSSjoerd Meijer 
117793175a5cSSjoerd Meijer     // If the GEP base pointer is a vector of pointers, abort.
117893175a5cSSjoerd Meijer     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
117993175a5cSSjoerd Meijer       return false;
118093175a5cSSjoerd Meijer 
118193175a5cSSjoerd Meijer     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
118293175a5cSSjoerd Meijer     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
118393175a5cSSjoerd Meijer     if (FromBase == ToBase)
118493175a5cSSjoerd Meijer       return true;
118593175a5cSSjoerd Meijer 
118693175a5cSSjoerd Meijer     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out "
118793175a5cSSjoerd Meijer                       << *FromBase << " != " << *ToBase << "\n");
118893175a5cSSjoerd Meijer 
118993175a5cSSjoerd Meijer     return false;
119093175a5cSSjoerd Meijer   }
119193175a5cSSjoerd Meijer   return true;
119293175a5cSSjoerd Meijer }
119393175a5cSSjoerd Meijer 
119493175a5cSSjoerd Meijer static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
119593175a5cSSjoerd Meijer   SmallPtrSet<const Instruction *, 8> Visited;
119693175a5cSSjoerd Meijer   SmallVector<const Instruction *, 8> WorkList;
119793175a5cSSjoerd Meijer   Visited.insert(I);
119893175a5cSSjoerd Meijer   WorkList.push_back(I);
119993175a5cSSjoerd Meijer   while (!WorkList.empty()) {
120093175a5cSSjoerd Meijer     const Instruction *Curr = WorkList.pop_back_val();
120193175a5cSSjoerd Meijer     // This use is outside the loop, nothing to do.
120293175a5cSSjoerd Meijer     if (!L->contains(Curr))
120393175a5cSSjoerd Meijer       continue;
120493175a5cSSjoerd Meijer     // Do we assume it is a "hard" use which will not be eliminated easily?
120593175a5cSSjoerd Meijer     if (Curr->mayHaveSideEffects())
120693175a5cSSjoerd Meijer       return true;
120793175a5cSSjoerd Meijer     // Otherwise, add all its users to worklist.
120893175a5cSSjoerd Meijer     for (auto U : Curr->users()) {
120993175a5cSSjoerd Meijer       auto *UI = cast<Instruction>(U);
121093175a5cSSjoerd Meijer       if (Visited.insert(UI).second)
121193175a5cSSjoerd Meijer         WorkList.push_back(UI);
121293175a5cSSjoerd Meijer     }
121393175a5cSSjoerd Meijer   }
121493175a5cSSjoerd Meijer   return false;
121593175a5cSSjoerd Meijer }
121693175a5cSSjoerd Meijer 
121793175a5cSSjoerd Meijer // Collect information about PHI nodes which can be transformed in
121893175a5cSSjoerd Meijer // rewriteLoopExitValues.
121993175a5cSSjoerd Meijer struct RewritePhi {
1220b2df9612SRoman Lebedev   PHINode *PN;               // For which PHI node is this replacement?
1221b2df9612SRoman Lebedev   unsigned Ith;              // For which incoming value?
1222b2df9612SRoman Lebedev   const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1223b2df9612SRoman Lebedev   Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1224b2df9612SRoman Lebedev   bool HighCost;               // Is this expansion a high-cost?
122593175a5cSSjoerd Meijer 
1226b2df9612SRoman Lebedev   Value *Expansion = nullptr;
1227b2df9612SRoman Lebedev   bool ValidRewrite = false;
1228b2df9612SRoman Lebedev 
1229b2df9612SRoman Lebedev   RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1230b2df9612SRoman Lebedev              bool H)
1231b2df9612SRoman Lebedev       : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1232b2df9612SRoman Lebedev         HighCost(H) {}
123393175a5cSSjoerd Meijer };
123493175a5cSSjoerd Meijer 
123593175a5cSSjoerd Meijer // Check whether it is possible to delete the loop after rewriting exit
123693175a5cSSjoerd Meijer // value. If it is possible, ignore ReplaceExitValue and do rewriting
123793175a5cSSjoerd Meijer // aggressively.
123893175a5cSSjoerd Meijer static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
123993175a5cSSjoerd Meijer   BasicBlock *Preheader = L->getLoopPreheader();
124093175a5cSSjoerd Meijer   // If there is no preheader, the loop will not be deleted.
124193175a5cSSjoerd Meijer   if (!Preheader)
124293175a5cSSjoerd Meijer     return false;
124393175a5cSSjoerd Meijer 
124493175a5cSSjoerd Meijer   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
124593175a5cSSjoerd Meijer   // We obviate multiple ExitingBlocks case for simplicity.
124693175a5cSSjoerd Meijer   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
124793175a5cSSjoerd Meijer   // after exit value rewriting, we can enhance the logic here.
124893175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 4> ExitingBlocks;
124993175a5cSSjoerd Meijer   L->getExitingBlocks(ExitingBlocks);
125093175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 8> ExitBlocks;
125193175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
125293175a5cSSjoerd Meijer   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
125393175a5cSSjoerd Meijer     return false;
125493175a5cSSjoerd Meijer 
125593175a5cSSjoerd Meijer   BasicBlock *ExitBlock = ExitBlocks[0];
125693175a5cSSjoerd Meijer   BasicBlock::iterator BI = ExitBlock->begin();
125793175a5cSSjoerd Meijer   while (PHINode *P = dyn_cast<PHINode>(BI)) {
125893175a5cSSjoerd Meijer     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
125993175a5cSSjoerd Meijer 
126093175a5cSSjoerd Meijer     // If the Incoming value of P is found in RewritePhiSet, we know it
126193175a5cSSjoerd Meijer     // could be rewritten to use a loop invariant value in transformation
126293175a5cSSjoerd Meijer     // phase later. Skip it in the loop invariant check below.
126393175a5cSSjoerd Meijer     bool found = false;
126493175a5cSSjoerd Meijer     for (const RewritePhi &Phi : RewritePhiSet) {
1265b2df9612SRoman Lebedev       if (!Phi.ValidRewrite)
1266b2df9612SRoman Lebedev         continue;
126793175a5cSSjoerd Meijer       unsigned i = Phi.Ith;
126893175a5cSSjoerd Meijer       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
126993175a5cSSjoerd Meijer         found = true;
127093175a5cSSjoerd Meijer         break;
127193175a5cSSjoerd Meijer       }
127293175a5cSSjoerd Meijer     }
127393175a5cSSjoerd Meijer 
127493175a5cSSjoerd Meijer     Instruction *I;
127593175a5cSSjoerd Meijer     if (!found && (I = dyn_cast<Instruction>(Incoming)))
127693175a5cSSjoerd Meijer       if (!L->hasLoopInvariantOperands(I))
127793175a5cSSjoerd Meijer         return false;
127893175a5cSSjoerd Meijer 
127993175a5cSSjoerd Meijer     ++BI;
128093175a5cSSjoerd Meijer   }
128193175a5cSSjoerd Meijer 
128293175a5cSSjoerd Meijer   for (auto *BB : L->blocks())
128393175a5cSSjoerd Meijer     if (llvm::any_of(*BB, [](Instruction &I) {
128493175a5cSSjoerd Meijer           return I.mayHaveSideEffects();
128593175a5cSSjoerd Meijer         }))
128693175a5cSSjoerd Meijer       return false;
128793175a5cSSjoerd Meijer 
128893175a5cSSjoerd Meijer   return true;
128993175a5cSSjoerd Meijer }
129093175a5cSSjoerd Meijer 
12910789f280SRoman Lebedev int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
12920789f280SRoman Lebedev                                 ScalarEvolution *SE,
12930789f280SRoman Lebedev                                 const TargetTransformInfo *TTI,
12940789f280SRoman Lebedev                                 SCEVExpander &Rewriter, DominatorTree *DT,
12950789f280SRoman Lebedev                                 ReplaceExitVal ReplaceExitValue,
129693175a5cSSjoerd Meijer                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
129793175a5cSSjoerd Meijer   // Check a pre-condition.
129893175a5cSSjoerd Meijer   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
129993175a5cSSjoerd Meijer          "Indvars did not preserve LCSSA!");
130093175a5cSSjoerd Meijer 
130193175a5cSSjoerd Meijer   SmallVector<BasicBlock*, 8> ExitBlocks;
130293175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
130393175a5cSSjoerd Meijer 
130493175a5cSSjoerd Meijer   SmallVector<RewritePhi, 8> RewritePhiSet;
130593175a5cSSjoerd Meijer   // Find all values that are computed inside the loop, but used outside of it.
130693175a5cSSjoerd Meijer   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
130793175a5cSSjoerd Meijer   // the exit blocks of the loop to find them.
130893175a5cSSjoerd Meijer   for (BasicBlock *ExitBB : ExitBlocks) {
130993175a5cSSjoerd Meijer     // If there are no PHI nodes in this exit block, then no values defined
131093175a5cSSjoerd Meijer     // inside the loop are used on this path, skip it.
131193175a5cSSjoerd Meijer     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
131293175a5cSSjoerd Meijer     if (!PN) continue;
131393175a5cSSjoerd Meijer 
131493175a5cSSjoerd Meijer     unsigned NumPreds = PN->getNumIncomingValues();
131593175a5cSSjoerd Meijer 
131693175a5cSSjoerd Meijer     // Iterate over all of the PHI nodes.
131793175a5cSSjoerd Meijer     BasicBlock::iterator BBI = ExitBB->begin();
131893175a5cSSjoerd Meijer     while ((PN = dyn_cast<PHINode>(BBI++))) {
131993175a5cSSjoerd Meijer       if (PN->use_empty())
132093175a5cSSjoerd Meijer         continue; // dead use, don't replace it
132193175a5cSSjoerd Meijer 
132293175a5cSSjoerd Meijer       if (!SE->isSCEVable(PN->getType()))
132393175a5cSSjoerd Meijer         continue;
132493175a5cSSjoerd Meijer 
132593175a5cSSjoerd Meijer       // It's necessary to tell ScalarEvolution about this explicitly so that
132693175a5cSSjoerd Meijer       // it can walk the def-use list and forget all SCEVs, as it may not be
132793175a5cSSjoerd Meijer       // watching the PHI itself. Once the new exit value is in place, there
132893175a5cSSjoerd Meijer       // may not be a def-use connection between the loop and every instruction
132993175a5cSSjoerd Meijer       // which got a SCEVAddRecExpr for that loop.
133093175a5cSSjoerd Meijer       SE->forgetValue(PN);
133193175a5cSSjoerd Meijer 
133293175a5cSSjoerd Meijer       // Iterate over all of the values in all the PHI nodes.
133393175a5cSSjoerd Meijer       for (unsigned i = 0; i != NumPreds; ++i) {
133493175a5cSSjoerd Meijer         // If the value being merged in is not integer or is not defined
133593175a5cSSjoerd Meijer         // in the loop, skip it.
133693175a5cSSjoerd Meijer         Value *InVal = PN->getIncomingValue(i);
133793175a5cSSjoerd Meijer         if (!isa<Instruction>(InVal))
133893175a5cSSjoerd Meijer           continue;
133993175a5cSSjoerd Meijer 
134093175a5cSSjoerd Meijer         // If this pred is for a subloop, not L itself, skip it.
134193175a5cSSjoerd Meijer         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
134293175a5cSSjoerd Meijer           continue; // The Block is in a subloop, skip it.
134393175a5cSSjoerd Meijer 
134493175a5cSSjoerd Meijer         // Check that InVal is defined in the loop.
134593175a5cSSjoerd Meijer         Instruction *Inst = cast<Instruction>(InVal);
134693175a5cSSjoerd Meijer         if (!L->contains(Inst))
134793175a5cSSjoerd Meijer           continue;
134893175a5cSSjoerd Meijer 
134993175a5cSSjoerd Meijer         // Okay, this instruction has a user outside of the current loop
135093175a5cSSjoerd Meijer         // and varies predictably *inside* the loop.  Evaluate the value it
135193175a5cSSjoerd Meijer         // contains when the loop exits, if possible.  We prefer to start with
135293175a5cSSjoerd Meijer         // expressions which are true for all exits (so as to maximize
135393175a5cSSjoerd Meijer         // expression reuse by the SCEVExpander), but resort to per-exit
135493175a5cSSjoerd Meijer         // evaluation if that fails.
135593175a5cSSjoerd Meijer         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
135693175a5cSSjoerd Meijer         if (isa<SCEVCouldNotCompute>(ExitValue) ||
135793175a5cSSjoerd Meijer             !SE->isLoopInvariant(ExitValue, L) ||
135893175a5cSSjoerd Meijer             !isSafeToExpand(ExitValue, *SE)) {
135993175a5cSSjoerd Meijer           // TODO: This should probably be sunk into SCEV in some way; maybe a
136093175a5cSSjoerd Meijer           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
136193175a5cSSjoerd Meijer           // most SCEV expressions and other recurrence types (e.g. shift
136293175a5cSSjoerd Meijer           // recurrences).  Is there existing code we can reuse?
136393175a5cSSjoerd Meijer           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
136493175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitCount))
136593175a5cSSjoerd Meijer             continue;
136693175a5cSSjoerd Meijer           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
136793175a5cSSjoerd Meijer             if (AddRec->getLoop() == L)
136893175a5cSSjoerd Meijer               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
136993175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitValue) ||
137093175a5cSSjoerd Meijer               !SE->isLoopInvariant(ExitValue, L) ||
137193175a5cSSjoerd Meijer               !isSafeToExpand(ExitValue, *SE))
137293175a5cSSjoerd Meijer             continue;
137393175a5cSSjoerd Meijer         }
137493175a5cSSjoerd Meijer 
137593175a5cSSjoerd Meijer         // Computing the value outside of the loop brings no benefit if it is
137693175a5cSSjoerd Meijer         // definitely used inside the loop in a way which can not be optimized
13777d572ef2SRoman Lebedev         // away. Avoid doing so unless we know we have a value which computes
13787d572ef2SRoman Lebedev         // the ExitValue already. TODO: This should be merged into SCEV
13797d572ef2SRoman Lebedev         // expander to leverage its knowledge of existing expressions.
13807d572ef2SRoman Lebedev         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
13817d572ef2SRoman Lebedev             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
138293175a5cSSjoerd Meijer           continue;
138393175a5cSSjoerd Meijer 
1384b2df9612SRoman Lebedev         // Check if expansions of this SCEV would count as being high cost.
13857d572ef2SRoman Lebedev         bool HighCost = Rewriter.isHighCostExpansion(
13867d572ef2SRoman Lebedev             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1387b2df9612SRoman Lebedev 
1388b2df9612SRoman Lebedev         // Note that we must not perform expansions until after
1389b2df9612SRoman Lebedev         // we query *all* the costs, because if we perform temporary expansion
1390b2df9612SRoman Lebedev         // inbetween, one that we might not intend to keep, said expansion
1391b2df9612SRoman Lebedev         // *may* affect cost calculation of the the next SCEV's we'll query,
1392b2df9612SRoman Lebedev         // and next SCEV may errneously get smaller cost.
1393b2df9612SRoman Lebedev 
1394b2df9612SRoman Lebedev         // Collect all the candidate PHINodes to be rewritten.
1395b2df9612SRoman Lebedev         RewritePhiSet.emplace_back(PN, i, ExitValue, Inst, HighCost);
1396b2df9612SRoman Lebedev       }
1397b2df9612SRoman Lebedev     }
1398b2df9612SRoman Lebedev   }
1399b2df9612SRoman Lebedev 
1400b2df9612SRoman Lebedev   // Now that we've done preliminary filtering and billed all the SCEV's,
1401b2df9612SRoman Lebedev   // we can perform the last sanity check - the expansion must be valid.
1402b2df9612SRoman Lebedev   for (RewritePhi &Phi : RewritePhiSet) {
1403b2df9612SRoman Lebedev     Phi.Expansion = Rewriter.expandCodeFor(Phi.ExpansionSCEV, Phi.PN->getType(),
1404b2df9612SRoman Lebedev                                            Phi.ExpansionPoint);
140593175a5cSSjoerd Meijer 
140693175a5cSSjoerd Meijer     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = "
1407b2df9612SRoman Lebedev                       << *(Phi.Expansion) << '\n'
1408b2df9612SRoman Lebedev                       << "  LoopVal = " << *(Phi.ExpansionPoint) << "\n");
140993175a5cSSjoerd Meijer 
1410b2df9612SRoman Lebedev     // FIXME: isValidRewrite() is a hack. it should be an assert, eventually.
1411b2df9612SRoman Lebedev     Phi.ValidRewrite = isValidRewrite(SE, Phi.ExpansionPoint, Phi.Expansion);
1412b2df9612SRoman Lebedev     if (!Phi.ValidRewrite) {
1413b2df9612SRoman Lebedev       DeadInsts.push_back(Phi.Expansion);
141493175a5cSSjoerd Meijer       continue;
141593175a5cSSjoerd Meijer     }
141693175a5cSSjoerd Meijer 
141793175a5cSSjoerd Meijer #ifndef NDEBUG
141893175a5cSSjoerd Meijer     // If we reuse an instruction from a loop which is neither L nor one of
141993175a5cSSjoerd Meijer     // its containing loops, we end up breaking LCSSA form for this loop by
142093175a5cSSjoerd Meijer     // creating a new use of its instruction.
1421b2df9612SRoman Lebedev     if (auto *ExitInsn = dyn_cast<Instruction>(Phi.Expansion))
142293175a5cSSjoerd Meijer       if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
142393175a5cSSjoerd Meijer         if (EVL != L)
142493175a5cSSjoerd Meijer           assert(EVL->contains(L) && "LCSSA breach detected!");
142593175a5cSSjoerd Meijer #endif
1426b2df9612SRoman Lebedev   }
142793175a5cSSjoerd Meijer 
1428b2df9612SRoman Lebedev   // TODO: after isValidRewrite() is an assertion, evaluate whether
1429b2df9612SRoman Lebedev   // it is beneficial to change how we calculate high-cost:
1430b2df9612SRoman Lebedev   // if we have SCEV 'A' which we know we will expand, should we calculate
1431b2df9612SRoman Lebedev   // the cost of other SCEV's after expanding SCEV 'A',
1432b2df9612SRoman Lebedev   // thus potentially giving cost bonus to those other SCEV's?
143393175a5cSSjoerd Meijer 
143493175a5cSSjoerd Meijer   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
143593175a5cSSjoerd Meijer   int NumReplaced = 0;
143693175a5cSSjoerd Meijer 
143793175a5cSSjoerd Meijer   // Transformation.
143893175a5cSSjoerd Meijer   for (const RewritePhi &Phi : RewritePhiSet) {
1439b2df9612SRoman Lebedev     if (!Phi.ValidRewrite)
1440b2df9612SRoman Lebedev       continue;
1441b2df9612SRoman Lebedev 
144293175a5cSSjoerd Meijer     PHINode *PN = Phi.PN;
1443b2df9612SRoman Lebedev     Value *ExitVal = Phi.Expansion;
144493175a5cSSjoerd Meijer 
144593175a5cSSjoerd Meijer     // Only do the rewrite when the ExitValue can be expanded cheaply.
144693175a5cSSjoerd Meijer     // If LoopCanBeDel is true, rewrite exit value aggressively.
144793175a5cSSjoerd Meijer     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
144893175a5cSSjoerd Meijer       DeadInsts.push_back(ExitVal);
144993175a5cSSjoerd Meijer       continue;
145093175a5cSSjoerd Meijer     }
145193175a5cSSjoerd Meijer 
145293175a5cSSjoerd Meijer     NumReplaced++;
145393175a5cSSjoerd Meijer     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
145493175a5cSSjoerd Meijer     PN->setIncomingValue(Phi.Ith, ExitVal);
145593175a5cSSjoerd Meijer 
145693175a5cSSjoerd Meijer     // If this instruction is dead now, delete it. Don't do it now to avoid
145793175a5cSSjoerd Meijer     // invalidating iterators.
145893175a5cSSjoerd Meijer     if (isInstructionTriviallyDead(Inst, TLI))
145993175a5cSSjoerd Meijer       DeadInsts.push_back(Inst);
146093175a5cSSjoerd Meijer 
146193175a5cSSjoerd Meijer     // Replace PN with ExitVal if that is legal and does not break LCSSA.
146293175a5cSSjoerd Meijer     if (PN->getNumIncomingValues() == 1 &&
146393175a5cSSjoerd Meijer         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
146493175a5cSSjoerd Meijer       PN->replaceAllUsesWith(ExitVal);
146593175a5cSSjoerd Meijer       PN->eraseFromParent();
146693175a5cSSjoerd Meijer     }
146793175a5cSSjoerd Meijer   }
146893175a5cSSjoerd Meijer 
146993175a5cSSjoerd Meijer   // The insertion point instruction may have been deleted; clear it out
147093175a5cSSjoerd Meijer   // so that the rewriter doesn't trip over it later.
147193175a5cSSjoerd Meijer   Rewriter.clearInsertPoint();
147293175a5cSSjoerd Meijer   return NumReplaced;
147393175a5cSSjoerd Meijer }
1474af7e1588SEvgeniy Brevnov 
1475af7e1588SEvgeniy Brevnov /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1476af7e1588SEvgeniy Brevnov /// \p OrigLoop.
1477af7e1588SEvgeniy Brevnov void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1478af7e1588SEvgeniy Brevnov                                         Loop *RemainderLoop, uint64_t UF) {
1479af7e1588SEvgeniy Brevnov   assert(UF > 0 && "Zero unrolled factor is not supported");
1480af7e1588SEvgeniy Brevnov   assert(UnrolledLoop != RemainderLoop &&
1481af7e1588SEvgeniy Brevnov          "Unrolled and Remainder loops are expected to distinct");
1482af7e1588SEvgeniy Brevnov 
1483af7e1588SEvgeniy Brevnov   // Get number of iterations in the original scalar loop.
1484af7e1588SEvgeniy Brevnov   unsigned OrigLoopInvocationWeight = 0;
1485af7e1588SEvgeniy Brevnov   Optional<unsigned> OrigAverageTripCount =
1486af7e1588SEvgeniy Brevnov       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1487af7e1588SEvgeniy Brevnov   if (!OrigAverageTripCount)
1488af7e1588SEvgeniy Brevnov     return;
1489af7e1588SEvgeniy Brevnov 
1490af7e1588SEvgeniy Brevnov   // Calculate number of iterations in unrolled loop.
1491af7e1588SEvgeniy Brevnov   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1492af7e1588SEvgeniy Brevnov   // Calculate number of iterations for remainder loop.
1493af7e1588SEvgeniy Brevnov   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1494af7e1588SEvgeniy Brevnov 
1495af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1496af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1497af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1498af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1499af7e1588SEvgeniy Brevnov }
1500388de9dfSAlina Sbirlea 
1501388de9dfSAlina Sbirlea /// Utility that implements appending of loops onto a worklist.
1502388de9dfSAlina Sbirlea /// Loops are added in preorder (analogous for reverse postorder for trees),
1503388de9dfSAlina Sbirlea /// and the worklist is processed LIFO.
1504388de9dfSAlina Sbirlea template <typename RangeT>
1505388de9dfSAlina Sbirlea void llvm::appendReversedLoopsToWorklist(
1506388de9dfSAlina Sbirlea     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1507388de9dfSAlina Sbirlea   // We use an internal worklist to build up the preorder traversal without
1508388de9dfSAlina Sbirlea   // recursion.
1509388de9dfSAlina Sbirlea   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1510388de9dfSAlina Sbirlea 
1511388de9dfSAlina Sbirlea   // We walk the initial sequence of loops in reverse because we generally want
1512388de9dfSAlina Sbirlea   // to visit defs before uses and the worklist is LIFO.
1513388de9dfSAlina Sbirlea   for (Loop *RootL : Loops) {
1514388de9dfSAlina Sbirlea     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1515388de9dfSAlina Sbirlea     assert(PreOrderWorklist.empty() &&
1516388de9dfSAlina Sbirlea            "Must start with an empty preorder walk worklist.");
1517388de9dfSAlina Sbirlea     PreOrderWorklist.push_back(RootL);
1518388de9dfSAlina Sbirlea     do {
1519388de9dfSAlina Sbirlea       Loop *L = PreOrderWorklist.pop_back_val();
1520388de9dfSAlina Sbirlea       PreOrderWorklist.append(L->begin(), L->end());
1521388de9dfSAlina Sbirlea       PreOrderLoops.push_back(L);
1522388de9dfSAlina Sbirlea     } while (!PreOrderWorklist.empty());
1523388de9dfSAlina Sbirlea 
1524388de9dfSAlina Sbirlea     Worklist.insert(std::move(PreOrderLoops));
1525388de9dfSAlina Sbirlea     PreOrderLoops.clear();
1526388de9dfSAlina Sbirlea   }
1527388de9dfSAlina Sbirlea }
1528388de9dfSAlina Sbirlea 
1529388de9dfSAlina Sbirlea template <typename RangeT>
1530388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(RangeT &&Loops,
1531388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1532388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1533388de9dfSAlina Sbirlea }
1534388de9dfSAlina Sbirlea 
1535388de9dfSAlina Sbirlea template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1536388de9dfSAlina Sbirlea     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1537388de9dfSAlina Sbirlea 
153867904db2SAlina Sbirlea template void
153967904db2SAlina Sbirlea llvm::appendLoopsToWorklist<Loop &>(Loop &L,
154067904db2SAlina Sbirlea                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
154167904db2SAlina Sbirlea 
1542388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(LoopInfo &LI,
1543388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1544388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(LI, Worklist);
1545388de9dfSAlina Sbirlea }
15463dcaf296SArkady Shlykov 
15473dcaf296SArkady Shlykov Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
15483dcaf296SArkady Shlykov                       LoopInfo *LI, LPPassManager *LPM) {
15493dcaf296SArkady Shlykov   Loop &New = *LI->AllocateLoop();
15503dcaf296SArkady Shlykov   if (PL)
15513dcaf296SArkady Shlykov     PL->addChildLoop(&New);
15523dcaf296SArkady Shlykov   else
15533dcaf296SArkady Shlykov     LI->addTopLevelLoop(&New);
15543dcaf296SArkady Shlykov 
15553dcaf296SArkady Shlykov   if (LPM)
15563dcaf296SArkady Shlykov     LPM->addLoop(New);
15573dcaf296SArkady Shlykov 
15583dcaf296SArkady Shlykov   // Add all of the blocks in L to the new loop.
15593dcaf296SArkady Shlykov   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
15603dcaf296SArkady Shlykov        I != E; ++I)
15613dcaf296SArkady Shlykov     if (LI->getLoopFor(*I) == L)
15623dcaf296SArkady Shlykov       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
15633dcaf296SArkady Shlykov 
15643dcaf296SArkady Shlykov   // Add all of the subloops to the new loop.
15653dcaf296SArkady Shlykov   for (Loop *I : *L)
15663dcaf296SArkady Shlykov     cloneLoop(I, &New, VM, LI, LPM);
15673dcaf296SArkady Shlykov 
15683dcaf296SArkady Shlykov   return &New;
15693dcaf296SArkady Shlykov }
15708528186bSFlorian Hahn 
15718528186bSFlorian Hahn /// IR Values for the lower and upper bounds of a pointer evolution.  We
15728528186bSFlorian Hahn /// need to use value-handles because SCEV expansion can invalidate previously
15738528186bSFlorian Hahn /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
15748528186bSFlorian Hahn /// a previous one.
15758528186bSFlorian Hahn struct PointerBounds {
15768528186bSFlorian Hahn   TrackingVH<Value> Start;
15778528186bSFlorian Hahn   TrackingVH<Value> End;
15788528186bSFlorian Hahn };
15798528186bSFlorian Hahn 
15808528186bSFlorian Hahn /// Expand code for the lower and upper bound of the pointer group \p CG
15818528186bSFlorian Hahn /// in \p TheLoop.  \return the values for the bounds.
15828528186bSFlorian Hahn static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
15838528186bSFlorian Hahn                                   Loop *TheLoop, Instruction *Loc,
15848528186bSFlorian Hahn                                   SCEVExpander &Exp, ScalarEvolution *SE) {
15858528186bSFlorian Hahn   // TODO: Add helper to retrieve pointers to CG.
15868528186bSFlorian Hahn   Value *Ptr = CG->RtCheck.Pointers[CG->Members[0]].PointerValue;
15878528186bSFlorian Hahn   const SCEV *Sc = SE->getSCEV(Ptr);
15888528186bSFlorian Hahn 
15898528186bSFlorian Hahn   unsigned AS = Ptr->getType()->getPointerAddressSpace();
15908528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
15918528186bSFlorian Hahn 
15928528186bSFlorian Hahn   // Use this type for pointer arithmetic.
15938528186bSFlorian Hahn   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
15948528186bSFlorian Hahn 
15958528186bSFlorian Hahn   if (SE->isLoopInvariant(Sc, TheLoop)) {
15968528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:"
15978528186bSFlorian Hahn                       << *Ptr << "\n");
15988528186bSFlorian Hahn     // Ptr could be in the loop body. If so, expand a new one at the correct
15998528186bSFlorian Hahn     // location.
16008528186bSFlorian Hahn     Instruction *Inst = dyn_cast<Instruction>(Ptr);
16018528186bSFlorian Hahn     Value *NewPtr = (Inst && TheLoop->contains(Inst))
16028528186bSFlorian Hahn                         ? Exp.expandCodeFor(Sc, PtrArithTy, Loc)
16038528186bSFlorian Hahn                         : Ptr;
16048528186bSFlorian Hahn     // We must return a half-open range, which means incrementing Sc.
16058528186bSFlorian Hahn     const SCEV *ScPlusOne = SE->getAddExpr(Sc, SE->getOne(PtrArithTy));
16068528186bSFlorian Hahn     Value *NewPtrPlusOne = Exp.expandCodeFor(ScPlusOne, PtrArithTy, Loc);
16078528186bSFlorian Hahn     return {NewPtr, NewPtrPlusOne};
16088528186bSFlorian Hahn   } else {
16098528186bSFlorian Hahn     Value *Start = nullptr, *End = nullptr;
16108528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
16118528186bSFlorian Hahn     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
16128528186bSFlorian Hahn     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
16138528186bSFlorian Hahn     LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High
16148528186bSFlorian Hahn                       << "\n");
16158528186bSFlorian Hahn     return {Start, End};
16168528186bSFlorian Hahn   }
16178528186bSFlorian Hahn }
16188528186bSFlorian Hahn 
16198528186bSFlorian Hahn /// Turns a collection of checks into a collection of expanded upper and
16208528186bSFlorian Hahn /// lower bounds for both pointers in the check.
16218528186bSFlorian Hahn static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
16228528186bSFlorian Hahn expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
16238528186bSFlorian Hahn              Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp) {
16248528186bSFlorian Hahn   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
16258528186bSFlorian Hahn 
16268528186bSFlorian Hahn   // Here we're relying on the SCEV Expander's cache to only emit code for the
16278528186bSFlorian Hahn   // same bounds once.
16288528186bSFlorian Hahn   transform(PointerChecks, std::back_inserter(ChecksWithBounds),
16298528186bSFlorian Hahn             [&](const RuntimePointerCheck &Check) {
16308528186bSFlorian Hahn               PointerBounds First = expandBounds(Check.first, L, Loc, Exp, SE),
16318528186bSFlorian Hahn                             Second =
16328528186bSFlorian Hahn                                 expandBounds(Check.second, L, Loc, Exp, SE);
16338528186bSFlorian Hahn               return std::make_pair(First, Second);
16348528186bSFlorian Hahn             });
16358528186bSFlorian Hahn 
16368528186bSFlorian Hahn   return ChecksWithBounds;
16378528186bSFlorian Hahn }
16388528186bSFlorian Hahn 
16398528186bSFlorian Hahn std::pair<Instruction *, Instruction *> llvm::addRuntimeChecks(
16408528186bSFlorian Hahn     Instruction *Loc, Loop *TheLoop,
16418528186bSFlorian Hahn     const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
16428528186bSFlorian Hahn     ScalarEvolution *SE) {
16438528186bSFlorian Hahn   // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
16448528186bSFlorian Hahn   // TODO: Pass  RtPtrChecking instead of PointerChecks and SE separately, if possible
16458528186bSFlorian Hahn   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
16468528186bSFlorian Hahn   SCEVExpander Exp(*SE, DL, "induction");
16478528186bSFlorian Hahn   auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, SE, Exp);
16488528186bSFlorian Hahn 
16498528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
16508528186bSFlorian Hahn   Instruction *FirstInst = nullptr;
16518528186bSFlorian Hahn   IRBuilder<> ChkBuilder(Loc);
16528528186bSFlorian Hahn   // Our instructions might fold to a constant.
16538528186bSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
16548528186bSFlorian Hahn 
16558528186bSFlorian Hahn   // FIXME: this helper is currently a duplicate of the one in
16568528186bSFlorian Hahn   // LoopVectorize.cpp.
16578528186bSFlorian Hahn   auto GetFirstInst = [](Instruction *FirstInst, Value *V,
16588528186bSFlorian Hahn                          Instruction *Loc) -> Instruction * {
16598528186bSFlorian Hahn     if (FirstInst)
16608528186bSFlorian Hahn       return FirstInst;
16618528186bSFlorian Hahn     if (Instruction *I = dyn_cast<Instruction>(V))
16628528186bSFlorian Hahn       return I->getParent() == Loc->getParent() ? I : nullptr;
16638528186bSFlorian Hahn     return nullptr;
16648528186bSFlorian Hahn   };
16658528186bSFlorian Hahn 
16668528186bSFlorian Hahn   for (const auto &Check : ExpandedChecks) {
16678528186bSFlorian Hahn     const PointerBounds &A = Check.first, &B = Check.second;
16688528186bSFlorian Hahn     // Check if two pointers (A and B) conflict where conflict is computed as:
16698528186bSFlorian Hahn     // start(A) <= end(B) && start(B) <= end(A)
16708528186bSFlorian Hahn     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
16718528186bSFlorian Hahn     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
16728528186bSFlorian Hahn 
16738528186bSFlorian Hahn     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
16748528186bSFlorian Hahn            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
16758528186bSFlorian Hahn            "Trying to bounds check pointers with different address spaces");
16768528186bSFlorian Hahn 
16778528186bSFlorian Hahn     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
16788528186bSFlorian Hahn     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
16798528186bSFlorian Hahn 
16808528186bSFlorian Hahn     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
16818528186bSFlorian Hahn     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
16828528186bSFlorian Hahn     Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
16838528186bSFlorian Hahn     Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
16848528186bSFlorian Hahn 
16858528186bSFlorian Hahn     // [A|B].Start points to the first accessed byte under base [A|B].
16868528186bSFlorian Hahn     // [A|B].End points to the last accessed byte, plus one.
16878528186bSFlorian Hahn     // There is no conflict when the intervals are disjoint:
16888528186bSFlorian Hahn     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
16898528186bSFlorian Hahn     //
16908528186bSFlorian Hahn     // bound0 = (B.Start < A.End)
16918528186bSFlorian Hahn     // bound1 = (A.Start < B.End)
16928528186bSFlorian Hahn     //  IsConflict = bound0 & bound1
16938528186bSFlorian Hahn     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
16948528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, Cmp0, Loc);
16958528186bSFlorian Hahn     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
16968528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, Cmp1, Loc);
16978528186bSFlorian Hahn     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
16988528186bSFlorian Hahn     FirstInst = GetFirstInst(FirstInst, IsConflict, Loc);
16998528186bSFlorian Hahn     if (MemoryRuntimeCheck) {
17008528186bSFlorian Hahn       IsConflict =
17018528186bSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
17028528186bSFlorian Hahn       FirstInst = GetFirstInst(FirstInst, IsConflict, Loc);
17038528186bSFlorian Hahn     }
17048528186bSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
17058528186bSFlorian Hahn   }
17068528186bSFlorian Hahn 
17078528186bSFlorian Hahn   if (!MemoryRuntimeCheck)
17088528186bSFlorian Hahn     return std::make_pair(nullptr, nullptr);
17098528186bSFlorian Hahn 
17108528186bSFlorian Hahn   // We have to do this trickery because the IRBuilder might fold the check to a
17118528186bSFlorian Hahn   // constant expression in which case there is no Instruction anchored in a
17128528186bSFlorian Hahn   // the block.
17138528186bSFlorian Hahn   Instruction *Check =
17148528186bSFlorian Hahn       BinaryOperator::CreateAnd(MemoryRuntimeCheck, ConstantInt::getTrue(Ctx));
17158528186bSFlorian Hahn   ChkBuilder.Insert(Check, "memcheck.conflict");
17168528186bSFlorian Hahn   FirstInst = GetFirstInst(FirstInst, Check, Loc);
17178528186bSFlorian Hahn   return std::make_pair(FirstInst, Check);
17188528186bSFlorian Hahn }
1719