1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines common loop utility functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Utils/LoopUtils.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/PriorityWorklist.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/DomTreeUpdater.h"
24 #include "llvm/Analysis/GlobalsModRef.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/LoopAccessAnalysis.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/MemorySSA.h"
30 #include "llvm/Analysis/MemorySSAUpdater.h"
31 #include "llvm/Analysis/MustExecute.h"
32 #include "llvm/Analysis/ScalarEvolution.h"
33 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
34 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/DIBuilder.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Operator.h"
44 #include "llvm/IR/PatternMatch.h"
45 #include "llvm/IR/ValueHandle.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/KnownBits.h"
50 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51 #include "llvm/Transforms/Utils/Local.h"
52 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
53 
54 using namespace llvm;
55 using namespace llvm::PatternMatch;
56 
57 #define DEBUG_TYPE "loop-utils"
58 
59 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
60 static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
61 
62 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
63                                    MemorySSAUpdater *MSSAU,
64                                    bool PreserveLCSSA) {
65   bool Changed = false;
66 
67   // We re-use a vector for the in-loop predecesosrs.
68   SmallVector<BasicBlock *, 4> InLoopPredecessors;
69 
70   auto RewriteExit = [&](BasicBlock *BB) {
71     assert(InLoopPredecessors.empty() &&
72            "Must start with an empty predecessors list!");
73     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
74 
75     // See if there are any non-loop predecessors of this exit block and
76     // keep track of the in-loop predecessors.
77     bool IsDedicatedExit = true;
78     for (auto *PredBB : predecessors(BB))
79       if (L->contains(PredBB)) {
80         if (isa<IndirectBrInst>(PredBB->getTerminator()))
81           // We cannot rewrite exiting edges from an indirectbr.
82           return false;
83         if (isa<CallBrInst>(PredBB->getTerminator()))
84           // We cannot rewrite exiting edges from a callbr.
85           return false;
86 
87         InLoopPredecessors.push_back(PredBB);
88       } else {
89         IsDedicatedExit = false;
90       }
91 
92     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
93 
94     // Nothing to do if this is already a dedicated exit.
95     if (IsDedicatedExit)
96       return false;
97 
98     auto *NewExitBB = SplitBlockPredecessors(
99         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
100 
101     if (!NewExitBB)
102       LLVM_DEBUG(
103           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
104                  << *L << "\n");
105     else
106       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
107                         << NewExitBB->getName() << "\n");
108     return true;
109   };
110 
111   // Walk the exit blocks directly rather than building up a data structure for
112   // them, but only visit each one once.
113   SmallPtrSet<BasicBlock *, 4> Visited;
114   for (auto *BB : L->blocks())
115     for (auto *SuccBB : successors(BB)) {
116       // We're looking for exit blocks so skip in-loop successors.
117       if (L->contains(SuccBB))
118         continue;
119 
120       // Visit each exit block exactly once.
121       if (!Visited.insert(SuccBB).second)
122         continue;
123 
124       Changed |= RewriteExit(SuccBB);
125     }
126 
127   return Changed;
128 }
129 
130 /// Returns the instructions that use values defined in the loop.
131 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
132   SmallVector<Instruction *, 8> UsedOutside;
133 
134   for (auto *Block : L->getBlocks())
135     // FIXME: I believe that this could use copy_if if the Inst reference could
136     // be adapted into a pointer.
137     for (auto &Inst : *Block) {
138       auto Users = Inst.users();
139       if (any_of(Users, [&](User *U) {
140             auto *Use = cast<Instruction>(U);
141             return !L->contains(Use->getParent());
142           }))
143         UsedOutside.push_back(&Inst);
144     }
145 
146   return UsedOutside;
147 }
148 
149 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
150   // By definition, all loop passes need the LoopInfo analysis and the
151   // Dominator tree it depends on. Because they all participate in the loop
152   // pass manager, they must also preserve these.
153   AU.addRequired<DominatorTreeWrapperPass>();
154   AU.addPreserved<DominatorTreeWrapperPass>();
155   AU.addRequired<LoopInfoWrapperPass>();
156   AU.addPreserved<LoopInfoWrapperPass>();
157 
158   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
159   // here because users shouldn't directly get them from this header.
160   extern char &LoopSimplifyID;
161   extern char &LCSSAID;
162   AU.addRequiredID(LoopSimplifyID);
163   AU.addPreservedID(LoopSimplifyID);
164   AU.addRequiredID(LCSSAID);
165   AU.addPreservedID(LCSSAID);
166   // This is used in the LPPassManager to perform LCSSA verification on passes
167   // which preserve lcssa form
168   AU.addRequired<LCSSAVerificationPass>();
169   AU.addPreserved<LCSSAVerificationPass>();
170 
171   // Loop passes are designed to run inside of a loop pass manager which means
172   // that any function analyses they require must be required by the first loop
173   // pass in the manager (so that it is computed before the loop pass manager
174   // runs) and preserved by all loop pasess in the manager. To make this
175   // reasonably robust, the set needed for most loop passes is maintained here.
176   // If your loop pass requires an analysis not listed here, you will need to
177   // carefully audit the loop pass manager nesting structure that results.
178   AU.addRequired<AAResultsWrapperPass>();
179   AU.addPreserved<AAResultsWrapperPass>();
180   AU.addPreserved<BasicAAWrapperPass>();
181   AU.addPreserved<GlobalsAAWrapperPass>();
182   AU.addPreserved<SCEVAAWrapperPass>();
183   AU.addRequired<ScalarEvolutionWrapperPass>();
184   AU.addPreserved<ScalarEvolutionWrapperPass>();
185   // FIXME: When all loop passes preserve MemorySSA, it can be required and
186   // preserved here instead of the individual handling in each pass.
187 }
188 
189 /// Manually defined generic "LoopPass" dependency initialization. This is used
190 /// to initialize the exact set of passes from above in \c
191 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
192 /// with:
193 ///
194 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
195 ///
196 /// As-if "LoopPass" were a pass.
197 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
198   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
199   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
200   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
201   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
202   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
203   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
204   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
205   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
206   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
207   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
208 }
209 
210 /// Create MDNode for input string.
211 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
212   LLVMContext &Context = TheLoop->getHeader()->getContext();
213   Metadata *MDs[] = {
214       MDString::get(Context, Name),
215       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
216   return MDNode::get(Context, MDs);
217 }
218 
219 /// Set input string into loop metadata by keeping other values intact.
220 /// If the string is already in loop metadata update value if it is
221 /// different.
222 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
223                                    unsigned V) {
224   SmallVector<Metadata *, 4> MDs(1);
225   // If the loop already has metadata, retain it.
226   MDNode *LoopID = TheLoop->getLoopID();
227   if (LoopID) {
228     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
229       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
230       // If it is of form key = value, try to parse it.
231       if (Node->getNumOperands() == 2) {
232         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
233         if (S && S->getString().equals(StringMD)) {
234           ConstantInt *IntMD =
235               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
236           if (IntMD && IntMD->getSExtValue() == V)
237             // It is already in place. Do nothing.
238             return;
239           // We need to update the value, so just skip it here and it will
240           // be added after copying other existed nodes.
241           continue;
242         }
243       }
244       MDs.push_back(Node);
245     }
246   }
247   // Add new metadata.
248   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
249   // Replace current metadata node with new one.
250   LLVMContext &Context = TheLoop->getHeader()->getContext();
251   MDNode *NewLoopID = MDNode::get(Context, MDs);
252   // Set operand 0 to refer to the loop id itself.
253   NewLoopID->replaceOperandWith(0, NewLoopID);
254   TheLoop->setLoopID(NewLoopID);
255 }
256 
257 Optional<ElementCount>
258 llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
259   Optional<int> Width =
260       getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
261 
262   if (Width.hasValue()) {
263     Optional<int> IsScalable = getOptionalIntLoopAttribute(
264         TheLoop, "llvm.loop.vectorize.scalable.enable");
265     return ElementCount::get(*Width, IsScalable.getValueOr(false));
266   }
267 
268   return None;
269 }
270 
271 Optional<MDNode *> llvm::makeFollowupLoopID(
272     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
273     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
274   if (!OrigLoopID) {
275     if (AlwaysNew)
276       return nullptr;
277     return None;
278   }
279 
280   assert(OrigLoopID->getOperand(0) == OrigLoopID);
281 
282   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
283   bool InheritSomeAttrs =
284       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
285   SmallVector<Metadata *, 8> MDs;
286   MDs.push_back(nullptr);
287 
288   bool Changed = false;
289   if (InheritAllAttrs || InheritSomeAttrs) {
290     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
291       MDNode *Op = cast<MDNode>(Existing.get());
292 
293       auto InheritThisAttribute = [InheritSomeAttrs,
294                                    InheritOptionsExceptPrefix](MDNode *Op) {
295         if (!InheritSomeAttrs)
296           return false;
297 
298         // Skip malformatted attribute metadata nodes.
299         if (Op->getNumOperands() == 0)
300           return true;
301         Metadata *NameMD = Op->getOperand(0).get();
302         if (!isa<MDString>(NameMD))
303           return true;
304         StringRef AttrName = cast<MDString>(NameMD)->getString();
305 
306         // Do not inherit excluded attributes.
307         return !AttrName.startswith(InheritOptionsExceptPrefix);
308       };
309 
310       if (InheritThisAttribute(Op))
311         MDs.push_back(Op);
312       else
313         Changed = true;
314     }
315   } else {
316     // Modified if we dropped at least one attribute.
317     Changed = OrigLoopID->getNumOperands() > 1;
318   }
319 
320   bool HasAnyFollowup = false;
321   for (StringRef OptionName : FollowupOptions) {
322     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
323     if (!FollowupNode)
324       continue;
325 
326     HasAnyFollowup = true;
327     for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
328       MDs.push_back(Option.get());
329       Changed = true;
330     }
331   }
332 
333   // Attributes of the followup loop not specified explicity, so signal to the
334   // transformation pass to add suitable attributes.
335   if (!AlwaysNew && !HasAnyFollowup)
336     return None;
337 
338   // If no attributes were added or remove, the previous loop Id can be reused.
339   if (!AlwaysNew && !Changed)
340     return OrigLoopID;
341 
342   // No attributes is equivalent to having no !llvm.loop metadata at all.
343   if (MDs.size() == 1)
344     return nullptr;
345 
346   // Build the new loop ID.
347   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
348   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
349   return FollowupLoopID;
350 }
351 
352 bool llvm::hasDisableAllTransformsHint(const Loop *L) {
353   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
354 }
355 
356 bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
357   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
358 }
359 
360 TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
361   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
362     return TM_SuppressedByUser;
363 
364   Optional<int> Count =
365       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
366   if (Count.hasValue())
367     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
368 
369   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
370     return TM_ForcedByUser;
371 
372   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
373     return TM_ForcedByUser;
374 
375   if (hasDisableAllTransformsHint(L))
376     return TM_Disable;
377 
378   return TM_Unspecified;
379 }
380 
381 TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
382   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
383     return TM_SuppressedByUser;
384 
385   Optional<int> Count =
386       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
387   if (Count.hasValue())
388     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
389 
390   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
391     return TM_ForcedByUser;
392 
393   if (hasDisableAllTransformsHint(L))
394     return TM_Disable;
395 
396   return TM_Unspecified;
397 }
398 
399 TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
400   Optional<bool> Enable =
401       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
402 
403   if (Enable == false)
404     return TM_SuppressedByUser;
405 
406   Optional<ElementCount> VectorizeWidth =
407       getOptionalElementCountLoopAttribute(L);
408   Optional<int> InterleaveCount =
409       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
410 
411   // 'Forcing' vector width and interleave count to one effectively disables
412   // this tranformation.
413   if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
414       InterleaveCount == 1)
415     return TM_SuppressedByUser;
416 
417   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
418     return TM_Disable;
419 
420   if (Enable == true)
421     return TM_ForcedByUser;
422 
423   if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
424     return TM_Disable;
425 
426   if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
427     return TM_Enable;
428 
429   if (hasDisableAllTransformsHint(L))
430     return TM_Disable;
431 
432   return TM_Unspecified;
433 }
434 
435 TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
436   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
437     return TM_ForcedByUser;
438 
439   if (hasDisableAllTransformsHint(L))
440     return TM_Disable;
441 
442   return TM_Unspecified;
443 }
444 
445 TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
446   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
447     return TM_SuppressedByUser;
448 
449   if (hasDisableAllTransformsHint(L))
450     return TM_Disable;
451 
452   return TM_Unspecified;
453 }
454 
455 /// Does a BFS from a given node to all of its children inside a given loop.
456 /// The returned vector of nodes includes the starting point.
457 SmallVector<DomTreeNode *, 16>
458 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
459   SmallVector<DomTreeNode *, 16> Worklist;
460   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
461     // Only include subregions in the top level loop.
462     BasicBlock *BB = DTN->getBlock();
463     if (CurLoop->contains(BB))
464       Worklist.push_back(DTN);
465   };
466 
467   AddRegionToWorklist(N);
468 
469   for (size_t I = 0; I < Worklist.size(); I++) {
470     for (DomTreeNode *Child : Worklist[I]->children())
471       AddRegionToWorklist(Child);
472   }
473 
474   return Worklist;
475 }
476 
477 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
478                           LoopInfo *LI, MemorySSA *MSSA) {
479   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
480   auto *Preheader = L->getLoopPreheader();
481   assert(Preheader && "Preheader should exist!");
482 
483   std::unique_ptr<MemorySSAUpdater> MSSAU;
484   if (MSSA)
485     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
486 
487   // Now that we know the removal is safe, remove the loop by changing the
488   // branch from the preheader to go to the single exit block.
489   //
490   // Because we're deleting a large chunk of code at once, the sequence in which
491   // we remove things is very important to avoid invalidation issues.
492 
493   // Tell ScalarEvolution that the loop is deleted. Do this before
494   // deleting the loop so that ScalarEvolution can look at the loop
495   // to determine what it needs to clean up.
496   if (SE)
497     SE->forgetLoop(L);
498 
499   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
500   assert(OldBr && "Preheader must end with a branch");
501   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
502   // Connect the preheader to the exit block. Keep the old edge to the header
503   // around to perform the dominator tree update in two separate steps
504   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
505   // preheader -> header.
506   //
507   //
508   // 0.  Preheader          1.  Preheader           2.  Preheader
509   //        |                    |   |                   |
510   //        V                    |   V                   |
511   //      Header <--\            | Header <--\           | Header <--\
512   //       |  |     |            |  |  |     |           |  |  |     |
513   //       |  V     |            |  |  V     |           |  |  V     |
514   //       | Body --/            |  | Body --/           |  | Body --/
515   //       V                     V  V                    V  V
516   //      Exit                   Exit                    Exit
517   //
518   // By doing this is two separate steps we can perform the dominator tree
519   // update without using the batch update API.
520   //
521   // Even when the loop is never executed, we cannot remove the edge from the
522   // source block to the exit block. Consider the case where the unexecuted loop
523   // branches back to an outer loop. If we deleted the loop and removed the edge
524   // coming to this inner loop, this will break the outer loop structure (by
525   // deleting the backedge of the outer loop). If the outer loop is indeed a
526   // non-loop, it will be deleted in a future iteration of loop deletion pass.
527   IRBuilder<> Builder(OldBr);
528 
529   auto *ExitBlock = L->getUniqueExitBlock();
530   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
531   if (ExitBlock) {
532     assert(ExitBlock && "Should have a unique exit block!");
533     assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
534 
535     Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
536     // Remove the old branch. The conditional branch becomes a new terminator.
537     OldBr->eraseFromParent();
538 
539     // Rewrite phis in the exit block to get their inputs from the Preheader
540     // instead of the exiting block.
541     for (PHINode &P : ExitBlock->phis()) {
542       // Set the zero'th element of Phi to be from the preheader and remove all
543       // other incoming values. Given the loop has dedicated exits, all other
544       // incoming values must be from the exiting blocks.
545       int PredIndex = 0;
546       P.setIncomingBlock(PredIndex, Preheader);
547       // Removes all incoming values from all other exiting blocks (including
548       // duplicate values from an exiting block).
549       // Nuke all entries except the zero'th entry which is the preheader entry.
550       // NOTE! We need to remove Incoming Values in the reverse order as done
551       // below, to keep the indices valid for deletion (removeIncomingValues
552       // updates getNumIncomingValues and shifts all values down into the
553       // operand being deleted).
554       for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
555         P.removeIncomingValue(e - i, false);
556 
557       assert((P.getNumIncomingValues() == 1 &&
558               P.getIncomingBlock(PredIndex) == Preheader) &&
559              "Should have exactly one value and that's from the preheader!");
560     }
561 
562     if (DT) {
563       DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
564       if (MSSA) {
565         MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
566                             *DT);
567         if (VerifyMemorySSA)
568           MSSA->verifyMemorySSA();
569       }
570     }
571 
572     // Disconnect the loop body by branching directly to its exit.
573     Builder.SetInsertPoint(Preheader->getTerminator());
574     Builder.CreateBr(ExitBlock);
575     // Remove the old branch.
576     Preheader->getTerminator()->eraseFromParent();
577   } else {
578     assert(L->hasNoExitBlocks() &&
579            "Loop should have either zero or one exit blocks.");
580 
581     Builder.SetInsertPoint(OldBr);
582     Builder.CreateUnreachable();
583     Preheader->getTerminator()->eraseFromParent();
584   }
585 
586   if (DT) {
587     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
588     if (MSSA) {
589       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
590                           *DT);
591       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
592                                                    L->block_end());
593       MSSAU->removeBlocks(DeadBlockSet);
594       if (VerifyMemorySSA)
595         MSSA->verifyMemorySSA();
596     }
597   }
598 
599   // Use a map to unique and a vector to guarantee deterministic ordering.
600   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
601   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
602 
603   if (ExitBlock) {
604     // Given LCSSA form is satisfied, we should not have users of instructions
605     // within the dead loop outside of the loop. However, LCSSA doesn't take
606     // unreachable uses into account. We handle them here.
607     // We could do it after drop all references (in this case all users in the
608     // loop will be already eliminated and we have less work to do but according
609     // to API doc of User::dropAllReferences only valid operation after dropping
610     // references, is deletion. So let's substitute all usages of
611     // instruction from the loop with undef value of corresponding type first.
612     for (auto *Block : L->blocks())
613       for (Instruction &I : *Block) {
614         auto *Undef = UndefValue::get(I.getType());
615         for (Use &U : llvm::make_early_inc_range(I.uses())) {
616           if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
617             if (L->contains(Usr->getParent()))
618               continue;
619           // If we have a DT then we can check that uses outside a loop only in
620           // unreachable block.
621           if (DT)
622             assert(!DT->isReachableFromEntry(U) &&
623                    "Unexpected user in reachable block");
624           U.set(Undef);
625         }
626         auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
627         if (!DVI)
628           continue;
629         auto Key =
630             DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
631         if (Key != DeadDebugSet.end())
632           continue;
633         DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
634         DeadDebugInst.push_back(DVI);
635       }
636 
637     // After the loop has been deleted all the values defined and modified
638     // inside the loop are going to be unavailable.
639     // Since debug values in the loop have been deleted, inserting an undef
640     // dbg.value truncates the range of any dbg.value before the loop where the
641     // loop used to be. This is particularly important for constant values.
642     DIBuilder DIB(*ExitBlock->getModule());
643     Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
644     assert(InsertDbgValueBefore &&
645            "There should be a non-PHI instruction in exit block, else these "
646            "instructions will have no parent.");
647     for (auto *DVI : DeadDebugInst)
648       DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
649                                   DVI->getVariable(), DVI->getExpression(),
650                                   DVI->getDebugLoc(), InsertDbgValueBefore);
651   }
652 
653   // Remove the block from the reference counting scheme, so that we can
654   // delete it freely later.
655   for (auto *Block : L->blocks())
656     Block->dropAllReferences();
657 
658   if (MSSA && VerifyMemorySSA)
659     MSSA->verifyMemorySSA();
660 
661   if (LI) {
662     // Erase the instructions and the blocks without having to worry
663     // about ordering because we already dropped the references.
664     // NOTE: This iteration is safe because erasing the block does not remove
665     // its entry from the loop's block list.  We do that in the next section.
666     for (BasicBlock *BB : L->blocks())
667       BB->eraseFromParent();
668 
669     // Finally, the blocks from loopinfo.  This has to happen late because
670     // otherwise our loop iterators won't work.
671 
672     SmallPtrSet<BasicBlock *, 8> blocks;
673     blocks.insert(L->block_begin(), L->block_end());
674     for (BasicBlock *BB : blocks)
675       LI->removeBlock(BB);
676 
677     // The last step is to update LoopInfo now that we've eliminated this loop.
678     // Note: LoopInfo::erase remove the given loop and relink its subloops with
679     // its parent. While removeLoop/removeChildLoop remove the given loop but
680     // not relink its subloops, which is what we want.
681     if (Loop *ParentLoop = L->getParentLoop()) {
682       Loop::iterator I = find(*ParentLoop, L);
683       assert(I != ParentLoop->end() && "Couldn't find loop");
684       ParentLoop->removeChildLoop(I);
685     } else {
686       Loop::iterator I = find(*LI, L);
687       assert(I != LI->end() && "Couldn't find loop");
688       LI->removeLoop(I);
689     }
690     LI->destroy(L);
691   }
692 }
693 
694 static Loop *getOutermostLoop(Loop *L) {
695   while (Loop *Parent = L->getParentLoop())
696     L = Parent;
697   return L;
698 }
699 
700 void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
701                              LoopInfo &LI, MemorySSA *MSSA) {
702   auto *Latch = L->getLoopLatch();
703   assert(Latch && "multiple latches not yet supported");
704   auto *Header = L->getHeader();
705   Loop *OutermostLoop = getOutermostLoop(L);
706 
707   SE.forgetLoop(L);
708 
709   std::unique_ptr<MemorySSAUpdater> MSSAU;
710   if (MSSA)
711     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
712 
713   // Update the CFG and domtree.  We chose to special case a couple of
714   // of common cases for code quality and test readability reasons.
715   [&]() -> void {
716     if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) {
717       if (!BI->isConditional()) {
718         DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
719         (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU,
720                                   MSSAU.get());
721         return;
722       }
723 
724       // Conditional latch/exit - note that latch can be shared by inner
725       // and outer loop so the other target doesn't need to an exit
726       if (L->isLoopExiting(Latch)) {
727         // TODO: Generalize ConstantFoldTerminator so that it can be used
728         // here without invalidating LCSSA or MemorySSA.  (Tricky case for
729         // LCSSA: header is an exit block of a preceeding sibling loop w/o
730         // dedicated exits.)
731         const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
732         BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
733 
734         DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
735         Header->removePredecessor(Latch, true);
736 
737         IRBuilder<> Builder(BI);
738         auto *NewBI = Builder.CreateBr(ExitBB);
739         // Transfer the metadata to the new branch instruction (minus the
740         // loop info since this is no longer a loop)
741         NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
742                                   LLVMContext::MD_annotation});
743 
744         BI->eraseFromParent();
745         DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
746         if (MSSA)
747           MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
748         return;
749       }
750     }
751 
752     // General case.  By splitting the backedge, and then explicitly making it
753     // unreachable we gracefully handle corner cases such as switch and invoke
754     // termiantors.
755     auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
756 
757     DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
758     (void)changeToUnreachable(BackedgeBB->getTerminator(),
759                               /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
760   }();
761 
762   // Erase (and destroy) this loop instance.  Handles relinking sub-loops
763   // and blocks within the loop as needed.
764   LI.erase(L);
765 
766   // If the loop we broke had a parent, then changeToUnreachable might have
767   // caused a block to be removed from the parent loop (see loop_nest_lcssa
768   // test case in zero-btc.ll for an example), thus changing the parent's
769   // exit blocks.  If that happened, we need to rebuild LCSSA on the outermost
770   // loop which might have a had a block removed.
771   if (OutermostLoop != L)
772     formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
773 }
774 
775 
776 /// Checks if \p L has an exiting latch branch.  There may also be other
777 /// exiting blocks.  Returns branch instruction terminating the loop
778 /// latch if above check is successful, nullptr otherwise.
779 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
780   BasicBlock *Latch = L->getLoopLatch();
781   if (!Latch)
782     return nullptr;
783 
784   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
785   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
786     return nullptr;
787 
788   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
789           LatchBR->getSuccessor(1) == L->getHeader()) &&
790          "At least one edge out of the latch must go to the header");
791 
792   return LatchBR;
793 }
794 
795 Optional<unsigned>
796 llvm::getLoopEstimatedTripCount(Loop *L,
797                                 unsigned *EstimatedLoopInvocationWeight) {
798   // Currently we take the estimate exit count only from the loop latch,
799   // ignoring other exiting blocks.  This can overestimate the trip count
800   // if we exit through another exit, but can never underestimate it.
801   // TODO: incorporate information from other exits
802   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
803   if (!LatchBranch)
804     return None;
805 
806   // To estimate the number of times the loop body was executed, we want to
807   // know the number of times the backedge was taken, vs. the number of times
808   // we exited the loop.
809   uint64_t BackedgeTakenWeight, LatchExitWeight;
810   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
811     return None;
812 
813   if (LatchBranch->getSuccessor(0) != L->getHeader())
814     std::swap(BackedgeTakenWeight, LatchExitWeight);
815 
816   if (!LatchExitWeight)
817     return None;
818 
819   if (EstimatedLoopInvocationWeight)
820     *EstimatedLoopInvocationWeight = LatchExitWeight;
821 
822   // Estimated backedge taken count is a ratio of the backedge taken weight by
823   // the weight of the edge exiting the loop, rounded to nearest.
824   uint64_t BackedgeTakenCount =
825       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
826   // Estimated trip count is one plus estimated backedge taken count.
827   return BackedgeTakenCount + 1;
828 }
829 
830 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
831                                      unsigned EstimatedloopInvocationWeight) {
832   // At the moment, we currently support changing the estimate trip count of
833   // the latch branch only.  We could extend this API to manipulate estimated
834   // trip counts for any exit.
835   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
836   if (!LatchBranch)
837     return false;
838 
839   // Calculate taken and exit weights.
840   unsigned LatchExitWeight = 0;
841   unsigned BackedgeTakenWeight = 0;
842 
843   if (EstimatedTripCount > 0) {
844     LatchExitWeight = EstimatedloopInvocationWeight;
845     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
846   }
847 
848   // Make a swap if back edge is taken when condition is "false".
849   if (LatchBranch->getSuccessor(0) != L->getHeader())
850     std::swap(BackedgeTakenWeight, LatchExitWeight);
851 
852   MDBuilder MDB(LatchBranch->getContext());
853 
854   // Set/Update profile metadata.
855   LatchBranch->setMetadata(
856       LLVMContext::MD_prof,
857       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
858 
859   return true;
860 }
861 
862 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
863                                               ScalarEvolution &SE) {
864   Loop *OuterL = InnerLoop->getParentLoop();
865   if (!OuterL)
866     return true;
867 
868   // Get the backedge taken count for the inner loop
869   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
870   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
871   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
872       !InnerLoopBECountSC->getType()->isIntegerTy())
873     return false;
874 
875   // Get whether count is invariant to the outer loop
876   ScalarEvolution::LoopDisposition LD =
877       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
878   if (LD != ScalarEvolution::LoopInvariant)
879     return false;
880 
881   return true;
882 }
883 
884 CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
885   switch (RK) {
886   default:
887     llvm_unreachable("Unknown min/max recurrence kind");
888   case RecurKind::UMin:
889     return CmpInst::ICMP_ULT;
890   case RecurKind::UMax:
891     return CmpInst::ICMP_UGT;
892   case RecurKind::SMin:
893     return CmpInst::ICMP_SLT;
894   case RecurKind::SMax:
895     return CmpInst::ICMP_SGT;
896   case RecurKind::FMin:
897     return CmpInst::FCMP_OLT;
898   case RecurKind::FMax:
899     return CmpInst::FCMP_OGT;
900   }
901 }
902 
903 Value *llvm::createSelectCmpOp(IRBuilderBase &Builder, Value *StartVal,
904                                RecurKind RK, Value *Left, Value *Right) {
905   if (auto VTy = dyn_cast<VectorType>(Left->getType()))
906     StartVal = Builder.CreateVectorSplat(VTy->getElementCount(), StartVal);
907   Value *Cmp =
908       Builder.CreateCmp(CmpInst::ICMP_NE, Left, StartVal, "rdx.select.cmp");
909   return Builder.CreateSelect(Cmp, Left, Right, "rdx.select");
910 }
911 
912 Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
913                             Value *Right) {
914   CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
915   Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
916   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
917   return Select;
918 }
919 
920 // Helper to generate an ordered reduction.
921 Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
922                                  unsigned Op, RecurKind RdxKind) {
923   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
924 
925   // Extract and apply reduction ops in ascending order:
926   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
927   Value *Result = Acc;
928   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
929     Value *Ext =
930         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
931 
932     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
933       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
934                                    "bin.rdx");
935     } else {
936       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
937              "Invalid min/max");
938       Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
939     }
940   }
941 
942   return Result;
943 }
944 
945 // Helper to generate a log2 shuffle reduction.
946 Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
947                                  unsigned Op, RecurKind RdxKind) {
948   unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
949   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
950   // and vector ops, reducing the set of values being computed by half each
951   // round.
952   assert(isPowerOf2_32(VF) &&
953          "Reduction emission only supported for pow2 vectors!");
954   // Note: fast-math-flags flags are controlled by the builder configuration
955   // and are assumed to apply to all generated arithmetic instructions.  Other
956   // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
957   // of the builder configuration, and since they're not passed explicitly,
958   // will never be relevant here.  Note that it would be generally unsound to
959   // propagate these from an intrinsic call to the expansion anyways as we/
960   // change the order of operations.
961   Value *TmpVec = Src;
962   SmallVector<int, 32> ShuffleMask(VF);
963   for (unsigned i = VF; i != 1; i >>= 1) {
964     // Move the upper half of the vector to the lower half.
965     for (unsigned j = 0; j != i / 2; ++j)
966       ShuffleMask[j] = i / 2 + j;
967 
968     // Fill the rest of the mask with undef.
969     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
970 
971     Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
972 
973     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
974       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
975                                    "bin.rdx");
976     } else {
977       assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
978              "Invalid min/max");
979       TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
980     }
981   }
982   // The result is in the first element of the vector.
983   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
984 }
985 
986 Value *llvm::createSelectCmpTargetReduction(IRBuilderBase &Builder,
987                                             const TargetTransformInfo *TTI,
988                                             Value *Src,
989                                             const RecurrenceDescriptor &Desc,
990                                             PHINode *OrigPhi) {
991   assert(RecurrenceDescriptor::isSelectCmpRecurrenceKind(
992              Desc.getRecurrenceKind()) &&
993          "Unexpected reduction kind");
994   Value *InitVal = Desc.getRecurrenceStartValue();
995   Value *NewVal = nullptr;
996 
997   // First use the original phi to determine the new value we're trying to
998   // select from in the loop.
999   SelectInst *SI = nullptr;
1000   for (auto *U : OrigPhi->users()) {
1001     if ((SI = dyn_cast<SelectInst>(U)))
1002       break;
1003   }
1004   assert(SI && "One user of the original phi should be a select");
1005 
1006   if (SI->getTrueValue() == OrigPhi)
1007     NewVal = SI->getFalseValue();
1008   else {
1009     assert(SI->getFalseValue() == OrigPhi &&
1010            "At least one input to the select should be the original Phi");
1011     NewVal = SI->getTrueValue();
1012   }
1013 
1014   // Create a splat vector with the new value and compare this to the vector
1015   // we want to reduce.
1016   ElementCount EC = cast<VectorType>(Src->getType())->getElementCount();
1017   Value *Right = Builder.CreateVectorSplat(EC, InitVal);
1018   Value *Cmp =
1019       Builder.CreateCmp(CmpInst::ICMP_NE, Src, Right, "rdx.select.cmp");
1020 
1021   // If any predicate is true it means that we want to select the new value.
1022   Cmp = Builder.CreateOrReduce(Cmp);
1023   return Builder.CreateSelect(Cmp, NewVal, InitVal, "rdx.select");
1024 }
1025 
1026 Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder,
1027                                          const TargetTransformInfo *TTI,
1028                                          Value *Src, RecurKind RdxKind) {
1029   auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
1030   switch (RdxKind) {
1031   case RecurKind::Add:
1032     return Builder.CreateAddReduce(Src);
1033   case RecurKind::Mul:
1034     return Builder.CreateMulReduce(Src);
1035   case RecurKind::And:
1036     return Builder.CreateAndReduce(Src);
1037   case RecurKind::Or:
1038     return Builder.CreateOrReduce(Src);
1039   case RecurKind::Xor:
1040     return Builder.CreateXorReduce(Src);
1041   case RecurKind::FMulAdd:
1042   case RecurKind::FAdd:
1043     return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy),
1044                                     Src);
1045   case RecurKind::FMul:
1046     return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src);
1047   case RecurKind::SMax:
1048     return Builder.CreateIntMaxReduce(Src, true);
1049   case RecurKind::SMin:
1050     return Builder.CreateIntMinReduce(Src, true);
1051   case RecurKind::UMax:
1052     return Builder.CreateIntMaxReduce(Src, false);
1053   case RecurKind::UMin:
1054     return Builder.CreateIntMinReduce(Src, false);
1055   case RecurKind::FMax:
1056     return Builder.CreateFPMaxReduce(Src);
1057   case RecurKind::FMin:
1058     return Builder.CreateFPMinReduce(Src);
1059   default:
1060     llvm_unreachable("Unhandled opcode");
1061   }
1062 }
1063 
1064 Value *llvm::createTargetReduction(IRBuilderBase &B,
1065                                    const TargetTransformInfo *TTI,
1066                                    const RecurrenceDescriptor &Desc, Value *Src,
1067                                    PHINode *OrigPhi) {
1068   // TODO: Support in-order reductions based on the recurrence descriptor.
1069   // All ops in the reduction inherit fast-math-flags from the recurrence
1070   // descriptor.
1071   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1072   B.setFastMathFlags(Desc.getFastMathFlags());
1073 
1074   RecurKind RK = Desc.getRecurrenceKind();
1075   if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
1076     return createSelectCmpTargetReduction(B, TTI, Src, Desc, OrigPhi);
1077 
1078   return createSimpleTargetReduction(B, TTI, Src, RK);
1079 }
1080 
1081 Value *llvm::createOrderedReduction(IRBuilderBase &B,
1082                                     const RecurrenceDescriptor &Desc,
1083                                     Value *Src, Value *Start) {
1084   assert((Desc.getRecurrenceKind() == RecurKind::FAdd ||
1085           Desc.getRecurrenceKind() == RecurKind::FMulAdd) &&
1086          "Unexpected reduction kind");
1087   assert(Src->getType()->isVectorTy() && "Expected a vector type");
1088   assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
1089 
1090   return B.CreateFAddReduce(Start, Src);
1091 }
1092 
1093 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1094   auto *VecOp = dyn_cast<Instruction>(I);
1095   if (!VecOp)
1096     return;
1097   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1098                                             : dyn_cast<Instruction>(OpValue);
1099   if (!Intersection)
1100     return;
1101   const unsigned Opcode = Intersection->getOpcode();
1102   VecOp->copyIRFlags(Intersection);
1103   for (auto *V : VL) {
1104     auto *Instr = dyn_cast<Instruction>(V);
1105     if (!Instr)
1106       continue;
1107     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1108       VecOp->andIRFlags(V);
1109   }
1110 }
1111 
1112 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1113                                  ScalarEvolution &SE) {
1114   const SCEV *Zero = SE.getZero(S->getType());
1115   return SE.isAvailableAtLoopEntry(S, L) &&
1116          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1117 }
1118 
1119 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1120                                     ScalarEvolution &SE) {
1121   const SCEV *Zero = SE.getZero(S->getType());
1122   return SE.isAvailableAtLoopEntry(S, L) &&
1123          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1124 }
1125 
1126 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1127                              bool Signed) {
1128   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1129   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1130     APInt::getMinValue(BitWidth);
1131   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1132   return SE.isAvailableAtLoopEntry(S, L) &&
1133          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1134                                      SE.getConstant(Min));
1135 }
1136 
1137 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1138                              bool Signed) {
1139   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1140   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1141     APInt::getMaxValue(BitWidth);
1142   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1143   return SE.isAvailableAtLoopEntry(S, L) &&
1144          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1145                                      SE.getConstant(Max));
1146 }
1147 
1148 //===----------------------------------------------------------------------===//
1149 // rewriteLoopExitValues - Optimize IV users outside the loop.
1150 // As a side effect, reduces the amount of IV processing within the loop.
1151 //===----------------------------------------------------------------------===//
1152 
1153 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1154   SmallPtrSet<const Instruction *, 8> Visited;
1155   SmallVector<const Instruction *, 8> WorkList;
1156   Visited.insert(I);
1157   WorkList.push_back(I);
1158   while (!WorkList.empty()) {
1159     const Instruction *Curr = WorkList.pop_back_val();
1160     // This use is outside the loop, nothing to do.
1161     if (!L->contains(Curr))
1162       continue;
1163     // Do we assume it is a "hard" use which will not be eliminated easily?
1164     if (Curr->mayHaveSideEffects())
1165       return true;
1166     // Otherwise, add all its users to worklist.
1167     for (auto U : Curr->users()) {
1168       auto *UI = cast<Instruction>(U);
1169       if (Visited.insert(UI).second)
1170         WorkList.push_back(UI);
1171     }
1172   }
1173   return false;
1174 }
1175 
1176 // Collect information about PHI nodes which can be transformed in
1177 // rewriteLoopExitValues.
1178 struct RewritePhi {
1179   PHINode *PN;               // For which PHI node is this replacement?
1180   unsigned Ith;              // For which incoming value?
1181   const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
1182   Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
1183   bool HighCost;               // Is this expansion a high-cost?
1184 
1185   RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
1186              bool H)
1187       : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
1188         HighCost(H) {}
1189 };
1190 
1191 // Check whether it is possible to delete the loop after rewriting exit
1192 // value. If it is possible, ignore ReplaceExitValue and do rewriting
1193 // aggressively.
1194 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1195   BasicBlock *Preheader = L->getLoopPreheader();
1196   // If there is no preheader, the loop will not be deleted.
1197   if (!Preheader)
1198     return false;
1199 
1200   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1201   // We obviate multiple ExitingBlocks case for simplicity.
1202   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1203   // after exit value rewriting, we can enhance the logic here.
1204   SmallVector<BasicBlock *, 4> ExitingBlocks;
1205   L->getExitingBlocks(ExitingBlocks);
1206   SmallVector<BasicBlock *, 8> ExitBlocks;
1207   L->getUniqueExitBlocks(ExitBlocks);
1208   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1209     return false;
1210 
1211   BasicBlock *ExitBlock = ExitBlocks[0];
1212   BasicBlock::iterator BI = ExitBlock->begin();
1213   while (PHINode *P = dyn_cast<PHINode>(BI)) {
1214     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1215 
1216     // If the Incoming value of P is found in RewritePhiSet, we know it
1217     // could be rewritten to use a loop invariant value in transformation
1218     // phase later. Skip it in the loop invariant check below.
1219     bool found = false;
1220     for (const RewritePhi &Phi : RewritePhiSet) {
1221       unsigned i = Phi.Ith;
1222       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1223         found = true;
1224         break;
1225       }
1226     }
1227 
1228     Instruction *I;
1229     if (!found && (I = dyn_cast<Instruction>(Incoming)))
1230       if (!L->hasLoopInvariantOperands(I))
1231         return false;
1232 
1233     ++BI;
1234   }
1235 
1236   for (auto *BB : L->blocks())
1237     if (llvm::any_of(*BB, [](Instruction &I) {
1238           return I.mayHaveSideEffects();
1239         }))
1240       return false;
1241 
1242   return true;
1243 }
1244 
1245 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
1246                                 ScalarEvolution *SE,
1247                                 const TargetTransformInfo *TTI,
1248                                 SCEVExpander &Rewriter, DominatorTree *DT,
1249                                 ReplaceExitVal ReplaceExitValue,
1250                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1251   // Check a pre-condition.
1252   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1253          "Indvars did not preserve LCSSA!");
1254 
1255   SmallVector<BasicBlock*, 8> ExitBlocks;
1256   L->getUniqueExitBlocks(ExitBlocks);
1257 
1258   SmallVector<RewritePhi, 8> RewritePhiSet;
1259   // Find all values that are computed inside the loop, but used outside of it.
1260   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
1261   // the exit blocks of the loop to find them.
1262   for (BasicBlock *ExitBB : ExitBlocks) {
1263     // If there are no PHI nodes in this exit block, then no values defined
1264     // inside the loop are used on this path, skip it.
1265     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1266     if (!PN) continue;
1267 
1268     unsigned NumPreds = PN->getNumIncomingValues();
1269 
1270     // Iterate over all of the PHI nodes.
1271     BasicBlock::iterator BBI = ExitBB->begin();
1272     while ((PN = dyn_cast<PHINode>(BBI++))) {
1273       if (PN->use_empty())
1274         continue; // dead use, don't replace it
1275 
1276       if (!SE->isSCEVable(PN->getType()))
1277         continue;
1278 
1279       // Iterate over all of the values in all the PHI nodes.
1280       for (unsigned i = 0; i != NumPreds; ++i) {
1281         // If the value being merged in is not integer or is not defined
1282         // in the loop, skip it.
1283         Value *InVal = PN->getIncomingValue(i);
1284         if (!isa<Instruction>(InVal))
1285           continue;
1286 
1287         // If this pred is for a subloop, not L itself, skip it.
1288         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1289           continue; // The Block is in a subloop, skip it.
1290 
1291         // Check that InVal is defined in the loop.
1292         Instruction *Inst = cast<Instruction>(InVal);
1293         if (!L->contains(Inst))
1294           continue;
1295 
1296         // Okay, this instruction has a user outside of the current loop
1297         // and varies predictably *inside* the loop.  Evaluate the value it
1298         // contains when the loop exits, if possible.  We prefer to start with
1299         // expressions which are true for all exits (so as to maximize
1300         // expression reuse by the SCEVExpander), but resort to per-exit
1301         // evaluation if that fails.
1302         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1303         if (isa<SCEVCouldNotCompute>(ExitValue) ||
1304             !SE->isLoopInvariant(ExitValue, L) ||
1305             !isSafeToExpand(ExitValue, *SE)) {
1306           // TODO: This should probably be sunk into SCEV in some way; maybe a
1307           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
1308           // most SCEV expressions and other recurrence types (e.g. shift
1309           // recurrences).  Is there existing code we can reuse?
1310           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1311           if (isa<SCEVCouldNotCompute>(ExitCount))
1312             continue;
1313           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1314             if (AddRec->getLoop() == L)
1315               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1316           if (isa<SCEVCouldNotCompute>(ExitValue) ||
1317               !SE->isLoopInvariant(ExitValue, L) ||
1318               !isSafeToExpand(ExitValue, *SE))
1319             continue;
1320         }
1321 
1322         // Computing the value outside of the loop brings no benefit if it is
1323         // definitely used inside the loop in a way which can not be optimized
1324         // away. Avoid doing so unless we know we have a value which computes
1325         // the ExitValue already. TODO: This should be merged into SCEV
1326         // expander to leverage its knowledge of existing expressions.
1327         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1328             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1329           continue;
1330 
1331         // Check if expansions of this SCEV would count as being high cost.
1332         bool HighCost = Rewriter.isHighCostExpansion(
1333             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1334 
1335         // Note that we must not perform expansions until after
1336         // we query *all* the costs, because if we perform temporary expansion
1337         // inbetween, one that we might not intend to keep, said expansion
1338         // *may* affect cost calculation of the the next SCEV's we'll query,
1339         // and next SCEV may errneously get smaller cost.
1340 
1341         // Collect all the candidate PHINodes to be rewritten.
1342         RewritePhiSet.emplace_back(PN, i, ExitValue, Inst, HighCost);
1343       }
1344     }
1345   }
1346 
1347   // TODO: evaluate whether it is beneficial to change how we calculate
1348   // high-cost: if we have SCEV 'A' which we know we will expand, should we
1349   // calculate the cost of other SCEV's after expanding SCEV 'A', thus
1350   // potentially giving cost bonus to those other SCEV's?
1351 
1352   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1353   int NumReplaced = 0;
1354 
1355   // Transformation.
1356   for (const RewritePhi &Phi : RewritePhiSet) {
1357     PHINode *PN = Phi.PN;
1358 
1359     // Only do the rewrite when the ExitValue can be expanded cheaply.
1360     // If LoopCanBeDel is true, rewrite exit value aggressively.
1361     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost)
1362       continue;
1363 
1364     Value *ExitVal = Rewriter.expandCodeFor(
1365         Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
1366 
1367     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
1368                       << '\n'
1369                       << "  LoopVal = " << *(Phi.ExpansionPoint) << "\n");
1370 
1371 #ifndef NDEBUG
1372     // If we reuse an instruction from a loop which is neither L nor one of
1373     // its containing loops, we end up breaking LCSSA form for this loop by
1374     // creating a new use of its instruction.
1375     if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1376       if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1377         if (EVL != L)
1378           assert(EVL->contains(L) && "LCSSA breach detected!");
1379 #endif
1380 
1381     NumReplaced++;
1382     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
1383     PN->setIncomingValue(Phi.Ith, ExitVal);
1384     // It's necessary to tell ScalarEvolution about this explicitly so that
1385     // it can walk the def-use list and forget all SCEVs, as it may not be
1386     // watching the PHI itself. Once the new exit value is in place, there
1387     // may not be a def-use connection between the loop and every instruction
1388     // which got a SCEVAddRecExpr for that loop.
1389     SE->forgetValue(PN);
1390 
1391     // If this instruction is dead now, delete it. Don't do it now to avoid
1392     // invalidating iterators.
1393     if (isInstructionTriviallyDead(Inst, TLI))
1394       DeadInsts.push_back(Inst);
1395 
1396     // Replace PN with ExitVal if that is legal and does not break LCSSA.
1397     if (PN->getNumIncomingValues() == 1 &&
1398         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
1399       PN->replaceAllUsesWith(ExitVal);
1400       PN->eraseFromParent();
1401     }
1402   }
1403 
1404   // The insertion point instruction may have been deleted; clear it out
1405   // so that the rewriter doesn't trip over it later.
1406   Rewriter.clearInsertPoint();
1407   return NumReplaced;
1408 }
1409 
1410 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1411 /// \p OrigLoop.
1412 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1413                                         Loop *RemainderLoop, uint64_t UF) {
1414   assert(UF > 0 && "Zero unrolled factor is not supported");
1415   assert(UnrolledLoop != RemainderLoop &&
1416          "Unrolled and Remainder loops are expected to distinct");
1417 
1418   // Get number of iterations in the original scalar loop.
1419   unsigned OrigLoopInvocationWeight = 0;
1420   Optional<unsigned> OrigAverageTripCount =
1421       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1422   if (!OrigAverageTripCount)
1423     return;
1424 
1425   // Calculate number of iterations in unrolled loop.
1426   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1427   // Calculate number of iterations for remainder loop.
1428   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1429 
1430   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1431                             OrigLoopInvocationWeight);
1432   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1433                             OrigLoopInvocationWeight);
1434 }
1435 
1436 /// Utility that implements appending of loops onto a worklist.
1437 /// Loops are added in preorder (analogous for reverse postorder for trees),
1438 /// and the worklist is processed LIFO.
1439 template <typename RangeT>
1440 void llvm::appendReversedLoopsToWorklist(
1441     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1442   // We use an internal worklist to build up the preorder traversal without
1443   // recursion.
1444   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1445 
1446   // We walk the initial sequence of loops in reverse because we generally want
1447   // to visit defs before uses and the worklist is LIFO.
1448   for (Loop *RootL : Loops) {
1449     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1450     assert(PreOrderWorklist.empty() &&
1451            "Must start with an empty preorder walk worklist.");
1452     PreOrderWorklist.push_back(RootL);
1453     do {
1454       Loop *L = PreOrderWorklist.pop_back_val();
1455       PreOrderWorklist.append(L->begin(), L->end());
1456       PreOrderLoops.push_back(L);
1457     } while (!PreOrderWorklist.empty());
1458 
1459     Worklist.insert(std::move(PreOrderLoops));
1460     PreOrderLoops.clear();
1461   }
1462 }
1463 
1464 template <typename RangeT>
1465 void llvm::appendLoopsToWorklist(RangeT &&Loops,
1466                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1467   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1468 }
1469 
1470 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1471     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1472 
1473 template void
1474 llvm::appendLoopsToWorklist<Loop &>(Loop &L,
1475                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
1476 
1477 void llvm::appendLoopsToWorklist(LoopInfo &LI,
1478                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1479   appendReversedLoopsToWorklist(LI, Worklist);
1480 }
1481 
1482 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
1483                       LoopInfo *LI, LPPassManager *LPM) {
1484   Loop &New = *LI->AllocateLoop();
1485   if (PL)
1486     PL->addChildLoop(&New);
1487   else
1488     LI->addTopLevelLoop(&New);
1489 
1490   if (LPM)
1491     LPM->addLoop(New);
1492 
1493   // Add all of the blocks in L to the new loop.
1494   for (BasicBlock *BB : L->blocks())
1495     if (LI->getLoopFor(BB) == L)
1496       New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
1497 
1498   // Add all of the subloops to the new loop.
1499   for (Loop *I : *L)
1500     cloneLoop(I, &New, VM, LI, LPM);
1501 
1502   return &New;
1503 }
1504 
1505 /// IR Values for the lower and upper bounds of a pointer evolution.  We
1506 /// need to use value-handles because SCEV expansion can invalidate previously
1507 /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
1508 /// a previous one.
1509 struct PointerBounds {
1510   TrackingVH<Value> Start;
1511   TrackingVH<Value> End;
1512 };
1513 
1514 /// Expand code for the lower and upper bound of the pointer group \p CG
1515 /// in \p TheLoop.  \return the values for the bounds.
1516 static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
1517                                   Loop *TheLoop, Instruction *Loc,
1518                                   SCEVExpander &Exp) {
1519   LLVMContext &Ctx = Loc->getContext();
1520   Type *PtrArithTy = Type::getInt8PtrTy(Ctx, CG->AddressSpace);
1521 
1522   Value *Start = nullptr, *End = nullptr;
1523   LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1524   Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1525   End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1526   LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1527   return {Start, End};
1528 }
1529 
1530 /// Turns a collection of checks into a collection of expanded upper and
1531 /// lower bounds for both pointers in the check.
1532 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
1533 expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
1534              Instruction *Loc, SCEVExpander &Exp) {
1535   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1536 
1537   // Here we're relying on the SCEV Expander's cache to only emit code for the
1538   // same bounds once.
1539   transform(PointerChecks, std::back_inserter(ChecksWithBounds),
1540             [&](const RuntimePointerCheck &Check) {
1541               PointerBounds First = expandBounds(Check.first, L, Loc, Exp),
1542                             Second = expandBounds(Check.second, L, Loc, Exp);
1543               return std::make_pair(First, Second);
1544             });
1545 
1546   return ChecksWithBounds;
1547 }
1548 
1549 Value *llvm::addRuntimeChecks(
1550     Instruction *Loc, Loop *TheLoop,
1551     const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
1552     SCEVExpander &Exp) {
1553   // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
1554   // TODO: Pass  RtPtrChecking instead of PointerChecks and SE separately, if possible
1555   auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, Exp);
1556 
1557   LLVMContext &Ctx = Loc->getContext();
1558   IRBuilder<> ChkBuilder(Loc);
1559   // Our instructions might fold to a constant.
1560   Value *MemoryRuntimeCheck = nullptr;
1561 
1562   for (const auto &Check : ExpandedChecks) {
1563     const PointerBounds &A = Check.first, &B = Check.second;
1564     // Check if two pointers (A and B) conflict where conflict is computed as:
1565     // start(A) <= end(B) && start(B) <= end(A)
1566     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1567     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
1568 
1569     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1570            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1571            "Trying to bounds check pointers with different address spaces");
1572 
1573     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1574     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1575 
1576     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1577     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1578     Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1579     Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
1580 
1581     // [A|B].Start points to the first accessed byte under base [A|B].
1582     // [A|B].End points to the last accessed byte, plus one.
1583     // There is no conflict when the intervals are disjoint:
1584     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
1585     //
1586     // bound0 = (B.Start < A.End)
1587     // bound1 = (A.Start < B.End)
1588     //  IsConflict = bound0 & bound1
1589     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
1590     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
1591     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1592     if (MemoryRuntimeCheck) {
1593       IsConflict =
1594           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1595     }
1596     MemoryRuntimeCheck = IsConflict;
1597   }
1598 
1599   return MemoryRuntimeCheck;
1600 }
1601 
1602 Optional<IVConditionInfo> llvm::hasPartialIVCondition(Loop &L,
1603                                                       unsigned MSSAThreshold,
1604                                                       MemorySSA &MSSA,
1605                                                       AAResults &AA) {
1606   auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator());
1607   if (!TI || !TI->isConditional())
1608     return {};
1609 
1610   auto *CondI = dyn_cast<CmpInst>(TI->getCondition());
1611   // The case with the condition outside the loop should already be handled
1612   // earlier.
1613   if (!CondI || !L.contains(CondI))
1614     return {};
1615 
1616   SmallVector<Instruction *> InstToDuplicate;
1617   InstToDuplicate.push_back(CondI);
1618 
1619   SmallVector<Value *, 4> WorkList;
1620   WorkList.append(CondI->op_begin(), CondI->op_end());
1621 
1622   SmallVector<MemoryAccess *, 4> AccessesToCheck;
1623   SmallVector<MemoryLocation, 4> AccessedLocs;
1624   while (!WorkList.empty()) {
1625     Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
1626     if (!I || !L.contains(I))
1627       continue;
1628 
1629     // TODO: support additional instructions.
1630     if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
1631       return {};
1632 
1633     // Do not duplicate volatile and atomic loads.
1634     if (auto *LI = dyn_cast<LoadInst>(I))
1635       if (LI->isVolatile() || LI->isAtomic())
1636         return {};
1637 
1638     InstToDuplicate.push_back(I);
1639     if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
1640       if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
1641         // Queue the defining access to check for alias checks.
1642         AccessesToCheck.push_back(MemUse->getDefiningAccess());
1643         AccessedLocs.push_back(MemoryLocation::get(I));
1644       } else {
1645         // MemoryDefs may clobber the location or may be atomic memory
1646         // operations. Bail out.
1647         return {};
1648       }
1649     }
1650     WorkList.append(I->op_begin(), I->op_end());
1651   }
1652 
1653   if (InstToDuplicate.empty())
1654     return {};
1655 
1656   SmallVector<BasicBlock *, 4> ExitingBlocks;
1657   L.getExitingBlocks(ExitingBlocks);
1658   auto HasNoClobbersOnPath =
1659       [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
1660        MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
1661                       SmallVector<MemoryAccess *, 4> AccessesToCheck)
1662       -> Optional<IVConditionInfo> {
1663     IVConditionInfo Info;
1664     // First, collect all blocks in the loop that are on a patch from Succ
1665     // to the header.
1666     SmallVector<BasicBlock *, 4> WorkList;
1667     WorkList.push_back(Succ);
1668     WorkList.push_back(Header);
1669     SmallPtrSet<BasicBlock *, 4> Seen;
1670     Seen.insert(Header);
1671     Info.PathIsNoop &=
1672         all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
1673 
1674     while (!WorkList.empty()) {
1675       BasicBlock *Current = WorkList.pop_back_val();
1676       if (!L.contains(Current))
1677         continue;
1678       const auto &SeenIns = Seen.insert(Current);
1679       if (!SeenIns.second)
1680         continue;
1681 
1682       Info.PathIsNoop &= all_of(
1683           *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
1684       WorkList.append(succ_begin(Current), succ_end(Current));
1685     }
1686 
1687     // Require at least 2 blocks on a path through the loop. This skips
1688     // paths that directly exit the loop.
1689     if (Seen.size() < 2)
1690       return {};
1691 
1692     // Next, check if there are any MemoryDefs that are on the path through
1693     // the loop (in the Seen set) and they may-alias any of the locations in
1694     // AccessedLocs. If that is the case, they may modify the condition and
1695     // partial unswitching is not possible.
1696     SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
1697     while (!AccessesToCheck.empty()) {
1698       MemoryAccess *Current = AccessesToCheck.pop_back_val();
1699       auto SeenI = SeenAccesses.insert(Current);
1700       if (!SeenI.second || !Seen.contains(Current->getBlock()))
1701         continue;
1702 
1703       // Bail out if exceeded the threshold.
1704       if (SeenAccesses.size() >= MSSAThreshold)
1705         return {};
1706 
1707       // MemoryUse are read-only accesses.
1708       if (isa<MemoryUse>(Current))
1709         continue;
1710 
1711       // For a MemoryDef, check if is aliases any of the location feeding
1712       // the original condition.
1713       if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
1714         if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
1715               return isModSet(
1716                   AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
1717             }))
1718           return {};
1719       }
1720 
1721       for (Use &U : Current->uses())
1722         AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
1723     }
1724 
1725     // We could also allow loops with known trip counts without mustprogress,
1726     // but ScalarEvolution may not be available.
1727     Info.PathIsNoop &= isMustProgress(&L);
1728 
1729     // If the path is considered a no-op so far, check if it reaches a
1730     // single exit block without any phis. This ensures no values from the
1731     // loop are used outside of the loop.
1732     if (Info.PathIsNoop) {
1733       for (auto *Exiting : ExitingBlocks) {
1734         if (!Seen.contains(Exiting))
1735           continue;
1736         for (auto *Succ : successors(Exiting)) {
1737           if (L.contains(Succ))
1738             continue;
1739 
1740           Info.PathIsNoop &= llvm::empty(Succ->phis()) &&
1741                              (!Info.ExitForPath || Info.ExitForPath == Succ);
1742           if (!Info.PathIsNoop)
1743             break;
1744           assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
1745                  "cannot have multiple exit blocks");
1746           Info.ExitForPath = Succ;
1747         }
1748       }
1749     }
1750     if (!Info.ExitForPath)
1751       Info.PathIsNoop = false;
1752 
1753     Info.InstToDuplicate = InstToDuplicate;
1754     return Info;
1755   };
1756 
1757   // If we branch to the same successor, partial unswitching will not be
1758   // beneficial.
1759   if (TI->getSuccessor(0) == TI->getSuccessor(1))
1760     return {};
1761 
1762   if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
1763                                       AccessesToCheck)) {
1764     Info->KnownValue = ConstantInt::getTrue(TI->getContext());
1765     return Info;
1766   }
1767   if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
1768                                       AccessesToCheck)) {
1769     Info->KnownValue = ConstantInt::getFalse(TI->getContext());
1770     return Info;
1771   }
1772 
1773   return {};
1774 }
1775