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