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"
25e00158edSFlorian Hahn #include "llvm/Analysis/InstSimplifyFolder.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"
3145d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
322f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
3345d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
34744c3c32SDavide Italiano #include "llvm/IR/DIBuilder.h"
3531088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
3676aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
37744c3c32SDavide Italiano #include "llvm/IR/IntrinsicInst.h"
38af7e1588SEvgeniy Brevnov #include "llvm/IR/MDBuilder.h"
3945d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
4076aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
4176aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
4205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
4331088a9dSChandler Carruth #include "llvm/Pass.h"
4476aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
454a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
4693175a5cSSjoerd Meijer #include "llvm/Transforms/Utils/Local.h"
47bcbd26bfSFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
4876aa662cSKarthik Bhat 
4976aa662cSKarthik Bhat using namespace llvm;
5076aa662cSKarthik Bhat using namespace llvm::PatternMatch;
5176aa662cSKarthik Bhat 
5276aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
5376aa662cSKarthik Bhat 
5472448525SMichael Kruse static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
554f64f1baSTim Corringham static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
5672448525SMichael Kruse 
574a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
5897468e92SAlina Sbirlea                                    MemorySSAUpdater *MSSAU,
594a000883SChandler Carruth                                    bool PreserveLCSSA) {
604a000883SChandler Carruth   bool Changed = false;
614a000883SChandler Carruth 
624a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
634a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
644a000883SChandler Carruth 
654a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
664a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
674a000883SChandler Carruth            "Must start with an empty predecessors list!");
684a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
694a000883SChandler Carruth 
704a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
714a000883SChandler Carruth     // keep track of the in-loop predecessors.
724a000883SChandler Carruth     bool IsDedicatedExit = true;
734a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
744a000883SChandler Carruth       if (L->contains(PredBB)) {
754a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
764a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
774a000883SChandler Carruth           return false;
78784929d0SCraig Topper         if (isa<CallBrInst>(PredBB->getTerminator()))
79784929d0SCraig Topper           // We cannot rewrite exiting edges from a callbr.
80784929d0SCraig Topper           return false;
814a000883SChandler Carruth 
824a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
834a000883SChandler Carruth       } else {
844a000883SChandler Carruth         IsDedicatedExit = false;
854a000883SChandler Carruth       }
864a000883SChandler Carruth 
874a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
884a000883SChandler Carruth 
894a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
904a000883SChandler Carruth     if (IsDedicatedExit)
914a000883SChandler Carruth       return false;
924a000883SChandler Carruth 
934a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
9497468e92SAlina Sbirlea         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
954a000883SChandler Carruth 
964a000883SChandler Carruth     if (!NewExitBB)
97d34e60caSNicola Zaghen       LLVM_DEBUG(
98d34e60caSNicola Zaghen           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
994a000883SChandler Carruth                  << *L << "\n");
1004a000883SChandler Carruth     else
101d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
1024a000883SChandler Carruth                         << NewExitBB->getName() << "\n");
1034a000883SChandler Carruth     return true;
1044a000883SChandler Carruth   };
1054a000883SChandler Carruth 
1064a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
1074a000883SChandler Carruth   // them, but only visit each one once.
1084a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
1094a000883SChandler Carruth   for (auto *BB : L->blocks())
1104a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
1114a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
1124a000883SChandler Carruth       if (L->contains(SuccBB))
1134a000883SChandler Carruth         continue;
1144a000883SChandler Carruth 
1154a000883SChandler Carruth       // Visit each exit block exactly once.
1164a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
1174a000883SChandler Carruth         continue;
1184a000883SChandler Carruth 
1194a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
1204a000883SChandler Carruth     }
1214a000883SChandler Carruth 
1224a000883SChandler Carruth   return Changed;
1234a000883SChandler Carruth }
1244a000883SChandler Carruth 
1255f8f34e4SAdrian Prantl /// Returns the instructions that use values defined in the loop.
126c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
127c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
128c5b7b555SAshutosh Nema 
129c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
130c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
131c5b7b555SAshutosh Nema     // be adapted into a pointer.
132c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
133c5b7b555SAshutosh Nema       auto Users = Inst.users();
1340a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
135c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
136c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
137c5b7b555SAshutosh Nema           }))
138c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
139c5b7b555SAshutosh Nema     }
140c5b7b555SAshutosh Nema 
141c5b7b555SAshutosh Nema   return UsedOutside;
142c5b7b555SAshutosh Nema }
14331088a9dSChandler Carruth 
14431088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
14531088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
14631088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
14731088a9dSChandler Carruth   // pass manager, they must also preserve these.
14831088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
14931088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
15031088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
15131088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
15231088a9dSChandler Carruth 
15331088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
15431088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
15531088a9dSChandler Carruth   extern char &LoopSimplifyID;
15631088a9dSChandler Carruth   extern char &LCSSAID;
15731088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
15831088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
15931088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
16031088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
161c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
162c3ccf5d7SIgor Laevsky   // which preserve lcssa form
163c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
164c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
16531088a9dSChandler Carruth 
16631088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
16731088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
16831088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
16931088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
17031088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
17131088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
17231088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
17331088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
17431088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
17531088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
17631088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
17731088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
17831088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
17931088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
1806da79ce1SAlina Sbirlea   // FIXME: When all loop passes preserve MemorySSA, it can be required and
1816da79ce1SAlina Sbirlea   // preserved here instead of the individual handling in each pass.
18231088a9dSChandler Carruth }
18331088a9dSChandler Carruth 
18431088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
18531088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
18631088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
18731088a9dSChandler Carruth /// with:
18831088a9dSChandler Carruth ///
18931088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
19031088a9dSChandler Carruth ///
19131088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
19231088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
19331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
19431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
19531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
196e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
19731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
19831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
19931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
20031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
20131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2026da79ce1SAlina Sbirlea   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
20331088a9dSChandler Carruth }
204963341c8SAdam Nemet 
2053c3a7652SSerguei Katkov /// Create MDNode for input string.
2063c3a7652SSerguei Katkov static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
2073c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2083c3a7652SSerguei Katkov   Metadata *MDs[] = {
2093c3a7652SSerguei Katkov       MDString::get(Context, Name),
2103c3a7652SSerguei Katkov       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
2113c3a7652SSerguei Katkov   return MDNode::get(Context, MDs);
2123c3a7652SSerguei Katkov }
2133c3a7652SSerguei Katkov 
2143c3a7652SSerguei Katkov /// Set input string into loop metadata by keeping other values intact.
2157f8c8095SSerguei Katkov /// If the string is already in loop metadata update value if it is
2167f8c8095SSerguei Katkov /// different.
2177f8c8095SSerguei Katkov void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
2183c3a7652SSerguei Katkov                                    unsigned V) {
2193c3a7652SSerguei Katkov   SmallVector<Metadata *, 4> MDs(1);
2203c3a7652SSerguei Katkov   // If the loop already has metadata, retain it.
2213c3a7652SSerguei Katkov   MDNode *LoopID = TheLoop->getLoopID();
2223c3a7652SSerguei Katkov   if (LoopID) {
2233c3a7652SSerguei Katkov     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2243c3a7652SSerguei Katkov       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
2257f8c8095SSerguei Katkov       // If it is of form key = value, try to parse it.
2267f8c8095SSerguei Katkov       if (Node->getNumOperands() == 2) {
2277f8c8095SSerguei Katkov         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
2287f8c8095SSerguei Katkov         if (S && S->getString().equals(StringMD)) {
2297f8c8095SSerguei Katkov           ConstantInt *IntMD =
2307f8c8095SSerguei Katkov               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
2317f8c8095SSerguei Katkov           if (IntMD && IntMD->getSExtValue() == V)
2327f8c8095SSerguei Katkov             // It is already in place. Do nothing.
2337f8c8095SSerguei Katkov             return;
2347f8c8095SSerguei Katkov           // We need to update the value, so just skip it here and it will
2357f8c8095SSerguei Katkov           // be added after copying other existed nodes.
2367f8c8095SSerguei Katkov           continue;
2377f8c8095SSerguei Katkov         }
2387f8c8095SSerguei Katkov       }
2393c3a7652SSerguei Katkov       MDs.push_back(Node);
2403c3a7652SSerguei Katkov     }
2413c3a7652SSerguei Katkov   }
2423c3a7652SSerguei Katkov   // Add new metadata.
2437f8c8095SSerguei Katkov   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
2443c3a7652SSerguei Katkov   // Replace current metadata node with new one.
2453c3a7652SSerguei Katkov   LLVMContext &Context = TheLoop->getHeader()->getContext();
2463c3a7652SSerguei Katkov   MDNode *NewLoopID = MDNode::get(Context, MDs);
2473c3a7652SSerguei Katkov   // Set operand 0 to refer to the loop id itself.
2483c3a7652SSerguei Katkov   NewLoopID->replaceOperandWith(0, NewLoopID);
2493c3a7652SSerguei Katkov   TheLoop->setLoopID(NewLoopID);
2503c3a7652SSerguei Katkov }
2513c3a7652SSerguei Katkov 
25271bd59f0SDavid Sherwood Optional<ElementCount>
253ddb3b26aSBardia Mahjour llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
25471bd59f0SDavid Sherwood   Optional<int> Width =
25571bd59f0SDavid Sherwood       getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
25671bd59f0SDavid Sherwood 
25771bd59f0SDavid Sherwood   if (Width.hasValue()) {
25871bd59f0SDavid Sherwood     Optional<int> IsScalable = getOptionalIntLoopAttribute(
25971bd59f0SDavid Sherwood         TheLoop, "llvm.loop.vectorize.scalable.enable");
2608a20e2b3SKazu Hirata     return ElementCount::get(*Width, IsScalable.getValueOr(false));
26171bd59f0SDavid Sherwood   }
26271bd59f0SDavid Sherwood 
26371bd59f0SDavid Sherwood   return None;
26471bd59f0SDavid Sherwood }
26571bd59f0SDavid Sherwood 
26672448525SMichael Kruse Optional<MDNode *> llvm::makeFollowupLoopID(
26772448525SMichael Kruse     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
26872448525SMichael Kruse     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
26972448525SMichael Kruse   if (!OrigLoopID) {
27072448525SMichael Kruse     if (AlwaysNew)
27172448525SMichael Kruse       return nullptr;
27272448525SMichael Kruse     return None;
27372448525SMichael Kruse   }
27472448525SMichael Kruse 
27572448525SMichael Kruse   assert(OrigLoopID->getOperand(0) == OrigLoopID);
27672448525SMichael Kruse 
27772448525SMichael Kruse   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
27872448525SMichael Kruse   bool InheritSomeAttrs =
27972448525SMichael Kruse       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
28072448525SMichael Kruse   SmallVector<Metadata *, 8> MDs;
28172448525SMichael Kruse   MDs.push_back(nullptr);
28272448525SMichael Kruse 
28372448525SMichael Kruse   bool Changed = false;
28472448525SMichael Kruse   if (InheritAllAttrs || InheritSomeAttrs) {
285dc300bebSKazu Hirata     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
28672448525SMichael Kruse       MDNode *Op = cast<MDNode>(Existing.get());
28772448525SMichael Kruse 
28872448525SMichael Kruse       auto InheritThisAttribute = [InheritSomeAttrs,
28972448525SMichael Kruse                                    InheritOptionsExceptPrefix](MDNode *Op) {
29072448525SMichael Kruse         if (!InheritSomeAttrs)
29172448525SMichael Kruse           return false;
29272448525SMichael Kruse 
29372448525SMichael Kruse         // Skip malformatted attribute metadata nodes.
29472448525SMichael Kruse         if (Op->getNumOperands() == 0)
29572448525SMichael Kruse           return true;
29672448525SMichael Kruse         Metadata *NameMD = Op->getOperand(0).get();
29772448525SMichael Kruse         if (!isa<MDString>(NameMD))
29872448525SMichael Kruse           return true;
29972448525SMichael Kruse         StringRef AttrName = cast<MDString>(NameMD)->getString();
30072448525SMichael Kruse 
30172448525SMichael Kruse         // Do not inherit excluded attributes.
30272448525SMichael Kruse         return !AttrName.startswith(InheritOptionsExceptPrefix);
30372448525SMichael Kruse       };
30472448525SMichael Kruse 
30572448525SMichael Kruse       if (InheritThisAttribute(Op))
30672448525SMichael Kruse         MDs.push_back(Op);
30772448525SMichael Kruse       else
30872448525SMichael Kruse         Changed = true;
30972448525SMichael Kruse     }
31072448525SMichael Kruse   } else {
31172448525SMichael Kruse     // Modified if we dropped at least one attribute.
31272448525SMichael Kruse     Changed = OrigLoopID->getNumOperands() > 1;
31372448525SMichael Kruse   }
31472448525SMichael Kruse 
31572448525SMichael Kruse   bool HasAnyFollowup = false;
31672448525SMichael Kruse   for (StringRef OptionName : FollowupOptions) {
317978ba615SMichael Kruse     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
31872448525SMichael Kruse     if (!FollowupNode)
31972448525SMichael Kruse       continue;
32072448525SMichael Kruse 
32172448525SMichael Kruse     HasAnyFollowup = true;
322dc300bebSKazu Hirata     for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
32372448525SMichael Kruse       MDs.push_back(Option.get());
32472448525SMichael Kruse       Changed = true;
32572448525SMichael Kruse     }
32672448525SMichael Kruse   }
32772448525SMichael Kruse 
32872448525SMichael Kruse   // Attributes of the followup loop not specified explicity, so signal to the
32972448525SMichael Kruse   // transformation pass to add suitable attributes.
33072448525SMichael Kruse   if (!AlwaysNew && !HasAnyFollowup)
33172448525SMichael Kruse     return None;
33272448525SMichael Kruse 
33372448525SMichael Kruse   // If no attributes were added or remove, the previous loop Id can be reused.
33472448525SMichael Kruse   if (!AlwaysNew && !Changed)
33572448525SMichael Kruse     return OrigLoopID;
33672448525SMichael Kruse 
33772448525SMichael Kruse   // No attributes is equivalent to having no !llvm.loop metadata at all.
33872448525SMichael Kruse   if (MDs.size() == 1)
33972448525SMichael Kruse     return nullptr;
34072448525SMichael Kruse 
34172448525SMichael Kruse   // Build the new loop ID.
34272448525SMichael Kruse   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
34372448525SMichael Kruse   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
34472448525SMichael Kruse   return FollowupLoopID;
34572448525SMichael Kruse }
34672448525SMichael Kruse 
34772448525SMichael Kruse bool llvm::hasDisableAllTransformsHint(const Loop *L) {
34872448525SMichael Kruse   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
34972448525SMichael Kruse }
35072448525SMichael Kruse 
3514f64f1baSTim Corringham bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
3524f64f1baSTim Corringham   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
3534f64f1baSTim Corringham }
3544f64f1baSTim Corringham 
355ddb3b26aSBardia Mahjour TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
35672448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
35772448525SMichael Kruse     return TM_SuppressedByUser;
35872448525SMichael Kruse 
35972448525SMichael Kruse   Optional<int> Count =
36072448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
36172448525SMichael Kruse   if (Count.hasValue())
36272448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
36372448525SMichael Kruse 
36472448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
36572448525SMichael Kruse     return TM_ForcedByUser;
36672448525SMichael Kruse 
36772448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
36872448525SMichael Kruse     return TM_ForcedByUser;
36972448525SMichael Kruse 
37072448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
37172448525SMichael Kruse     return TM_Disable;
37272448525SMichael Kruse 
37372448525SMichael Kruse   return TM_Unspecified;
37472448525SMichael Kruse }
37572448525SMichael Kruse 
376ddb3b26aSBardia Mahjour TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
37772448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
37872448525SMichael Kruse     return TM_SuppressedByUser;
37972448525SMichael Kruse 
38072448525SMichael Kruse   Optional<int> Count =
38172448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
38272448525SMichael Kruse   if (Count.hasValue())
38372448525SMichael Kruse     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
38472448525SMichael Kruse 
38572448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
38672448525SMichael Kruse     return TM_ForcedByUser;
38772448525SMichael Kruse 
38872448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
38972448525SMichael Kruse     return TM_Disable;
39072448525SMichael Kruse 
39172448525SMichael Kruse   return TM_Unspecified;
39272448525SMichael Kruse }
39372448525SMichael Kruse 
394ddb3b26aSBardia Mahjour TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
39572448525SMichael Kruse   Optional<bool> Enable =
39672448525SMichael Kruse       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
39772448525SMichael Kruse 
39872448525SMichael Kruse   if (Enable == false)
39972448525SMichael Kruse     return TM_SuppressedByUser;
40072448525SMichael Kruse 
40171bd59f0SDavid Sherwood   Optional<ElementCount> VectorizeWidth =
40271bd59f0SDavid Sherwood       getOptionalElementCountLoopAttribute(L);
40372448525SMichael Kruse   Optional<int> InterleaveCount =
40472448525SMichael Kruse       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
40572448525SMichael Kruse 
40672448525SMichael Kruse   // 'Forcing' vector width and interleave count to one effectively disables
40772448525SMichael Kruse   // this tranformation.
40871bd59f0SDavid Sherwood   if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
40971bd59f0SDavid Sherwood       InterleaveCount == 1)
41072448525SMichael Kruse     return TM_SuppressedByUser;
41172448525SMichael Kruse 
41272448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
41372448525SMichael Kruse     return TM_Disable;
41472448525SMichael Kruse 
41570560a0aSMichael Kruse   if (Enable == true)
41670560a0aSMichael Kruse     return TM_ForcedByUser;
41770560a0aSMichael Kruse 
41871bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
41972448525SMichael Kruse     return TM_Disable;
42072448525SMichael Kruse 
42171bd59f0SDavid Sherwood   if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
42272448525SMichael Kruse     return TM_Enable;
42372448525SMichael Kruse 
42472448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
42572448525SMichael Kruse     return TM_Disable;
42672448525SMichael Kruse 
42772448525SMichael Kruse   return TM_Unspecified;
42872448525SMichael Kruse }
42972448525SMichael Kruse 
430ddb3b26aSBardia Mahjour TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
43172448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
43272448525SMichael Kruse     return TM_ForcedByUser;
43372448525SMichael Kruse 
43472448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
43572448525SMichael Kruse     return TM_Disable;
43672448525SMichael Kruse 
43772448525SMichael Kruse   return TM_Unspecified;
43872448525SMichael Kruse }
43972448525SMichael Kruse 
440ddb3b26aSBardia Mahjour TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
44172448525SMichael Kruse   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
44272448525SMichael Kruse     return TM_SuppressedByUser;
44372448525SMichael Kruse 
44472448525SMichael Kruse   if (hasDisableAllTransformsHint(L))
44572448525SMichael Kruse     return TM_Disable;
44672448525SMichael Kruse 
44772448525SMichael Kruse   return TM_Unspecified;
448963341c8SAdam Nemet }
449122f984aSEvgeniy Stepanov 
4507ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
4517ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
4527ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
4537ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
4547ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
4557ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
4567ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
4577ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
4587ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
4597ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
4607ed5856aSAlina Sbirlea   };
4617ed5856aSAlina Sbirlea 
4627ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
4637ed5856aSAlina Sbirlea 
46476c5cb05SNicolai Hähnle   for (size_t I = 0; I < Worklist.size(); I++) {
46576c5cb05SNicolai Hähnle     for (DomTreeNode *Child : Worklist[I]->children())
4667ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
46776c5cb05SNicolai Hähnle   }
4687ed5856aSAlina Sbirlea 
4697ed5856aSAlina Sbirlea   return Worklist;
4707ed5856aSAlina Sbirlea }
4717ed5856aSAlina Sbirlea 
472efb130fcSAlina Sbirlea void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
473efb130fcSAlina Sbirlea                           LoopInfo *LI, MemorySSA *MSSA) {
474899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
475df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
476df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
477df3e71e0SMarcello Maggioni 
478efb130fcSAlina Sbirlea   std::unique_ptr<MemorySSAUpdater> MSSAU;
479efb130fcSAlina Sbirlea   if (MSSA)
480efb130fcSAlina Sbirlea     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
481efb130fcSAlina Sbirlea 
482df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
483df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
484df3e71e0SMarcello Maggioni   //
485df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
486df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
487df3e71e0SMarcello Maggioni 
488df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
489df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
490df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
491df3e71e0SMarcello Maggioni   if (SE)
492df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
493df3e71e0SMarcello Maggioni 
494df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
495df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
496df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
497df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
498df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
499df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
500df3e71e0SMarcello Maggioni   // preheader -> header.
501df3e71e0SMarcello Maggioni   //
502df3e71e0SMarcello Maggioni   //
503df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
504df3e71e0SMarcello Maggioni   //        |                    |   |                   |
505df3e71e0SMarcello Maggioni   //        V                    |   V                   |
506df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
507df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
508df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
509df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
510df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
511df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
512df3e71e0SMarcello Maggioni   //
513df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
514df3e71e0SMarcello Maggioni   // update without using the batch update API.
515df3e71e0SMarcello Maggioni   //
516df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
517df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
518df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
519df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
520df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
521df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
522df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
523babc224cSAtmn Patel 
524babc224cSAtmn Patel   auto *ExitBlock = L->getUniqueExitBlock();
525f88a7975SAtmn Patel   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
526babc224cSAtmn Patel   if (ExitBlock) {
527babc224cSAtmn Patel     assert(ExitBlock && "Should have a unique exit block!");
528babc224cSAtmn Patel     assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
529babc224cSAtmn Patel 
530df3e71e0SMarcello Maggioni     Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
531df3e71e0SMarcello Maggioni     // Remove the old branch. The conditional branch becomes a new terminator.
532df3e71e0SMarcello Maggioni     OldBr->eraseFromParent();
533df3e71e0SMarcello Maggioni 
534df3e71e0SMarcello Maggioni     // Rewrite phis in the exit block to get their inputs from the Preheader
535df3e71e0SMarcello Maggioni     // instead of the exiting block.
536c7fc81e6SBenjamin Kramer     for (PHINode &P : ExitBlock->phis()) {
537df3e71e0SMarcello Maggioni       // Set the zero'th element of Phi to be from the preheader and remove all
538df3e71e0SMarcello Maggioni       // other incoming values. Given the loop has dedicated exits, all other
539df3e71e0SMarcello Maggioni       // incoming values must be from the exiting blocks.
540df3e71e0SMarcello Maggioni       int PredIndex = 0;
541c7fc81e6SBenjamin Kramer       P.setIncomingBlock(PredIndex, Preheader);
542df3e71e0SMarcello Maggioni       // Removes all incoming values from all other exiting blocks (including
543df3e71e0SMarcello Maggioni       // duplicate values from an exiting block).
544df3e71e0SMarcello Maggioni       // Nuke all entries except the zero'th entry which is the preheader entry.
545df3e71e0SMarcello Maggioni       // NOTE! We need to remove Incoming Values in the reverse order as done
546df3e71e0SMarcello Maggioni       // below, to keep the indices valid for deletion (removeIncomingValues
547babc224cSAtmn Patel       // updates getNumIncomingValues and shifts all values down into the
548babc224cSAtmn Patel       // operand being deleted).
549c7fc81e6SBenjamin Kramer       for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
550c7fc81e6SBenjamin Kramer         P.removeIncomingValue(e - i, false);
551df3e71e0SMarcello Maggioni 
552c7fc81e6SBenjamin Kramer       assert((P.getNumIncomingValues() == 1 &&
553c7fc81e6SBenjamin Kramer               P.getIncomingBlock(PredIndex) == Preheader) &&
554df3e71e0SMarcello Maggioni              "Should have exactly one value and that's from the preheader!");
555df3e71e0SMarcello Maggioni     }
556df3e71e0SMarcello Maggioni 
557efb130fcSAlina Sbirlea     if (DT) {
558efb130fcSAlina Sbirlea       DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
559efb130fcSAlina Sbirlea       if (MSSA) {
560babc224cSAtmn Patel         MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
561babc224cSAtmn Patel                             *DT);
562efb130fcSAlina Sbirlea         if (VerifyMemorySSA)
563efb130fcSAlina Sbirlea           MSSA->verifyMemorySSA();
564efb130fcSAlina Sbirlea       }
565efb130fcSAlina Sbirlea     }
566efb130fcSAlina Sbirlea 
567df3e71e0SMarcello Maggioni     // Disconnect the loop body by branching directly to its exit.
568df3e71e0SMarcello Maggioni     Builder.SetInsertPoint(Preheader->getTerminator());
569df3e71e0SMarcello Maggioni     Builder.CreateBr(ExitBlock);
570df3e71e0SMarcello Maggioni     // Remove the old branch.
571df3e71e0SMarcello Maggioni     Preheader->getTerminator()->eraseFromParent();
572f88a7975SAtmn Patel   } else {
573f88a7975SAtmn Patel     assert(L->hasNoExitBlocks() &&
574f88a7975SAtmn Patel            "Loop should have either zero or one exit blocks.");
575f88a7975SAtmn Patel 
576f88a7975SAtmn Patel     Builder.SetInsertPoint(OldBr);
577f88a7975SAtmn Patel     Builder.CreateUnreachable();
578f88a7975SAtmn Patel     Preheader->getTerminator()->eraseFromParent();
579f88a7975SAtmn Patel   }
580df3e71e0SMarcello Maggioni 
581df3e71e0SMarcello Maggioni   if (DT) {
582efb130fcSAlina Sbirlea     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
583efb130fcSAlina Sbirlea     if (MSSA) {
584f88a7975SAtmn Patel       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
585f88a7975SAtmn Patel                           *DT);
586efb130fcSAlina Sbirlea       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
587efb130fcSAlina Sbirlea                                                    L->block_end());
588efb130fcSAlina Sbirlea       MSSAU->removeBlocks(DeadBlockSet);
589519b019aSAlina Sbirlea       if (VerifyMemorySSA)
590519b019aSAlina Sbirlea         MSSA->verifyMemorySSA();
591efb130fcSAlina Sbirlea     }
592df3e71e0SMarcello Maggioni   }
593df3e71e0SMarcello Maggioni 
594744c3c32SDavide Italiano   // Use a map to unique and a vector to guarantee deterministic ordering.
5958ee59ca6SDavide Italiano   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
596744c3c32SDavide Italiano   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
597744c3c32SDavide Italiano 
598babc224cSAtmn Patel   if (ExitBlock) {
599a757d65cSSerguei Katkov     // Given LCSSA form is satisfied, we should not have users of instructions
600a757d65cSSerguei Katkov     // within the dead loop outside of the loop. However, LCSSA doesn't take
601a757d65cSSerguei Katkov     // unreachable uses into account. We handle them here.
602a757d65cSSerguei Katkov     // We could do it after drop all references (in this case all users in the
603a757d65cSSerguei Katkov     // loop will be already eliminated and we have less work to do but according
604a757d65cSSerguei Katkov     // to API doc of User::dropAllReferences only valid operation after dropping
605a757d65cSSerguei Katkov     // references, is deletion. So let's substitute all usages of
606a757d65cSSerguei Katkov     // instruction from the loop with undef value of corresponding type first.
607a757d65cSSerguei Katkov     for (auto *Block : L->blocks())
608a757d65cSSerguei Katkov       for (Instruction &I : *Block) {
609a757d65cSSerguei Katkov         auto *Undef = UndefValue::get(I.getType());
6100d182d9dSKazu Hirata         for (Use &U : llvm::make_early_inc_range(I.uses())) {
611a757d65cSSerguei Katkov           if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
612a757d65cSSerguei Katkov             if (L->contains(Usr->getParent()))
613a757d65cSSerguei Katkov               continue;
614a757d65cSSerguei Katkov           // If we have a DT then we can check that uses outside a loop only in
615a757d65cSSerguei Katkov           // unreachable block.
616a757d65cSSerguei Katkov           if (DT)
617a757d65cSSerguei Katkov             assert(!DT->isReachableFromEntry(U) &&
618a757d65cSSerguei Katkov                    "Unexpected user in reachable block");
619a757d65cSSerguei Katkov           U.set(Undef);
620a757d65cSSerguei Katkov         }
621744c3c32SDavide Italiano         auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
622744c3c32SDavide Italiano         if (!DVI)
623744c3c32SDavide Italiano           continue;
624babc224cSAtmn Patel         auto Key =
625babc224cSAtmn Patel             DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
6268ee59ca6SDavide Italiano         if (Key != DeadDebugSet.end())
627744c3c32SDavide Italiano           continue;
6288ee59ca6SDavide Italiano         DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
629744c3c32SDavide Italiano         DeadDebugInst.push_back(DVI);
630a757d65cSSerguei Katkov       }
631a757d65cSSerguei Katkov 
632744c3c32SDavide Italiano     // After the loop has been deleted all the values defined and modified
633744c3c32SDavide Italiano     // inside the loop are going to be unavailable.
634744c3c32SDavide Italiano     // Since debug values in the loop have been deleted, inserting an undef
635744c3c32SDavide Italiano     // dbg.value truncates the range of any dbg.value before the loop where the
636744c3c32SDavide Italiano     // loop used to be. This is particularly important for constant values.
637744c3c32SDavide Italiano     DIBuilder DIB(*ExitBlock->getModule());
638e5be660eSRoman Lebedev     Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
639e5be660eSRoman Lebedev     assert(InsertDbgValueBefore &&
640e5be660eSRoman Lebedev            "There should be a non-PHI instruction in exit block, else these "
641e5be660eSRoman Lebedev            "instructions will have no parent.");
642744c3c32SDavide Italiano     for (auto *DVI : DeadDebugInst)
643e5be660eSRoman Lebedev       DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
644e5be660eSRoman Lebedev                                   DVI->getVariable(), DVI->getExpression(),
645e5be660eSRoman Lebedev                                   DVI->getDebugLoc(), InsertDbgValueBefore);
646babc224cSAtmn Patel   }
647744c3c32SDavide Italiano 
648df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
649df3e71e0SMarcello Maggioni   // delete it freely later.
650df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
651df3e71e0SMarcello Maggioni     Block->dropAllReferences();
652df3e71e0SMarcello Maggioni 
653efb130fcSAlina Sbirlea   if (MSSA && VerifyMemorySSA)
654efb130fcSAlina Sbirlea     MSSA->verifyMemorySSA();
655efb130fcSAlina Sbirlea 
656df3e71e0SMarcello Maggioni   if (LI) {
657df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
658df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
659df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
660df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
661d1abf481SKazu Hirata     for (BasicBlock *BB : L->blocks())
662d1abf481SKazu Hirata       BB->eraseFromParent();
663df3e71e0SMarcello Maggioni 
664df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
665df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
666df3e71e0SMarcello Maggioni 
667df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
668df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
669df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
670df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
671df3e71e0SMarcello Maggioni 
672df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
6739883d7edSWhitney Tsang     // Note: LoopInfo::erase remove the given loop and relink its subloops with
6749883d7edSWhitney Tsang     // its parent. While removeLoop/removeChildLoop remove the given loop but
6759883d7edSWhitney Tsang     // not relink its subloops, which is what we want.
6769883d7edSWhitney Tsang     if (Loop *ParentLoop = L->getParentLoop()) {
6775d6c5b46SWhitney Tsang       Loop::iterator I = find(*ParentLoop, L);
6789883d7edSWhitney Tsang       assert(I != ParentLoop->end() && "Couldn't find loop");
6799883d7edSWhitney Tsang       ParentLoop->removeChildLoop(I);
6809883d7edSWhitney Tsang     } else {
6815d6c5b46SWhitney Tsang       Loop::iterator I = find(*LI, L);
6829883d7edSWhitney Tsang       assert(I != LI->end() && "Couldn't find loop");
6839883d7edSWhitney Tsang       LI->removeLoop(I);
6849883d7edSWhitney Tsang     }
6859883d7edSWhitney Tsang     LI->destroy(L);
686df3e71e0SMarcello Maggioni   }
687df3e71e0SMarcello Maggioni }
688df3e71e0SMarcello Maggioni 
689ef51eed3SPhilip Reames static Loop *getOutermostLoop(Loop *L) {
690ef51eed3SPhilip Reames   while (Loop *Parent = L->getParentLoop())
691ef51eed3SPhilip Reames     L = Parent;
692ef51eed3SPhilip Reames   return L;
693ef51eed3SPhilip Reames }
694ef51eed3SPhilip Reames 
6954739dd67SPhilip Reames void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
6964739dd67SPhilip Reames                              LoopInfo &LI, MemorySSA *MSSA) {
6974739dd67SPhilip Reames   auto *Latch = L->getLoopLatch();
6984739dd67SPhilip Reames   assert(Latch && "multiple latches not yet supported");
6994739dd67SPhilip Reames   auto *Header = L->getHeader();
700ef51eed3SPhilip Reames   Loop *OutermostLoop = getOutermostLoop(L);
7014739dd67SPhilip Reames 
7024739dd67SPhilip Reames   SE.forgetLoop(L);
7034739dd67SPhilip Reames 
7044739dd67SPhilip Reames   std::unique_ptr<MemorySSAUpdater> MSSAU;
7054739dd67SPhilip Reames   if (MSSA)
7064739dd67SPhilip Reames     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
7074739dd67SPhilip Reames 
7086a823760SPhilip Reames   // Update the CFG and domtree.  We chose to special case a couple of
7096a823760SPhilip Reames   // of common cases for code quality and test readability reasons.
7106a823760SPhilip Reames   [&]() -> void {
7116a823760SPhilip Reames     if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) {
7126a823760SPhilip Reames       if (!BI->isConditional()) {
7136a823760SPhilip Reames         DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
7146a823760SPhilip Reames         (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU,
7156a823760SPhilip Reames                                   MSSAU.get());
7166a823760SPhilip Reames         return;
7176a823760SPhilip Reames       }
7186a823760SPhilip Reames 
7196a823760SPhilip Reames       // Conditional latch/exit - note that latch can be shared by inner
7206a823760SPhilip Reames       // and outer loop so the other target doesn't need to an exit
7216a823760SPhilip Reames       if (L->isLoopExiting(Latch)) {
7226a823760SPhilip Reames         // TODO: Generalize ConstantFoldTerminator so that it can be used
723c3b3aa27SPhilip Reames         // here without invalidating LCSSA or MemorySSA.  (Tricky case for
724c3b3aa27SPhilip Reames         // LCSSA: header is an exit block of a preceeding sibling loop w/o
725c3b3aa27SPhilip Reames         // dedicated exits.)
7266a823760SPhilip Reames         const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
7276a823760SPhilip Reames         BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
7286a823760SPhilip Reames 
7296a823760SPhilip Reames         DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
7306a823760SPhilip Reames         Header->removePredecessor(Latch, true);
7316a823760SPhilip Reames 
7326a823760SPhilip Reames         IRBuilder<> Builder(BI);
7336a823760SPhilip Reames         auto *NewBI = Builder.CreateBr(ExitBB);
7346a823760SPhilip Reames         // Transfer the metadata to the new branch instruction (minus the
7356a823760SPhilip Reames         // loop info since this is no longer a loop)
7366a823760SPhilip Reames         NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
7376a823760SPhilip Reames                                   LLVMContext::MD_annotation});
7386a823760SPhilip Reames 
7396a823760SPhilip Reames         BI->eraseFromParent();
7406a823760SPhilip Reames         DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
741c3b3aa27SPhilip Reames         if (MSSA)
742c3b3aa27SPhilip Reames           MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
7436a823760SPhilip Reames         return;
7446a823760SPhilip Reames       }
7456a823760SPhilip Reames     }
7466a823760SPhilip Reames 
7476a823760SPhilip Reames     // General case.  By splitting the backedge, and then explicitly making it
7486a823760SPhilip Reames     // unreachable we gracefully handle corner cases such as switch and invoke
7496a823760SPhilip Reames     // termiantors.
7504739dd67SPhilip Reames     auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
7514739dd67SPhilip Reames 
7524739dd67SPhilip Reames     DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
75325a3130dSJohannes Doerfert     (void)changeToUnreachable(BackedgeBB->getTerminator(),
7544739dd67SPhilip Reames                               /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
7556a823760SPhilip Reames   }();
7564739dd67SPhilip Reames 
7574739dd67SPhilip Reames   // Erase (and destroy) this loop instance.  Handles relinking sub-loops
7584739dd67SPhilip Reames   // and blocks within the loop as needed.
7594739dd67SPhilip Reames   LI.erase(L);
760ef51eed3SPhilip Reames 
761ef51eed3SPhilip Reames   // If the loop we broke had a parent, then changeToUnreachable might have
762ef51eed3SPhilip Reames   // caused a block to be removed from the parent loop (see loop_nest_lcssa
763ef51eed3SPhilip Reames   // test case in zero-btc.ll for an example), thus changing the parent's
764ef51eed3SPhilip Reames   // exit blocks.  If that happened, we need to rebuild LCSSA on the outermost
765ef51eed3SPhilip Reames   // loop which might have a had a block removed.
766ef51eed3SPhilip Reames   if (OutermostLoop != L)
767ef51eed3SPhilip Reames     formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
7684739dd67SPhilip Reames }
7694739dd67SPhilip Reames 
7704739dd67SPhilip Reames 
7712d31b025SPhilip Reames /// Checks if \p L has an exiting latch branch.  There may also be other
7722d31b025SPhilip Reames /// exiting blocks.  Returns branch instruction terminating the loop
773af7e1588SEvgeniy Brevnov /// latch if above check is successful, nullptr otherwise.
774af7e1588SEvgeniy Brevnov static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
77545c43e7dSSerguei Katkov   BasicBlock *Latch = L->getLoopLatch();
77645c43e7dSSerguei Katkov   if (!Latch)
777af7e1588SEvgeniy Brevnov     return nullptr;
778af7e1588SEvgeniy Brevnov 
77945c43e7dSSerguei Katkov   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
78045c43e7dSSerguei Katkov   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
781af7e1588SEvgeniy Brevnov     return nullptr;
78241d72a86SDehao Chen 
78341d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
78441d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
78541d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
78641d72a86SDehao Chen 
787af7e1588SEvgeniy Brevnov   return LatchBR;
788af7e1588SEvgeniy Brevnov }
789af7e1588SEvgeniy Brevnov 
790f632c494SPhilip Reames /// Return the estimated trip count for any exiting branch which dominates
791f632c494SPhilip Reames /// the loop latch.
792f632c494SPhilip Reames static Optional<uint64_t>
793f632c494SPhilip Reames getEstimatedTripCount(BranchInst *ExitingBranch, Loop *L,
794f632c494SPhilip Reames                       uint64_t &OrigExitWeight) {
795f632c494SPhilip Reames   // To estimate the number of times the loop body was executed, we want to
796f632c494SPhilip Reames   // know the number of times the backedge was taken, vs. the number of times
797f632c494SPhilip Reames   // we exited the loop.
798f632c494SPhilip Reames   uint64_t LoopWeight, ExitWeight;
799f632c494SPhilip Reames   if (!ExitingBranch->extractProfMetadata(LoopWeight, ExitWeight))
800f632c494SPhilip Reames     return None;
801f632c494SPhilip Reames 
802f632c494SPhilip Reames   if (L->contains(ExitingBranch->getSuccessor(1)))
803f632c494SPhilip Reames     std::swap(LoopWeight, ExitWeight);
804f632c494SPhilip Reames 
805f632c494SPhilip Reames   if (!ExitWeight)
806f632c494SPhilip Reames     // Don't have a way to return predicated infinite
807f632c494SPhilip Reames     return None;
808f632c494SPhilip Reames 
809f632c494SPhilip Reames   OrigExitWeight = ExitWeight;
810f632c494SPhilip Reames 
811f632c494SPhilip Reames   // Estimated exit count is a ratio of the loop weight by the weight of the
812f632c494SPhilip Reames   // edge exiting the loop, rounded to nearest.
813f632c494SPhilip Reames   uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
814f632c494SPhilip Reames   // Estimated trip count is one plus estimated exit count.
815f632c494SPhilip Reames   return ExitCount + 1;
816f632c494SPhilip Reames }
817f632c494SPhilip Reames 
818af7e1588SEvgeniy Brevnov Optional<unsigned>
819af7e1588SEvgeniy Brevnov llvm::getLoopEstimatedTripCount(Loop *L,
820af7e1588SEvgeniy Brevnov                                 unsigned *EstimatedLoopInvocationWeight) {
8212d31b025SPhilip Reames   // Currently we take the estimate exit count only from the loop latch,
8222d31b025SPhilip Reames   // ignoring other exiting blocks.  This can overestimate the trip count
8232d31b025SPhilip Reames   // if we exit through another exit, but can never underestimate it.
8242d31b025SPhilip Reames   // TODO: incorporate information from other exits
825f632c494SPhilip Reames   if (BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L)) {
826f632c494SPhilip Reames     uint64_t ExitWeight;
827f632c494SPhilip Reames     if (Optional<uint64_t> EstTripCount =
828f632c494SPhilip Reames         getEstimatedTripCount(LatchBranch, L, ExitWeight)) {
829af7e1588SEvgeniy Brevnov       if (EstimatedLoopInvocationWeight)
830f632c494SPhilip Reames         *EstimatedLoopInvocationWeight = ExitWeight;
831f632c494SPhilip Reames       return *EstTripCount;
832f632c494SPhilip Reames     }
833f632c494SPhilip Reames   }
834f632c494SPhilip Reames   return None;
83541d72a86SDehao Chen }
836cf9daa33SAmara Emerson 
837af7e1588SEvgeniy Brevnov bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
838af7e1588SEvgeniy Brevnov                                      unsigned EstimatedloopInvocationWeight) {
8392d31b025SPhilip Reames   // At the moment, we currently support changing the estimate trip count of
8402d31b025SPhilip Reames   // the latch branch only.  We could extend this API to manipulate estimated
8412d31b025SPhilip Reames   // trip counts for any exit.
842af7e1588SEvgeniy Brevnov   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
843af7e1588SEvgeniy Brevnov   if (!LatchBranch)
844af7e1588SEvgeniy Brevnov     return false;
845af7e1588SEvgeniy Brevnov 
846af7e1588SEvgeniy Brevnov   // Calculate taken and exit weights.
847af7e1588SEvgeniy Brevnov   unsigned LatchExitWeight = 0;
848af7e1588SEvgeniy Brevnov   unsigned BackedgeTakenWeight = 0;
849af7e1588SEvgeniy Brevnov 
850af7e1588SEvgeniy Brevnov   if (EstimatedTripCount > 0) {
851af7e1588SEvgeniy Brevnov     LatchExitWeight = EstimatedloopInvocationWeight;
852af7e1588SEvgeniy Brevnov     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
853af7e1588SEvgeniy Brevnov   }
854af7e1588SEvgeniy Brevnov 
855af7e1588SEvgeniy Brevnov   // Make a swap if back edge is taken when condition is "false".
856af7e1588SEvgeniy Brevnov   if (LatchBranch->getSuccessor(0) != L->getHeader())
857af7e1588SEvgeniy Brevnov     std::swap(BackedgeTakenWeight, LatchExitWeight);
858af7e1588SEvgeniy Brevnov 
859af7e1588SEvgeniy Brevnov   MDBuilder MDB(LatchBranch->getContext());
860af7e1588SEvgeniy Brevnov 
861af7e1588SEvgeniy Brevnov   // Set/Update profile metadata.
862af7e1588SEvgeniy Brevnov   LatchBranch->setMetadata(
863af7e1588SEvgeniy Brevnov       LLVMContext::MD_prof,
864af7e1588SEvgeniy Brevnov       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
865af7e1588SEvgeniy Brevnov 
866af7e1588SEvgeniy Brevnov   return true;
867af7e1588SEvgeniy Brevnov }
868af7e1588SEvgeniy Brevnov 
8696cb64787SDavid Green bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
870395b80cdSDavid Green                                               ScalarEvolution &SE) {
871395b80cdSDavid Green   Loop *OuterL = InnerLoop->getParentLoop();
872395b80cdSDavid Green   if (!OuterL)
873395b80cdSDavid Green     return true;
874395b80cdSDavid Green 
875395b80cdSDavid Green   // Get the backedge taken count for the inner loop
876395b80cdSDavid Green   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
877395b80cdSDavid Green   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
878395b80cdSDavid Green   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
879395b80cdSDavid Green       !InnerLoopBECountSC->getType()->isIntegerTy())
880395b80cdSDavid Green     return false;
881395b80cdSDavid Green 
882395b80cdSDavid Green   // Get whether count is invariant to the outer loop
883395b80cdSDavid Green   ScalarEvolution::LoopDisposition LD =
884395b80cdSDavid Green       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
885395b80cdSDavid Green   if (LD != ScalarEvolution::LoopInvariant)
886395b80cdSDavid Green     return false;
887395b80cdSDavid Green 
888395b80cdSDavid Green   return true;
889395b80cdSDavid Green }
890395b80cdSDavid Green 
8910dcd2b40SSimon Pilgrim CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
8926594dc37SVikram TV   switch (RK) {
8936594dc37SVikram TV   default:
8946594dc37SVikram TV     llvm_unreachable("Unknown min/max recurrence kind");
895c74e8539SSanjay Patel   case RecurKind::UMin:
8960dcd2b40SSimon Pilgrim     return CmpInst::ICMP_ULT;
897c74e8539SSanjay Patel   case RecurKind::UMax:
8980dcd2b40SSimon Pilgrim     return CmpInst::ICMP_UGT;
899c74e8539SSanjay Patel   case RecurKind::SMin:
9000dcd2b40SSimon Pilgrim     return CmpInst::ICMP_SLT;
901c74e8539SSanjay Patel   case RecurKind::SMax:
9020dcd2b40SSimon Pilgrim     return CmpInst::ICMP_SGT;
903c74e8539SSanjay Patel   case RecurKind::FMin:
9040dcd2b40SSimon Pilgrim     return CmpInst::FCMP_OLT;
905c74e8539SSanjay Patel   case RecurKind::FMax:
9060dcd2b40SSimon Pilgrim     return CmpInst::FCMP_OGT;
9070dcd2b40SSimon Pilgrim   }
9086594dc37SVikram TV }
9096594dc37SVikram TV 
91026b7d9d6SDavid Sherwood Value *llvm::createSelectCmpOp(IRBuilderBase &Builder, Value *StartVal,
91126b7d9d6SDavid Sherwood                                RecurKind RK, Value *Left, Value *Right) {
91226b7d9d6SDavid Sherwood   if (auto VTy = dyn_cast<VectorType>(Left->getType()))
91326b7d9d6SDavid Sherwood     StartVal = Builder.CreateVectorSplat(VTy->getElementCount(), StartVal);
91426b7d9d6SDavid Sherwood   Value *Cmp =
91526b7d9d6SDavid Sherwood       Builder.CreateCmp(CmpInst::ICMP_NE, Left, StartVal, "rdx.select.cmp");
91626b7d9d6SDavid Sherwood   return Builder.CreateSelect(Cmp, Left, Right, "rdx.select");
91726b7d9d6SDavid Sherwood }
91826b7d9d6SDavid Sherwood 
9190dcd2b40SSimon Pilgrim Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
9200dcd2b40SSimon Pilgrim                             Value *Right) {
9210dcd2b40SSimon Pilgrim   CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
92209b1c563SSanjay Patel   Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
9236594dc37SVikram TV   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
9246594dc37SVikram TV   return Select;
9256594dc37SVikram TV }
9266594dc37SVikram TV 
92723c2182cSSimon Pilgrim // Helper to generate an ordered reduction.
928c74e8539SSanjay Patel Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
929b24db85cSPhilip Reames                                  unsigned Op, RecurKind RdxKind) {
9308d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
93123c2182cSSimon Pilgrim 
93223c2182cSSimon Pilgrim   // Extract and apply reduction ops in ascending order:
93323c2182cSSimon Pilgrim   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
93423c2182cSSimon Pilgrim   Value *Result = Acc;
93523c2182cSSimon Pilgrim   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
93623c2182cSSimon Pilgrim     Value *Ext =
93723c2182cSSimon Pilgrim         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
93823c2182cSSimon Pilgrim 
93923c2182cSSimon Pilgrim     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
94023c2182cSSimon Pilgrim       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
94123c2182cSSimon Pilgrim                                    "bin.rdx");
94223c2182cSSimon Pilgrim     } else {
943c74e8539SSanjay Patel       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
94423c2182cSSimon Pilgrim              "Invalid min/max");
945c74e8539SSanjay Patel       Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
94623c2182cSSimon Pilgrim     }
94723c2182cSSimon Pilgrim   }
94823c2182cSSimon Pilgrim 
94923c2182cSSimon Pilgrim   return Result;
95023c2182cSSimon Pilgrim }
95123c2182cSSimon Pilgrim 
952cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
953c74e8539SSanjay Patel Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
954b24db85cSPhilip Reames                                  unsigned Op, RecurKind RdxKind) {
9558d11ec66SChristopher Tetreault   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
956cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
957cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
958cf9daa33SAmara Emerson   // round.
959cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
960cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
9610d13f94cSPhilip Reames   // Note: fast-math-flags flags are controlled by the builder configuration
9620d13f94cSPhilip Reames   // and are assumed to apply to all generated arithmetic instructions.  Other
9630d13f94cSPhilip Reames   // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
9640d13f94cSPhilip Reames   // of the builder configuration, and since they're not passed explicitly,
9650d13f94cSPhilip Reames   // will never be relevant here.  Note that it would be generally unsound to
9660d13f94cSPhilip Reames   // propagate these from an intrinsic call to the expansion anyways as we/
9670d13f94cSPhilip Reames   // change the order of operations.
968cf9daa33SAmara Emerson   Value *TmpVec = Src;
9696f64dacaSBenjamin Kramer   SmallVector<int, 32> ShuffleMask(VF);
970cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
971cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
972cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
9736f64dacaSBenjamin Kramer       ShuffleMask[j] = i / 2 + j;
974cf9daa33SAmara Emerson 
975cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
9766f64dacaSBenjamin Kramer     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
977cf9daa33SAmara Emerson 
9789b296102SJuneyoung Lee     Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
979cf9daa33SAmara Emerson 
980cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
981ad62a3a2SSanjay Patel       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
982ad62a3a2SSanjay Patel                                    "bin.rdx");
983cf9daa33SAmara Emerson     } else {
984c74e8539SSanjay Patel       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
985cf9daa33SAmara Emerson              "Invalid min/max");
986c74e8539SSanjay Patel       TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
987cf9daa33SAmara Emerson     }
988cf9daa33SAmara Emerson   }
989cf9daa33SAmara Emerson   // The result is in the first element of the vector.
990cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
991cf9daa33SAmara Emerson }
992cf9daa33SAmara Emerson 
99326b7d9d6SDavid Sherwood Value *llvm::createSelectCmpTargetReduction(IRBuilderBase &Builder,
99426b7d9d6SDavid Sherwood                                             const TargetTransformInfo *TTI,
99526b7d9d6SDavid Sherwood                                             Value *Src,
99626b7d9d6SDavid Sherwood                                             const RecurrenceDescriptor &Desc,
99726b7d9d6SDavid Sherwood                                             PHINode *OrigPhi) {
99826b7d9d6SDavid Sherwood   assert(RecurrenceDescriptor::isSelectCmpRecurrenceKind(
99926b7d9d6SDavid Sherwood              Desc.getRecurrenceKind()) &&
100026b7d9d6SDavid Sherwood          "Unexpected reduction kind");
100126b7d9d6SDavid Sherwood   Value *InitVal = Desc.getRecurrenceStartValue();
100226b7d9d6SDavid Sherwood   Value *NewVal = nullptr;
100326b7d9d6SDavid Sherwood 
100426b7d9d6SDavid Sherwood   // First use the original phi to determine the new value we're trying to
100526b7d9d6SDavid Sherwood   // select from in the loop.
100626b7d9d6SDavid Sherwood   SelectInst *SI = nullptr;
100726b7d9d6SDavid Sherwood   for (auto *U : OrigPhi->users()) {
100826b7d9d6SDavid Sherwood     if ((SI = dyn_cast<SelectInst>(U)))
100926b7d9d6SDavid Sherwood       break;
101026b7d9d6SDavid Sherwood   }
101126b7d9d6SDavid Sherwood   assert(SI && "One user of the original phi should be a select");
101226b7d9d6SDavid Sherwood 
101326b7d9d6SDavid Sherwood   if (SI->getTrueValue() == OrigPhi)
101426b7d9d6SDavid Sherwood     NewVal = SI->getFalseValue();
101526b7d9d6SDavid Sherwood   else {
101626b7d9d6SDavid Sherwood     assert(SI->getFalseValue() == OrigPhi &&
101726b7d9d6SDavid Sherwood            "At least one input to the select should be the original Phi");
101826b7d9d6SDavid Sherwood     NewVal = SI->getTrueValue();
101926b7d9d6SDavid Sherwood   }
102026b7d9d6SDavid Sherwood 
102126b7d9d6SDavid Sherwood   // Create a splat vector with the new value and compare this to the vector
102226b7d9d6SDavid Sherwood   // we want to reduce.
102326b7d9d6SDavid Sherwood   ElementCount EC = cast<VectorType>(Src->getType())->getElementCount();
102426b7d9d6SDavid Sherwood   Value *Right = Builder.CreateVectorSplat(EC, InitVal);
102526b7d9d6SDavid Sherwood   Value *Cmp =
102626b7d9d6SDavid Sherwood       Builder.CreateCmp(CmpInst::ICMP_NE, Src, Right, "rdx.select.cmp");
102726b7d9d6SDavid Sherwood 
102826b7d9d6SDavid Sherwood   // If any predicate is true it means that we want to select the new value.
102926b7d9d6SDavid Sherwood   Cmp = Builder.CreateOrReduce(Cmp);
103026b7d9d6SDavid Sherwood   return Builder.CreateSelect(Cmp, NewVal, InitVal, "rdx.select");
103126b7d9d6SDavid Sherwood }
103226b7d9d6SDavid Sherwood 
1033c74e8539SSanjay Patel Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder,
1034c74e8539SSanjay Patel                                          const TargetTransformInfo *TTI,
1035b24db85cSPhilip Reames                                          Value *Src, RecurKind RdxKind) {
103697669575SSanjay Patel   auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
103736263a7cSSanjay Patel   switch (RdxKind) {
103836263a7cSSanjay Patel   case RecurKind::Add:
103997669575SSanjay Patel     return Builder.CreateAddReduce(Src);
104036263a7cSSanjay Patel   case RecurKind::Mul:
104197669575SSanjay Patel     return Builder.CreateMulReduce(Src);
104236263a7cSSanjay Patel   case RecurKind::And:
104397669575SSanjay Patel     return Builder.CreateAndReduce(Src);
104436263a7cSSanjay Patel   case RecurKind::Or:
104597669575SSanjay Patel     return Builder.CreateOrReduce(Src);
104636263a7cSSanjay Patel   case RecurKind::Xor:
104797669575SSanjay Patel     return Builder.CreateXorReduce(Src);
1048c2441b6bSRosie Sumpter   case RecurKind::FMulAdd:
104936263a7cSSanjay Patel   case RecurKind::FAdd:
105097669575SSanjay Patel     return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy),
105197669575SSanjay Patel                                     Src);
105236263a7cSSanjay Patel   case RecurKind::FMul:
105397669575SSanjay Patel     return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src);
1054c74e8539SSanjay Patel   case RecurKind::SMax:
105597669575SSanjay Patel     return Builder.CreateIntMaxReduce(Src, true);
1056c74e8539SSanjay Patel   case RecurKind::SMin:
105797669575SSanjay Patel     return Builder.CreateIntMinReduce(Src, true);
1058c74e8539SSanjay Patel   case RecurKind::UMax:
105997669575SSanjay Patel     return Builder.CreateIntMaxReduce(Src, false);
1060c74e8539SSanjay Patel   case RecurKind::UMin:
106197669575SSanjay Patel     return Builder.CreateIntMinReduce(Src, false);
106236263a7cSSanjay Patel   case RecurKind::FMax:
106397669575SSanjay Patel     return Builder.CreateFPMaxReduce(Src);
106436263a7cSSanjay Patel   case RecurKind::FMin:
106597669575SSanjay Patel     return Builder.CreateFPMinReduce(Src);
1066cf9daa33SAmara Emerson   default:
1067cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1068cf9daa33SAmara Emerson   }
1069cf9daa33SAmara Emerson }
1070cf9daa33SAmara Emerson 
107128ffe38bSNikita Popov Value *llvm::createTargetReduction(IRBuilderBase &B,
1072cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
107326b7d9d6SDavid Sherwood                                    const RecurrenceDescriptor &Desc, Value *Src,
107426b7d9d6SDavid Sherwood                                    PHINode *OrigPhi) {
1075cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
1076ad62a3a2SSanjay Patel   // All ops in the reduction inherit fast-math-flags from the recurrence
1077ad62a3a2SSanjay Patel   // descriptor.
107828ffe38bSNikita Popov   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1079ad62a3a2SSanjay Patel   B.setFastMathFlags(Desc.getFastMathFlags());
108026b7d9d6SDavid Sherwood 
108126b7d9d6SDavid Sherwood   RecurKind RK = Desc.getRecurrenceKind();
108226b7d9d6SDavid Sherwood   if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
108326b7d9d6SDavid Sherwood     return createSelectCmpTargetReduction(B, TTI, Src, Desc, OrigPhi);
108426b7d9d6SDavid Sherwood 
108526b7d9d6SDavid Sherwood   return createSimpleTargetReduction(B, TTI, Src, RK);
1086cf9daa33SAmara Emerson }
1087cf9daa33SAmara Emerson 
10887344f3d3SKerry McLaughlin Value *llvm::createOrderedReduction(IRBuilderBase &B,
10895e6bfb66SSimon Pilgrim                                     const RecurrenceDescriptor &Desc,
10905e6bfb66SSimon Pilgrim                                     Value *Src, Value *Start) {
1091c2441b6bSRosie Sumpter   assert((Desc.getRecurrenceKind() == RecurKind::FAdd ||
1092c2441b6bSRosie Sumpter           Desc.getRecurrenceKind() == RecurKind::FMulAdd) &&
1093ce4acb01SBenjamin Kramer          "Unexpected reduction kind");
10947344f3d3SKerry McLaughlin   assert(Src->getType()->isVectorTy() && "Expected a vector type");
10957344f3d3SKerry McLaughlin   assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
10967344f3d3SKerry McLaughlin 
10977344f3d3SKerry McLaughlin   return B.CreateFAddReduce(Start, Src);
10987344f3d3SKerry McLaughlin }
10997344f3d3SKerry McLaughlin 
1100a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1101a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1102a61f4b89SDinar Temirbulatov   if (!VecOp)
1103a61f4b89SDinar Temirbulatov     return;
1104a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1105a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1106a61f4b89SDinar Temirbulatov   if (!Intersection)
1107a61f4b89SDinar Temirbulatov     return;
1108a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1109a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1110a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1111a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1112a61f4b89SDinar Temirbulatov     if (!Instr)
1113a61f4b89SDinar Temirbulatov       continue;
1114a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1115a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1116cf9daa33SAmara Emerson   }
1117cf9daa33SAmara Emerson }
1118a78dc4d6SMax Kazantsev 
1119a78dc4d6SMax Kazantsev bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1120a78dc4d6SMax Kazantsev                                  ScalarEvolution &SE) {
1121a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1122a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1123a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1124a78dc4d6SMax Kazantsev }
1125a78dc4d6SMax Kazantsev 
1126a78dc4d6SMax Kazantsev bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1127a78dc4d6SMax Kazantsev                                     ScalarEvolution &SE) {
1128a78dc4d6SMax Kazantsev   const SCEV *Zero = SE.getZero(S->getType());
1129a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1130a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1131a78dc4d6SMax Kazantsev }
1132a78dc4d6SMax Kazantsev 
1133a78dc4d6SMax Kazantsev bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1134a78dc4d6SMax Kazantsev                              bool Signed) {
1135a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1136a78dc4d6SMax Kazantsev   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1137a78dc4d6SMax Kazantsev     APInt::getMinValue(BitWidth);
1138a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1139a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1140a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1141a78dc4d6SMax Kazantsev                                      SE.getConstant(Min));
1142a78dc4d6SMax Kazantsev }
1143a78dc4d6SMax Kazantsev 
1144a78dc4d6SMax Kazantsev bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1145a78dc4d6SMax Kazantsev                              bool Signed) {
1146a78dc4d6SMax Kazantsev   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1147a78dc4d6SMax Kazantsev   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1148a78dc4d6SMax Kazantsev     APInt::getMaxValue(BitWidth);
1149a78dc4d6SMax Kazantsev   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1150a78dc4d6SMax Kazantsev   return SE.isAvailableAtLoopEntry(S, L) &&
1151a78dc4d6SMax Kazantsev          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1152a78dc4d6SMax Kazantsev                                      SE.getConstant(Max));
1153a78dc4d6SMax Kazantsev }
115493175a5cSSjoerd Meijer 
115593175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
115693175a5cSSjoerd Meijer // rewriteLoopExitValues - Optimize IV users outside the loop.
115793175a5cSSjoerd Meijer // As a side effect, reduces the amount of IV processing within the loop.
115893175a5cSSjoerd Meijer //===----------------------------------------------------------------------===//
115993175a5cSSjoerd Meijer 
116093175a5cSSjoerd Meijer static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
116193175a5cSSjoerd Meijer   SmallPtrSet<const Instruction *, 8> Visited;
116293175a5cSSjoerd Meijer   SmallVector<const Instruction *, 8> WorkList;
116393175a5cSSjoerd Meijer   Visited.insert(I);
116493175a5cSSjoerd Meijer   WorkList.push_back(I);
116593175a5cSSjoerd Meijer   while (!WorkList.empty()) {
116693175a5cSSjoerd Meijer     const Instruction *Curr = WorkList.pop_back_val();
116793175a5cSSjoerd Meijer     // This use is outside the loop, nothing to do.
116893175a5cSSjoerd Meijer     if (!L->contains(Curr))
116993175a5cSSjoerd Meijer       continue;
117093175a5cSSjoerd Meijer     // Do we assume it is a "hard" use which will not be eliminated easily?
117193175a5cSSjoerd Meijer     if (Curr->mayHaveSideEffects())
117293175a5cSSjoerd Meijer       return true;
117393175a5cSSjoerd Meijer     // Otherwise, add all its users to worklist.
117493175a5cSSjoerd Meijer     for (auto U : Curr->users()) {
117593175a5cSSjoerd Meijer       auto *UI = cast<Instruction>(U);
117693175a5cSSjoerd Meijer       if (Visited.insert(UI).second)
117793175a5cSSjoerd Meijer         WorkList.push_back(UI);
117893175a5cSSjoerd Meijer     }
117993175a5cSSjoerd Meijer   }
118093175a5cSSjoerd Meijer   return false;
118193175a5cSSjoerd Meijer }
118293175a5cSSjoerd Meijer 
118393175a5cSSjoerd Meijer // Collect information about PHI nodes which can be transformed in
118493175a5cSSjoerd Meijer // rewriteLoopExitValues.
118593175a5cSSjoerd Meijer struct RewritePhi {
1186b2df9612SRoman Lebedev   PHINode *PN;               // For which PHI node is this replacement?
1187b2df9612SRoman Lebedev   unsigned Ith;              // For which incoming value?
1188b2df9612SRoman Lebedev   const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1189b2df9612SRoman Lebedev   Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1190b2df9612SRoman Lebedev   bool HighCost;               // Is this expansion a high-cost?
119193175a5cSSjoerd Meijer 
1192b2df9612SRoman Lebedev   RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1193b2df9612SRoman Lebedev              bool H)
1194b2df9612SRoman Lebedev       : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1195b2df9612SRoman Lebedev         HighCost(H) {}
119693175a5cSSjoerd Meijer };
119793175a5cSSjoerd Meijer 
119893175a5cSSjoerd Meijer // Check whether it is possible to delete the loop after rewriting exit
119993175a5cSSjoerd Meijer // value. If it is possible, ignore ReplaceExitValue and do rewriting
120093175a5cSSjoerd Meijer // aggressively.
120193175a5cSSjoerd Meijer static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
120293175a5cSSjoerd Meijer   BasicBlock *Preheader = L->getLoopPreheader();
120393175a5cSSjoerd Meijer   // If there is no preheader, the loop will not be deleted.
120493175a5cSSjoerd Meijer   if (!Preheader)
120593175a5cSSjoerd Meijer     return false;
120693175a5cSSjoerd Meijer 
120793175a5cSSjoerd Meijer   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
120893175a5cSSjoerd Meijer   // We obviate multiple ExitingBlocks case for simplicity.
120993175a5cSSjoerd Meijer   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
121093175a5cSSjoerd Meijer   // after exit value rewriting, we can enhance the logic here.
121193175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 4> ExitingBlocks;
121293175a5cSSjoerd Meijer   L->getExitingBlocks(ExitingBlocks);
121393175a5cSSjoerd Meijer   SmallVector<BasicBlock *, 8> ExitBlocks;
121493175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
121593175a5cSSjoerd Meijer   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
121693175a5cSSjoerd Meijer     return false;
121793175a5cSSjoerd Meijer 
121893175a5cSSjoerd Meijer   BasicBlock *ExitBlock = ExitBlocks[0];
121993175a5cSSjoerd Meijer   BasicBlock::iterator BI = ExitBlock->begin();
122093175a5cSSjoerd Meijer   while (PHINode *P = dyn_cast<PHINode>(BI)) {
122193175a5cSSjoerd Meijer     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
122293175a5cSSjoerd Meijer 
122393175a5cSSjoerd Meijer     // If the Incoming value of P is found in RewritePhiSet, we know it
122493175a5cSSjoerd Meijer     // could be rewritten to use a loop invariant value in transformation
122593175a5cSSjoerd Meijer     // phase later. Skip it in the loop invariant check below.
122693175a5cSSjoerd Meijer     bool found = false;
122793175a5cSSjoerd Meijer     for (const RewritePhi &Phi : RewritePhiSet) {
122893175a5cSSjoerd Meijer       unsigned i = Phi.Ith;
122993175a5cSSjoerd Meijer       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
123093175a5cSSjoerd Meijer         found = true;
123193175a5cSSjoerd Meijer         break;
123293175a5cSSjoerd Meijer       }
123393175a5cSSjoerd Meijer     }
123493175a5cSSjoerd Meijer 
123593175a5cSSjoerd Meijer     Instruction *I;
123693175a5cSSjoerd Meijer     if (!found && (I = dyn_cast<Instruction>(Incoming)))
123793175a5cSSjoerd Meijer       if (!L->hasLoopInvariantOperands(I))
123893175a5cSSjoerd Meijer         return false;
123993175a5cSSjoerd Meijer 
124093175a5cSSjoerd Meijer     ++BI;
124193175a5cSSjoerd Meijer   }
124293175a5cSSjoerd Meijer 
124393175a5cSSjoerd Meijer   for (auto *BB : L->blocks())
124493175a5cSSjoerd Meijer     if (llvm::any_of(*BB, [](Instruction &I) {
124593175a5cSSjoerd Meijer           return I.mayHaveSideEffects();
124693175a5cSSjoerd Meijer         }))
124793175a5cSSjoerd Meijer       return false;
124893175a5cSSjoerd Meijer 
124993175a5cSSjoerd Meijer   return true;
125093175a5cSSjoerd Meijer }
125193175a5cSSjoerd Meijer 
12520789f280SRoman Lebedev int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
12530789f280SRoman Lebedev                                 ScalarEvolution *SE,
12540789f280SRoman Lebedev                                 const TargetTransformInfo *TTI,
12550789f280SRoman Lebedev                                 SCEVExpander &Rewriter, DominatorTree *DT,
12560789f280SRoman Lebedev                                 ReplaceExitVal ReplaceExitValue,
125793175a5cSSjoerd Meijer                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
125893175a5cSSjoerd Meijer   // Check a pre-condition.
125993175a5cSSjoerd Meijer   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
126093175a5cSSjoerd Meijer          "Indvars did not preserve LCSSA!");
126193175a5cSSjoerd Meijer 
126293175a5cSSjoerd Meijer   SmallVector<BasicBlock*, 8> ExitBlocks;
126393175a5cSSjoerd Meijer   L->getUniqueExitBlocks(ExitBlocks);
126493175a5cSSjoerd Meijer 
126593175a5cSSjoerd Meijer   SmallVector<RewritePhi, 8> RewritePhiSet;
126693175a5cSSjoerd Meijer   // Find all values that are computed inside the loop, but used outside of it.
126793175a5cSSjoerd Meijer   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
126893175a5cSSjoerd Meijer   // the exit blocks of the loop to find them.
126993175a5cSSjoerd Meijer   for (BasicBlock *ExitBB : ExitBlocks) {
127093175a5cSSjoerd Meijer     // If there are no PHI nodes in this exit block, then no values defined
127193175a5cSSjoerd Meijer     // inside the loop are used on this path, skip it.
127293175a5cSSjoerd Meijer     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
127393175a5cSSjoerd Meijer     if (!PN) continue;
127493175a5cSSjoerd Meijer 
127593175a5cSSjoerd Meijer     unsigned NumPreds = PN->getNumIncomingValues();
127693175a5cSSjoerd Meijer 
127793175a5cSSjoerd Meijer     // Iterate over all of the PHI nodes.
127893175a5cSSjoerd Meijer     BasicBlock::iterator BBI = ExitBB->begin();
127993175a5cSSjoerd Meijer     while ((PN = dyn_cast<PHINode>(BBI++))) {
128093175a5cSSjoerd Meijer       if (PN->use_empty())
128193175a5cSSjoerd Meijer         continue; // dead use, don't replace it
128293175a5cSSjoerd Meijer 
128393175a5cSSjoerd Meijer       if (!SE->isSCEVable(PN->getType()))
128493175a5cSSjoerd Meijer         continue;
128593175a5cSSjoerd Meijer 
128693175a5cSSjoerd Meijer       // Iterate over all of the values in all the PHI nodes.
128793175a5cSSjoerd Meijer       for (unsigned i = 0; i != NumPreds; ++i) {
128893175a5cSSjoerd Meijer         // If the value being merged in is not integer or is not defined
128993175a5cSSjoerd Meijer         // in the loop, skip it.
129093175a5cSSjoerd Meijer         Value *InVal = PN->getIncomingValue(i);
129193175a5cSSjoerd Meijer         if (!isa<Instruction>(InVal))
129293175a5cSSjoerd Meijer           continue;
129393175a5cSSjoerd Meijer 
129493175a5cSSjoerd Meijer         // If this pred is for a subloop, not L itself, skip it.
129593175a5cSSjoerd Meijer         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
129693175a5cSSjoerd Meijer           continue; // The Block is in a subloop, skip it.
129793175a5cSSjoerd Meijer 
129893175a5cSSjoerd Meijer         // Check that InVal is defined in the loop.
129993175a5cSSjoerd Meijer         Instruction *Inst = cast<Instruction>(InVal);
130093175a5cSSjoerd Meijer         if (!L->contains(Inst))
130193175a5cSSjoerd Meijer           continue;
130293175a5cSSjoerd Meijer 
130393175a5cSSjoerd Meijer         // Okay, this instruction has a user outside of the current loop
130493175a5cSSjoerd Meijer         // and varies predictably *inside* the loop.  Evaluate the value it
130593175a5cSSjoerd Meijer         // contains when the loop exits, if possible.  We prefer to start with
130693175a5cSSjoerd Meijer         // expressions which are true for all exits (so as to maximize
130793175a5cSSjoerd Meijer         // expression reuse by the SCEVExpander), but resort to per-exit
130893175a5cSSjoerd Meijer         // evaluation if that fails.
130993175a5cSSjoerd Meijer         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
131093175a5cSSjoerd Meijer         if (isa<SCEVCouldNotCompute>(ExitValue) ||
131193175a5cSSjoerd Meijer             !SE->isLoopInvariant(ExitValue, L) ||
131293175a5cSSjoerd Meijer             !isSafeToExpand(ExitValue, *SE)) {
131393175a5cSSjoerd Meijer           // TODO: This should probably be sunk into SCEV in some way; maybe a
131493175a5cSSjoerd Meijer           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
131593175a5cSSjoerd Meijer           // most SCEV expressions and other recurrence types (e.g. shift
131693175a5cSSjoerd Meijer           // recurrences).  Is there existing code we can reuse?
131793175a5cSSjoerd Meijer           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
131893175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitCount))
131993175a5cSSjoerd Meijer             continue;
132093175a5cSSjoerd Meijer           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
132193175a5cSSjoerd Meijer             if (AddRec->getLoop() == L)
132293175a5cSSjoerd Meijer               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
132393175a5cSSjoerd Meijer           if (isa<SCEVCouldNotCompute>(ExitValue) ||
132493175a5cSSjoerd Meijer               !SE->isLoopInvariant(ExitValue, L) ||
132593175a5cSSjoerd Meijer               !isSafeToExpand(ExitValue, *SE))
132693175a5cSSjoerd Meijer             continue;
132793175a5cSSjoerd Meijer         }
132893175a5cSSjoerd Meijer 
132993175a5cSSjoerd Meijer         // Computing the value outside of the loop brings no benefit if it is
133093175a5cSSjoerd Meijer         // definitely used inside the loop in a way which can not be optimized
13317d572ef2SRoman Lebedev         // away. Avoid doing so unless we know we have a value which computes
13327d572ef2SRoman Lebedev         // the ExitValue already. TODO: This should be merged into SCEV
13337d572ef2SRoman Lebedev         // expander to leverage its knowledge of existing expressions.
13347d572ef2SRoman Lebedev         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
13357d572ef2SRoman Lebedev             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
133693175a5cSSjoerd Meijer           continue;
133793175a5cSSjoerd Meijer 
1338b2df9612SRoman Lebedev         // Check if expansions of this SCEV would count as being high cost.
13397d572ef2SRoman Lebedev         bool HighCost = Rewriter.isHighCostExpansion(
13407d572ef2SRoman Lebedev             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1341b2df9612SRoman Lebedev 
1342b2df9612SRoman Lebedev         // Note that we must not perform expansions until after
1343b2df9612SRoman Lebedev         // we query *all* the costs, because if we perform temporary expansion
1344b2df9612SRoman Lebedev         // inbetween, one that we might not intend to keep, said expansion
1345b2df9612SRoman Lebedev         // *may* affect cost calculation of the the next SCEV's we'll query,
1346b2df9612SRoman Lebedev         // and next SCEV may errneously get smaller cost.
1347b2df9612SRoman Lebedev 
1348b2df9612SRoman Lebedev         // Collect all the candidate PHINodes to be rewritten.
1349b2df9612SRoman Lebedev         RewritePhiSet.emplace_back(PN, i, ExitValue, Inst, HighCost);
1350b2df9612SRoman Lebedev       }
1351b2df9612SRoman Lebedev     }
1352b2df9612SRoman Lebedev   }
1353b2df9612SRoman Lebedev 
1354795d142dSRoman Lebedev   // TODO: evaluate whether it is beneficial to change how we calculate
1355795d142dSRoman Lebedev   // high-cost: if we have SCEV 'A' which we know we will expand, should we
1356795d142dSRoman Lebedev   // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1357795d142dSRoman Lebedev   // potentially giving cost bonus to those other SCEV's?
135893175a5cSSjoerd Meijer 
135993175a5cSSjoerd Meijer   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
136093175a5cSSjoerd Meijer   int NumReplaced = 0;
136193175a5cSSjoerd Meijer 
136293175a5cSSjoerd Meijer   // Transformation.
136393175a5cSSjoerd Meijer   for (const RewritePhi &Phi : RewritePhiSet) {
136493175a5cSSjoerd Meijer     PHINode *PN = Phi.PN;
136593175a5cSSjoerd Meijer 
136693175a5cSSjoerd Meijer     // Only do the rewrite when the ExitValue can be expanded cheaply.
136793175a5cSSjoerd Meijer     // If LoopCanBeDel is true, rewrite exit value aggressively.
1368795d142dSRoman Lebedev     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost)
136993175a5cSSjoerd Meijer       continue;
1370795d142dSRoman Lebedev 
1371795d142dSRoman Lebedev     Value *ExitVal = Rewriter.expandCodeFor(
1372795d142dSRoman Lebedev         Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
1373795d142dSRoman Lebedev 
1374795d142dSRoman Lebedev     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
1375795d142dSRoman Lebedev                       << '\n'
1376795d142dSRoman Lebedev                       << "  LoopVal = " << *(Phi.ExpansionPoint) << "\n");
1377795d142dSRoman Lebedev 
1378795d142dSRoman Lebedev #ifndef NDEBUG
1379795d142dSRoman Lebedev     // If we reuse an instruction from a loop which is neither L nor one of
1380795d142dSRoman Lebedev     // its containing loops, we end up breaking LCSSA form for this loop by
1381795d142dSRoman Lebedev     // creating a new use of its instruction.
1382795d142dSRoman Lebedev     if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1383795d142dSRoman Lebedev       if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1384795d142dSRoman Lebedev         if (EVL != L)
1385795d142dSRoman Lebedev           assert(EVL->contains(L) && "LCSSA breach detected!");
1386795d142dSRoman Lebedev #endif
138793175a5cSSjoerd Meijer 
138893175a5cSSjoerd Meijer     NumReplaced++;
138993175a5cSSjoerd Meijer     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
139093175a5cSSjoerd Meijer     PN->setIncomingValue(Phi.Ith, ExitVal);
13918977bd58SFlorian Hahn     // It's necessary to tell ScalarEvolution about this explicitly so that
13928977bd58SFlorian Hahn     // it can walk the def-use list and forget all SCEVs, as it may not be
13938977bd58SFlorian Hahn     // watching the PHI itself. Once the new exit value is in place, there
13948977bd58SFlorian Hahn     // may not be a def-use connection between the loop and every instruction
13958977bd58SFlorian Hahn     // which got a SCEVAddRecExpr for that loop.
13968977bd58SFlorian Hahn     SE->forgetValue(PN);
139793175a5cSSjoerd Meijer 
139893175a5cSSjoerd Meijer     // If this instruction is dead now, delete it. Don't do it now to avoid
139993175a5cSSjoerd Meijer     // invalidating iterators.
140093175a5cSSjoerd Meijer     if (isInstructionTriviallyDead(Inst, TLI))
140193175a5cSSjoerd Meijer       DeadInsts.push_back(Inst);
140293175a5cSSjoerd Meijer 
140393175a5cSSjoerd Meijer     // Replace PN with ExitVal if that is legal and does not break LCSSA.
140493175a5cSSjoerd Meijer     if (PN->getNumIncomingValues() == 1 &&
140593175a5cSSjoerd Meijer         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
140693175a5cSSjoerd Meijer       PN->replaceAllUsesWith(ExitVal);
140793175a5cSSjoerd Meijer       PN->eraseFromParent();
140893175a5cSSjoerd Meijer     }
140993175a5cSSjoerd Meijer   }
141093175a5cSSjoerd Meijer 
141193175a5cSSjoerd Meijer   // The insertion point instruction may have been deleted; clear it out
141293175a5cSSjoerd Meijer   // so that the rewriter doesn't trip over it later.
141393175a5cSSjoerd Meijer   Rewriter.clearInsertPoint();
141493175a5cSSjoerd Meijer   return NumReplaced;
141593175a5cSSjoerd Meijer }
1416af7e1588SEvgeniy Brevnov 
1417af7e1588SEvgeniy Brevnov /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1418af7e1588SEvgeniy Brevnov /// \p OrigLoop.
1419af7e1588SEvgeniy Brevnov void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1420af7e1588SEvgeniy Brevnov                                         Loop *RemainderLoop, uint64_t UF) {
1421af7e1588SEvgeniy Brevnov   assert(UF > 0 && "Zero unrolled factor is not supported");
1422af7e1588SEvgeniy Brevnov   assert(UnrolledLoop != RemainderLoop &&
1423af7e1588SEvgeniy Brevnov          "Unrolled and Remainder loops are expected to distinct");
1424af7e1588SEvgeniy Brevnov 
1425af7e1588SEvgeniy Brevnov   // Get number of iterations in the original scalar loop.
1426af7e1588SEvgeniy Brevnov   unsigned OrigLoopInvocationWeight = 0;
1427af7e1588SEvgeniy Brevnov   Optional<unsigned> OrigAverageTripCount =
1428af7e1588SEvgeniy Brevnov       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1429af7e1588SEvgeniy Brevnov   if (!OrigAverageTripCount)
1430af7e1588SEvgeniy Brevnov     return;
1431af7e1588SEvgeniy Brevnov 
1432af7e1588SEvgeniy Brevnov   // Calculate number of iterations in unrolled loop.
1433af7e1588SEvgeniy Brevnov   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1434af7e1588SEvgeniy Brevnov   // Calculate number of iterations for remainder loop.
1435af7e1588SEvgeniy Brevnov   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1436af7e1588SEvgeniy Brevnov 
1437af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1438af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1439af7e1588SEvgeniy Brevnov   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1440af7e1588SEvgeniy Brevnov                             OrigLoopInvocationWeight);
1441af7e1588SEvgeniy Brevnov }
1442388de9dfSAlina Sbirlea 
1443388de9dfSAlina Sbirlea /// Utility that implements appending of loops onto a worklist.
1444388de9dfSAlina Sbirlea /// Loops are added in preorder (analogous for reverse postorder for trees),
1445388de9dfSAlina Sbirlea /// and the worklist is processed LIFO.
1446388de9dfSAlina Sbirlea template <typename RangeT>
1447388de9dfSAlina Sbirlea void llvm::appendReversedLoopsToWorklist(
1448388de9dfSAlina Sbirlea     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1449388de9dfSAlina Sbirlea   // We use an internal worklist to build up the preorder traversal without
1450388de9dfSAlina Sbirlea   // recursion.
1451388de9dfSAlina Sbirlea   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1452388de9dfSAlina Sbirlea 
1453388de9dfSAlina Sbirlea   // We walk the initial sequence of loops in reverse because we generally want
1454388de9dfSAlina Sbirlea   // to visit defs before uses and the worklist is LIFO.
1455388de9dfSAlina Sbirlea   for (Loop *RootL : Loops) {
1456388de9dfSAlina Sbirlea     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1457388de9dfSAlina Sbirlea     assert(PreOrderWorklist.empty() &&
1458388de9dfSAlina Sbirlea            "Must start with an empty preorder walk worklist.");
1459388de9dfSAlina Sbirlea     PreOrderWorklist.push_back(RootL);
1460388de9dfSAlina Sbirlea     do {
1461388de9dfSAlina Sbirlea       Loop *L = PreOrderWorklist.pop_back_val();
1462388de9dfSAlina Sbirlea       PreOrderWorklist.append(L->begin(), L->end());
1463388de9dfSAlina Sbirlea       PreOrderLoops.push_back(L);
1464388de9dfSAlina Sbirlea     } while (!PreOrderWorklist.empty());
1465388de9dfSAlina Sbirlea 
1466388de9dfSAlina Sbirlea     Worklist.insert(std::move(PreOrderLoops));
1467388de9dfSAlina Sbirlea     PreOrderLoops.clear();
1468388de9dfSAlina Sbirlea   }
1469388de9dfSAlina Sbirlea }
1470388de9dfSAlina Sbirlea 
1471388de9dfSAlina Sbirlea template <typename RangeT>
1472388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(RangeT &&Loops,
1473388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1474388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1475388de9dfSAlina Sbirlea }
1476388de9dfSAlina Sbirlea 
1477388de9dfSAlina Sbirlea template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1478388de9dfSAlina Sbirlea     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1479388de9dfSAlina Sbirlea 
148067904db2SAlina Sbirlea template void
148167904db2SAlina Sbirlea llvm::appendLoopsToWorklist<Loop &>(Loop &L,
148267904db2SAlina Sbirlea                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
148367904db2SAlina Sbirlea 
1484388de9dfSAlina Sbirlea void llvm::appendLoopsToWorklist(LoopInfo &LI,
1485388de9dfSAlina Sbirlea                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1486388de9dfSAlina Sbirlea   appendReversedLoopsToWorklist(LI, Worklist);
1487388de9dfSAlina Sbirlea }
14883dcaf296SArkady Shlykov 
14893dcaf296SArkady Shlykov Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
14903dcaf296SArkady Shlykov                       LoopInfo *LI, LPPassManager *LPM) {
14913dcaf296SArkady Shlykov   Loop &New = *LI->AllocateLoop();
14923dcaf296SArkady Shlykov   if (PL)
14933dcaf296SArkady Shlykov     PL->addChildLoop(&New);
14943dcaf296SArkady Shlykov   else
14953dcaf296SArkady Shlykov     LI->addTopLevelLoop(&New);
14963dcaf296SArkady Shlykov 
14973dcaf296SArkady Shlykov   if (LPM)
14983dcaf296SArkady Shlykov     LPM->addLoop(New);
14993dcaf296SArkady Shlykov 
15003dcaf296SArkady Shlykov   // Add all of the blocks in L to the new loop.
1501d1abf481SKazu Hirata   for (BasicBlock *BB : L->blocks())
1502d1abf481SKazu Hirata     if (LI->getLoopFor(BB) == L)
1503d1abf481SKazu Hirata       New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
15043dcaf296SArkady Shlykov 
15053dcaf296SArkady Shlykov   // Add all of the subloops to the new loop.
15063dcaf296SArkady Shlykov   for (Loop *I : *L)
15073dcaf296SArkady Shlykov     cloneLoop(I, &New, VM, LI, LPM);
15083dcaf296SArkady Shlykov 
15093dcaf296SArkady Shlykov   return &New;
15103dcaf296SArkady Shlykov }
15118528186bSFlorian Hahn 
15128528186bSFlorian Hahn /// IR Values for the lower and upper bounds of a pointer evolution.  We
15138528186bSFlorian Hahn /// need to use value-handles because SCEV expansion can invalidate previously
15148528186bSFlorian Hahn /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
15158528186bSFlorian Hahn /// a previous one.
15168528186bSFlorian Hahn struct PointerBounds {
15178528186bSFlorian Hahn   TrackingVH<Value> Start;
15188528186bSFlorian Hahn   TrackingVH<Value> End;
15198528186bSFlorian Hahn };
15208528186bSFlorian Hahn 
15218528186bSFlorian Hahn /// Expand code for the lower and upper bound of the pointer group \p CG
15228528186bSFlorian Hahn /// in \p TheLoop.  \return the values for the bounds.
15238528186bSFlorian Hahn static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
15248528186bSFlorian Hahn                                   Loop *TheLoop, Instruction *Loc,
152528410d17SFlorian Hahn                                   SCEVExpander &Exp) {
15268528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
15276d753b07SFlorian Hahn   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, CG->AddressSpace);
15288528186bSFlorian Hahn 
15298528186bSFlorian Hahn   Value *Start = nullptr, *End = nullptr;
15308528186bSFlorian Hahn   LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
15318528186bSFlorian Hahn   Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
15328528186bSFlorian Hahn   End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1533e908e063SMindong Chen   LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
15348528186bSFlorian Hahn   return {Start, End};
15358528186bSFlorian Hahn }
15368528186bSFlorian Hahn 
15378528186bSFlorian Hahn /// Turns a collection of checks into a collection of expanded upper and
15388528186bSFlorian Hahn /// lower bounds for both pointers in the check.
15398528186bSFlorian Hahn static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
15408528186bSFlorian Hahn expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
154128410d17SFlorian Hahn              Instruction *Loc, SCEVExpander &Exp) {
15428528186bSFlorian Hahn   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
15438528186bSFlorian Hahn 
15448528186bSFlorian Hahn   // Here we're relying on the SCEV Expander's cache to only emit code for the
15458528186bSFlorian Hahn   // same bounds once.
15468528186bSFlorian Hahn   transform(PointerChecks, std::back_inserter(ChecksWithBounds),
15478528186bSFlorian Hahn             [&](const RuntimePointerCheck &Check) {
154828410d17SFlorian Hahn               PointerBounds First = expandBounds(Check.first, L, Loc, Exp),
154928410d17SFlorian Hahn                             Second = expandBounds(Check.second, L, Loc, Exp);
15508528186bSFlorian Hahn               return std::make_pair(First, Second);
15518528186bSFlorian Hahn             });
15528528186bSFlorian Hahn 
15538528186bSFlorian Hahn   return ChecksWithBounds;
15548528186bSFlorian Hahn }
15558528186bSFlorian Hahn 
1556e844f053SFlorian Hahn Value *llvm::addRuntimeChecks(
15578528186bSFlorian Hahn     Instruction *Loc, Loop *TheLoop,
15588528186bSFlorian Hahn     const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
155928410d17SFlorian Hahn     SCEVExpander &Exp) {
15608528186bSFlorian Hahn   // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
15618528186bSFlorian Hahn   // TODO: Pass  RtPtrChecking instead of PointerChecks and SE separately, if possible
156228410d17SFlorian Hahn   auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, Exp);
15638528186bSFlorian Hahn 
15648528186bSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
1565e00158edSFlorian Hahn   IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
1566e00158edSFlorian Hahn                                            Loc->getModule()->getDataLayout());
1567e00158edSFlorian Hahn   ChkBuilder.SetInsertPoint(Loc);
15688528186bSFlorian Hahn   // Our instructions might fold to a constant.
15698528186bSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
15708528186bSFlorian Hahn 
15718528186bSFlorian Hahn   for (const auto &Check : ExpandedChecks) {
15728528186bSFlorian Hahn     const PointerBounds &A = Check.first, &B = Check.second;
15738528186bSFlorian Hahn     // Check if two pointers (A and B) conflict where conflict is computed as:
15748528186bSFlorian Hahn     // start(A) <= end(B) && start(B) <= end(A)
15758528186bSFlorian Hahn     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
15768528186bSFlorian Hahn     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
15778528186bSFlorian Hahn 
15788528186bSFlorian Hahn     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
15798528186bSFlorian Hahn            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
15808528186bSFlorian Hahn            "Trying to bounds check pointers with different address spaces");
15818528186bSFlorian Hahn 
15828528186bSFlorian Hahn     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
15838528186bSFlorian Hahn     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
15848528186bSFlorian Hahn 
15858528186bSFlorian Hahn     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
15868528186bSFlorian Hahn     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
15878528186bSFlorian Hahn     Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
15888528186bSFlorian Hahn     Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
15898528186bSFlorian Hahn 
15908528186bSFlorian Hahn     // [A|B].Start points to the first accessed byte under base [A|B].
15918528186bSFlorian Hahn     // [A|B].End points to the last accessed byte, plus one.
15928528186bSFlorian Hahn     // There is no conflict when the intervals are disjoint:
15938528186bSFlorian Hahn     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
15948528186bSFlorian Hahn     //
15958528186bSFlorian Hahn     // bound0 = (B.Start < A.End)
15968528186bSFlorian Hahn     // bound1 = (A.Start < B.End)
15978528186bSFlorian Hahn     //  IsConflict = bound0 & bound1
15988528186bSFlorian Hahn     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
15998528186bSFlorian Hahn     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
16008528186bSFlorian Hahn     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
16018528186bSFlorian Hahn     if (MemoryRuntimeCheck) {
16028528186bSFlorian Hahn       IsConflict =
16038528186bSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
16048528186bSFlorian Hahn     }
16058528186bSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
16068528186bSFlorian Hahn   }
16078528186bSFlorian Hahn 
1608e844f053SFlorian Hahn   return MemoryRuntimeCheck;
16098528186bSFlorian Hahn }
1610cfe87d4eSJingu Kang 
1611*b7315ffcSFlorian Hahn Value *llvm::addDiffRuntimeChecks(
1612*b7315ffcSFlorian Hahn     Instruction *Loc, Loop *TheLoop, ArrayRef<PointerDiffInfo> Checks,
1613*b7315ffcSFlorian Hahn     SCEVExpander &Expander,
1614*b7315ffcSFlorian Hahn     function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
1615*b7315ffcSFlorian Hahn 
1616*b7315ffcSFlorian Hahn   LLVMContext &Ctx = Loc->getContext();
1617*b7315ffcSFlorian Hahn   IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
1618*b7315ffcSFlorian Hahn                                            Loc->getModule()->getDataLayout());
1619*b7315ffcSFlorian Hahn   ChkBuilder.SetInsertPoint(Loc);
1620*b7315ffcSFlorian Hahn   // Our instructions might fold to a constant.
1621*b7315ffcSFlorian Hahn   Value *MemoryRuntimeCheck = nullptr;
1622*b7315ffcSFlorian Hahn 
1623*b7315ffcSFlorian Hahn   for (auto &C : Checks) {
1624*b7315ffcSFlorian Hahn     Type *Ty = C.SinkStart->getType();
1625*b7315ffcSFlorian Hahn     // Compute VF * IC * AccessSize.
1626*b7315ffcSFlorian Hahn     auto *VFTimesUFTimesSize =
1627*b7315ffcSFlorian Hahn         ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
1628*b7315ffcSFlorian Hahn                              ConstantInt::get(Ty, IC * C.AccessSize));
1629*b7315ffcSFlorian Hahn     Value *Sink = Expander.expandCodeFor(C.SinkStart, Ty, Loc);
1630*b7315ffcSFlorian Hahn     Value *Src = Expander.expandCodeFor(C.SrcStart, Ty, Loc);
1631*b7315ffcSFlorian Hahn     Value *Diff = ChkBuilder.CreateSub(Sink, Src);
1632*b7315ffcSFlorian Hahn     Value *IsConflict =
1633*b7315ffcSFlorian Hahn         ChkBuilder.CreateICmpULT(Diff, VFTimesUFTimesSize, "diff.check");
1634*b7315ffcSFlorian Hahn 
1635*b7315ffcSFlorian Hahn     if (MemoryRuntimeCheck) {
1636*b7315ffcSFlorian Hahn       IsConflict =
1637*b7315ffcSFlorian Hahn           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1638*b7315ffcSFlorian Hahn     }
1639*b7315ffcSFlorian Hahn     MemoryRuntimeCheck = IsConflict;
1640*b7315ffcSFlorian Hahn   }
1641*b7315ffcSFlorian Hahn 
1642*b7315ffcSFlorian Hahn   return MemoryRuntimeCheck;
1643*b7315ffcSFlorian Hahn }
1644*b7315ffcSFlorian Hahn 
1645e4abb641SJingu Kang Optional<IVConditionInfo> llvm::hasPartialIVCondition(Loop &L,
1646cfe87d4eSJingu Kang                                                       unsigned MSSAThreshold,
1647e4abb641SJingu Kang                                                       MemorySSA &MSSA,
1648e4abb641SJingu Kang                                                       AAResults &AA) {
1649e4abb641SJingu Kang   auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator());
1650cfe87d4eSJingu Kang   if (!TI || !TI->isConditional())
1651cfe87d4eSJingu Kang     return {};
1652cfe87d4eSJingu Kang 
1653cfe87d4eSJingu Kang   auto *CondI = dyn_cast<CmpInst>(TI->getCondition());
1654cfe87d4eSJingu Kang   // The case with the condition outside the loop should already be handled
1655cfe87d4eSJingu Kang   // earlier.
1656e4abb641SJingu Kang   if (!CondI || !L.contains(CondI))
1657cfe87d4eSJingu Kang     return {};
1658cfe87d4eSJingu Kang 
1659cfe87d4eSJingu Kang   SmallVector<Instruction *> InstToDuplicate;
1660cfe87d4eSJingu Kang   InstToDuplicate.push_back(CondI);
1661cfe87d4eSJingu Kang 
1662cfe87d4eSJingu Kang   SmallVector<Value *, 4> WorkList;
1663cfe87d4eSJingu Kang   WorkList.append(CondI->op_begin(), CondI->op_end());
1664cfe87d4eSJingu Kang 
1665cfe87d4eSJingu Kang   SmallVector<MemoryAccess *, 4> AccessesToCheck;
1666cfe87d4eSJingu Kang   SmallVector<MemoryLocation, 4> AccessedLocs;
1667cfe87d4eSJingu Kang   while (!WorkList.empty()) {
1668cfe87d4eSJingu Kang     Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
1669e4abb641SJingu Kang     if (!I || !L.contains(I))
1670cfe87d4eSJingu Kang       continue;
1671cfe87d4eSJingu Kang 
1672cfe87d4eSJingu Kang     // TODO: support additional instructions.
1673cfe87d4eSJingu Kang     if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
1674cfe87d4eSJingu Kang       return {};
1675cfe87d4eSJingu Kang 
1676cfe87d4eSJingu Kang     // Do not duplicate volatile and atomic loads.
1677cfe87d4eSJingu Kang     if (auto *LI = dyn_cast<LoadInst>(I))
1678cfe87d4eSJingu Kang       if (LI->isVolatile() || LI->isAtomic())
1679cfe87d4eSJingu Kang         return {};
1680cfe87d4eSJingu Kang 
1681cfe87d4eSJingu Kang     InstToDuplicate.push_back(I);
1682e4abb641SJingu Kang     if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
1683cfe87d4eSJingu Kang       if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
1684cfe87d4eSJingu Kang         // Queue the defining access to check for alias checks.
1685cfe87d4eSJingu Kang         AccessesToCheck.push_back(MemUse->getDefiningAccess());
1686cfe87d4eSJingu Kang         AccessedLocs.push_back(MemoryLocation::get(I));
1687cfe87d4eSJingu Kang       } else {
1688cfe87d4eSJingu Kang         // MemoryDefs may clobber the location or may be atomic memory
1689cfe87d4eSJingu Kang         // operations. Bail out.
1690cfe87d4eSJingu Kang         return {};
1691cfe87d4eSJingu Kang       }
1692cfe87d4eSJingu Kang     }
1693cfe87d4eSJingu Kang     WorkList.append(I->op_begin(), I->op_end());
1694cfe87d4eSJingu Kang   }
1695cfe87d4eSJingu Kang 
1696cfe87d4eSJingu Kang   if (InstToDuplicate.empty())
1697cfe87d4eSJingu Kang     return {};
1698cfe87d4eSJingu Kang 
1699cfe87d4eSJingu Kang   SmallVector<BasicBlock *, 4> ExitingBlocks;
1700e4abb641SJingu Kang   L.getExitingBlocks(ExitingBlocks);
1701cfe87d4eSJingu Kang   auto HasNoClobbersOnPath =
1702e4abb641SJingu Kang       [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
1703cfe87d4eSJingu Kang        MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
1704cfe87d4eSJingu Kang                       SmallVector<MemoryAccess *, 4> AccessesToCheck)
1705cfe87d4eSJingu Kang       -> Optional<IVConditionInfo> {
1706cfe87d4eSJingu Kang     IVConditionInfo Info;
1707cfe87d4eSJingu Kang     // First, collect all blocks in the loop that are on a patch from Succ
1708cfe87d4eSJingu Kang     // to the header.
1709cfe87d4eSJingu Kang     SmallVector<BasicBlock *, 4> WorkList;
1710cfe87d4eSJingu Kang     WorkList.push_back(Succ);
1711cfe87d4eSJingu Kang     WorkList.push_back(Header);
1712cfe87d4eSJingu Kang     SmallPtrSet<BasicBlock *, 4> Seen;
1713cfe87d4eSJingu Kang     Seen.insert(Header);
1714cfe87d4eSJingu Kang     Info.PathIsNoop &=
1715cfe87d4eSJingu Kang         all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
1716cfe87d4eSJingu Kang 
1717cfe87d4eSJingu Kang     while (!WorkList.empty()) {
1718cfe87d4eSJingu Kang       BasicBlock *Current = WorkList.pop_back_val();
1719e4abb641SJingu Kang       if (!L.contains(Current))
1720cfe87d4eSJingu Kang         continue;
1721cfe87d4eSJingu Kang       const auto &SeenIns = Seen.insert(Current);
1722cfe87d4eSJingu Kang       if (!SeenIns.second)
1723cfe87d4eSJingu Kang         continue;
1724cfe87d4eSJingu Kang 
1725cfe87d4eSJingu Kang       Info.PathIsNoop &= all_of(
1726cfe87d4eSJingu Kang           *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
1727cfe87d4eSJingu Kang       WorkList.append(succ_begin(Current), succ_end(Current));
1728cfe87d4eSJingu Kang     }
1729cfe87d4eSJingu Kang 
1730cfe87d4eSJingu Kang     // Require at least 2 blocks on a path through the loop. This skips
1731cfe87d4eSJingu Kang     // paths that directly exit the loop.
1732cfe87d4eSJingu Kang     if (Seen.size() < 2)
1733cfe87d4eSJingu Kang       return {};
1734cfe87d4eSJingu Kang 
1735cfe87d4eSJingu Kang     // Next, check if there are any MemoryDefs that are on the path through
1736cfe87d4eSJingu Kang     // the loop (in the Seen set) and they may-alias any of the locations in
1737cfe87d4eSJingu Kang     // AccessedLocs. If that is the case, they may modify the condition and
1738cfe87d4eSJingu Kang     // partial unswitching is not possible.
1739cfe87d4eSJingu Kang     SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
1740cfe87d4eSJingu Kang     while (!AccessesToCheck.empty()) {
1741cfe87d4eSJingu Kang       MemoryAccess *Current = AccessesToCheck.pop_back_val();
1742cfe87d4eSJingu Kang       auto SeenI = SeenAccesses.insert(Current);
1743cfe87d4eSJingu Kang       if (!SeenI.second || !Seen.contains(Current->getBlock()))
1744cfe87d4eSJingu Kang         continue;
1745cfe87d4eSJingu Kang 
1746cfe87d4eSJingu Kang       // Bail out if exceeded the threshold.
1747cfe87d4eSJingu Kang       if (SeenAccesses.size() >= MSSAThreshold)
1748cfe87d4eSJingu Kang         return {};
1749cfe87d4eSJingu Kang 
1750cfe87d4eSJingu Kang       // MemoryUse are read-only accesses.
1751cfe87d4eSJingu Kang       if (isa<MemoryUse>(Current))
1752cfe87d4eSJingu Kang         continue;
1753cfe87d4eSJingu Kang 
1754cfe87d4eSJingu Kang       // For a MemoryDef, check if is aliases any of the location feeding
1755cfe87d4eSJingu Kang       // the original condition.
1756cfe87d4eSJingu Kang       if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
1757e4abb641SJingu Kang         if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
1758cfe87d4eSJingu Kang               return isModSet(
1759e4abb641SJingu Kang                   AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
1760cfe87d4eSJingu Kang             }))
1761cfe87d4eSJingu Kang           return {};
1762cfe87d4eSJingu Kang       }
1763cfe87d4eSJingu Kang 
1764cfe87d4eSJingu Kang       for (Use &U : Current->uses())
1765cfe87d4eSJingu Kang         AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
1766cfe87d4eSJingu Kang     }
1767cfe87d4eSJingu Kang 
1768cfe87d4eSJingu Kang     // We could also allow loops with known trip counts without mustprogress,
1769cfe87d4eSJingu Kang     // but ScalarEvolution may not be available.
17707629b2a0SPhilip Reames     Info.PathIsNoop &= isMustProgress(&L);
1771cfe87d4eSJingu Kang 
1772cfe87d4eSJingu Kang     // If the path is considered a no-op so far, check if it reaches a
1773cfe87d4eSJingu Kang     // single exit block without any phis. This ensures no values from the
1774cfe87d4eSJingu Kang     // loop are used outside of the loop.
1775cfe87d4eSJingu Kang     if (Info.PathIsNoop) {
1776cfe87d4eSJingu Kang       for (auto *Exiting : ExitingBlocks) {
1777cfe87d4eSJingu Kang         if (!Seen.contains(Exiting))
1778cfe87d4eSJingu Kang           continue;
1779cfe87d4eSJingu Kang         for (auto *Succ : successors(Exiting)) {
1780e4abb641SJingu Kang           if (L.contains(Succ))
1781cfe87d4eSJingu Kang             continue;
1782cfe87d4eSJingu Kang 
1783cfe87d4eSJingu Kang           Info.PathIsNoop &= llvm::empty(Succ->phis()) &&
1784cfe87d4eSJingu Kang                              (!Info.ExitForPath || Info.ExitForPath == Succ);
1785cfe87d4eSJingu Kang           if (!Info.PathIsNoop)
1786cfe87d4eSJingu Kang             break;
1787cfe87d4eSJingu Kang           assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
1788cfe87d4eSJingu Kang                  "cannot have multiple exit blocks");
1789cfe87d4eSJingu Kang           Info.ExitForPath = Succ;
1790cfe87d4eSJingu Kang         }
1791cfe87d4eSJingu Kang       }
1792cfe87d4eSJingu Kang     }
1793cfe87d4eSJingu Kang     if (!Info.ExitForPath)
1794cfe87d4eSJingu Kang       Info.PathIsNoop = false;
1795cfe87d4eSJingu Kang 
1796cfe87d4eSJingu Kang     Info.InstToDuplicate = InstToDuplicate;
1797cfe87d4eSJingu Kang     return Info;
1798cfe87d4eSJingu Kang   };
1799cfe87d4eSJingu Kang 
1800cfe87d4eSJingu Kang   // If we branch to the same successor, partial unswitching will not be
1801cfe87d4eSJingu Kang   // beneficial.
1802cfe87d4eSJingu Kang   if (TI->getSuccessor(0) == TI->getSuccessor(1))
1803cfe87d4eSJingu Kang     return {};
1804cfe87d4eSJingu Kang 
1805e4abb641SJingu Kang   if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
1806cfe87d4eSJingu Kang                                       AccessesToCheck)) {
1807cfe87d4eSJingu Kang     Info->KnownValue = ConstantInt::getTrue(TI->getContext());
1808cfe87d4eSJingu Kang     return Info;
1809cfe87d4eSJingu Kang   }
1810e4abb641SJingu Kang   if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
1811cfe87d4eSJingu Kang                                       AccessesToCheck)) {
1812cfe87d4eSJingu Kang     Info->KnownValue = ConstantInt::getFalse(TI->getContext());
1813cfe87d4eSJingu Kang     return Info;
1814cfe87d4eSJingu Kang   }
1815cfe87d4eSJingu Kang 
1816cfe87d4eSJingu Kang   return {};
1817cfe87d4eSJingu Kang }
1818