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/ScopeExit.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Analysis/BasicAliasAnalysis.h"
17 #include "llvm/Analysis/DomTreeUpdater.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/MemorySSA.h"
23 #include "llvm/Analysis/MemorySSAUpdater.h"
24 #include "llvm/Analysis/MustExecute.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
27 #include "llvm/Analysis/ScalarEvolutionExpander.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/PatternMatch.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/InitializePasses.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/KnownBits.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
48 
49 static cl::opt<bool> ForceReductionIntrinsic(
50     "force-reduction-intrinsics", cl::Hidden,
51     cl::desc("Force creating reduction intrinsics for testing."),
52     cl::init(false));
53 
54 #define DEBUG_TYPE "loop-utils"
55 
56 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
57 static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
58 
59 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
60                                    MemorySSAUpdater *MSSAU,
61                                    bool PreserveLCSSA) {
62   bool Changed = false;
63 
64   // We re-use a vector for the in-loop predecesosrs.
65   SmallVector<BasicBlock *, 4> InLoopPredecessors;
66 
67   auto RewriteExit = [&](BasicBlock *BB) {
68     assert(InLoopPredecessors.empty() &&
69            "Must start with an empty predecessors list!");
70     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
71 
72     // See if there are any non-loop predecessors of this exit block and
73     // keep track of the in-loop predecessors.
74     bool IsDedicatedExit = true;
75     for (auto *PredBB : predecessors(BB))
76       if (L->contains(PredBB)) {
77         if (isa<IndirectBrInst>(PredBB->getTerminator()))
78           // We cannot rewrite exiting edges from an indirectbr.
79           return false;
80         if (isa<CallBrInst>(PredBB->getTerminator()))
81           // We cannot rewrite exiting edges from a callbr.
82           return false;
83 
84         InLoopPredecessors.push_back(PredBB);
85       } else {
86         IsDedicatedExit = false;
87       }
88 
89     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
90 
91     // Nothing to do if this is already a dedicated exit.
92     if (IsDedicatedExit)
93       return false;
94 
95     auto *NewExitBB = SplitBlockPredecessors(
96         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
97 
98     if (!NewExitBB)
99       LLVM_DEBUG(
100           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
101                  << *L << "\n");
102     else
103       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
104                         << NewExitBB->getName() << "\n");
105     return true;
106   };
107 
108   // Walk the exit blocks directly rather than building up a data structure for
109   // them, but only visit each one once.
110   SmallPtrSet<BasicBlock *, 4> Visited;
111   for (auto *BB : L->blocks())
112     for (auto *SuccBB : successors(BB)) {
113       // We're looking for exit blocks so skip in-loop successors.
114       if (L->contains(SuccBB))
115         continue;
116 
117       // Visit each exit block exactly once.
118       if (!Visited.insert(SuccBB).second)
119         continue;
120 
121       Changed |= RewriteExit(SuccBB);
122     }
123 
124   return Changed;
125 }
126 
127 /// Returns the instructions that use values defined in the loop.
128 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
129   SmallVector<Instruction *, 8> UsedOutside;
130 
131   for (auto *Block : L->getBlocks())
132     // FIXME: I believe that this could use copy_if if the Inst reference could
133     // be adapted into a pointer.
134     for (auto &Inst : *Block) {
135       auto Users = Inst.users();
136       if (any_of(Users, [&](User *U) {
137             auto *Use = cast<Instruction>(U);
138             return !L->contains(Use->getParent());
139           }))
140         UsedOutside.push_back(&Inst);
141     }
142 
143   return UsedOutside;
144 }
145 
146 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
147   // By definition, all loop passes need the LoopInfo analysis and the
148   // Dominator tree it depends on. Because they all participate in the loop
149   // pass manager, they must also preserve these.
150   AU.addRequired<DominatorTreeWrapperPass>();
151   AU.addPreserved<DominatorTreeWrapperPass>();
152   AU.addRequired<LoopInfoWrapperPass>();
153   AU.addPreserved<LoopInfoWrapperPass>();
154 
155   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
156   // here because users shouldn't directly get them from this header.
157   extern char &LoopSimplifyID;
158   extern char &LCSSAID;
159   AU.addRequiredID(LoopSimplifyID);
160   AU.addPreservedID(LoopSimplifyID);
161   AU.addRequiredID(LCSSAID);
162   AU.addPreservedID(LCSSAID);
163   // This is used in the LPPassManager to perform LCSSA verification on passes
164   // which preserve lcssa form
165   AU.addRequired<LCSSAVerificationPass>();
166   AU.addPreserved<LCSSAVerificationPass>();
167 
168   // Loop passes are designed to run inside of a loop pass manager which means
169   // that any function analyses they require must be required by the first loop
170   // pass in the manager (so that it is computed before the loop pass manager
171   // runs) and preserved by all loop pasess in the manager. To make this
172   // reasonably robust, the set needed for most loop passes is maintained here.
173   // If your loop pass requires an analysis not listed here, you will need to
174   // carefully audit the loop pass manager nesting structure that results.
175   AU.addRequired<AAResultsWrapperPass>();
176   AU.addPreserved<AAResultsWrapperPass>();
177   AU.addPreserved<BasicAAWrapperPass>();
178   AU.addPreserved<GlobalsAAWrapperPass>();
179   AU.addPreserved<SCEVAAWrapperPass>();
180   AU.addRequired<ScalarEvolutionWrapperPass>();
181   AU.addPreserved<ScalarEvolutionWrapperPass>();
182   // FIXME: When all loop passes preserve MemorySSA, it can be required and
183   // preserved here instead of the individual handling in each pass.
184 }
185 
186 /// Manually defined generic "LoopPass" dependency initialization. This is used
187 /// to initialize the exact set of passes from above in \c
188 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
189 /// with:
190 ///
191 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
192 ///
193 /// As-if "LoopPass" were a pass.
194 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
195   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
196   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
197   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
198   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
199   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
200   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
201   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
202   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
203   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
204   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
205 }
206 
207 /// Create MDNode for input string.
208 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
209   LLVMContext &Context = TheLoop->getHeader()->getContext();
210   Metadata *MDs[] = {
211       MDString::get(Context, Name),
212       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
213   return MDNode::get(Context, MDs);
214 }
215 
216 /// Set input string into loop metadata by keeping other values intact.
217 /// If the string is already in loop metadata update value if it is
218 /// different.
219 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
220                                    unsigned V) {
221   SmallVector<Metadata *, 4> MDs(1);
222   // If the loop already has metadata, retain it.
223   MDNode *LoopID = TheLoop->getLoopID();
224   if (LoopID) {
225     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
226       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
227       // If it is of form key = value, try to parse it.
228       if (Node->getNumOperands() == 2) {
229         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
230         if (S && S->getString().equals(StringMD)) {
231           ConstantInt *IntMD =
232               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
233           if (IntMD && IntMD->getSExtValue() == V)
234             // It is already in place. Do nothing.
235             return;
236           // We need to update the value, so just skip it here and it will
237           // be added after copying other existed nodes.
238           continue;
239         }
240       }
241       MDs.push_back(Node);
242     }
243   }
244   // Add new metadata.
245   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
246   // Replace current metadata node with new one.
247   LLVMContext &Context = TheLoop->getHeader()->getContext();
248   MDNode *NewLoopID = MDNode::get(Context, MDs);
249   // Set operand 0 to refer to the loop id itself.
250   NewLoopID->replaceOperandWith(0, NewLoopID);
251   TheLoop->setLoopID(NewLoopID);
252 }
253 
254 /// Find string metadata for loop
255 ///
256 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
257 /// operand or null otherwise.  If the string metadata is not found return
258 /// Optional's not-a-value.
259 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
260                                                             StringRef Name) {
261   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
262   if (!MD)
263     return None;
264   switch (MD->getNumOperands()) {
265   case 1:
266     return nullptr;
267   case 2:
268     return &MD->getOperand(1);
269   default:
270     llvm_unreachable("loop metadata has 0 or 1 operand");
271   }
272 }
273 
274 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
275                                                    StringRef Name) {
276   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
277   if (!MD)
278     return None;
279   switch (MD->getNumOperands()) {
280   case 1:
281     // When the value is absent it is interpreted as 'attribute set'.
282     return true;
283   case 2:
284     if (ConstantInt *IntMD =
285             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
286       return IntMD->getZExtValue();
287     return true;
288   }
289   llvm_unreachable("unexpected number of options");
290 }
291 
292 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
293   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
294 }
295 
296 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
297                                                       StringRef Name) {
298   const MDOperand *AttrMD =
299       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
300   if (!AttrMD)
301     return None;
302 
303   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
304   if (!IntMD)
305     return None;
306 
307   return IntMD->getSExtValue();
308 }
309 
310 Optional<MDNode *> llvm::makeFollowupLoopID(
311     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
312     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
313   if (!OrigLoopID) {
314     if (AlwaysNew)
315       return nullptr;
316     return None;
317   }
318 
319   assert(OrigLoopID->getOperand(0) == OrigLoopID);
320 
321   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
322   bool InheritSomeAttrs =
323       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
324   SmallVector<Metadata *, 8> MDs;
325   MDs.push_back(nullptr);
326 
327   bool Changed = false;
328   if (InheritAllAttrs || InheritSomeAttrs) {
329     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
330       MDNode *Op = cast<MDNode>(Existing.get());
331 
332       auto InheritThisAttribute = [InheritSomeAttrs,
333                                    InheritOptionsExceptPrefix](MDNode *Op) {
334         if (!InheritSomeAttrs)
335           return false;
336 
337         // Skip malformatted attribute metadata nodes.
338         if (Op->getNumOperands() == 0)
339           return true;
340         Metadata *NameMD = Op->getOperand(0).get();
341         if (!isa<MDString>(NameMD))
342           return true;
343         StringRef AttrName = cast<MDString>(NameMD)->getString();
344 
345         // Do not inherit excluded attributes.
346         return !AttrName.startswith(InheritOptionsExceptPrefix);
347       };
348 
349       if (InheritThisAttribute(Op))
350         MDs.push_back(Op);
351       else
352         Changed = true;
353     }
354   } else {
355     // Modified if we dropped at least one attribute.
356     Changed = OrigLoopID->getNumOperands() > 1;
357   }
358 
359   bool HasAnyFollowup = false;
360   for (StringRef OptionName : FollowupOptions) {
361     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
362     if (!FollowupNode)
363       continue;
364 
365     HasAnyFollowup = true;
366     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
367       MDs.push_back(Option.get());
368       Changed = true;
369     }
370   }
371 
372   // Attributes of the followup loop not specified explicity, so signal to the
373   // transformation pass to add suitable attributes.
374   if (!AlwaysNew && !HasAnyFollowup)
375     return None;
376 
377   // If no attributes were added or remove, the previous loop Id can be reused.
378   if (!AlwaysNew && !Changed)
379     return OrigLoopID;
380 
381   // No attributes is equivalent to having no !llvm.loop metadata at all.
382   if (MDs.size() == 1)
383     return nullptr;
384 
385   // Build the new loop ID.
386   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
387   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
388   return FollowupLoopID;
389 }
390 
391 bool llvm::hasDisableAllTransformsHint(const Loop *L) {
392   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
393 }
394 
395 bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
396   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
397 }
398 
399 TransformationMode llvm::hasUnrollTransformation(Loop *L) {
400   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
401     return TM_SuppressedByUser;
402 
403   Optional<int> Count =
404       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
405   if (Count.hasValue())
406     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
407 
408   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
409     return TM_ForcedByUser;
410 
411   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
412     return TM_ForcedByUser;
413 
414   if (hasDisableAllTransformsHint(L))
415     return TM_Disable;
416 
417   return TM_Unspecified;
418 }
419 
420 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
421   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
422     return TM_SuppressedByUser;
423 
424   Optional<int> Count =
425       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
426   if (Count.hasValue())
427     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
428 
429   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
430     return TM_ForcedByUser;
431 
432   if (hasDisableAllTransformsHint(L))
433     return TM_Disable;
434 
435   return TM_Unspecified;
436 }
437 
438 TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
439   Optional<bool> Enable =
440       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
441 
442   if (Enable == false)
443     return TM_SuppressedByUser;
444 
445   Optional<int> VectorizeWidth =
446       getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
447   Optional<int> InterleaveCount =
448       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
449 
450   // 'Forcing' vector width and interleave count to one effectively disables
451   // this tranformation.
452   if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1)
453     return TM_SuppressedByUser;
454 
455   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
456     return TM_Disable;
457 
458   if (Enable == true)
459     return TM_ForcedByUser;
460 
461   if (VectorizeWidth == 1 && InterleaveCount == 1)
462     return TM_Disable;
463 
464   if (VectorizeWidth > 1 || InterleaveCount > 1)
465     return TM_Enable;
466 
467   if (hasDisableAllTransformsHint(L))
468     return TM_Disable;
469 
470   return TM_Unspecified;
471 }
472 
473 TransformationMode llvm::hasDistributeTransformation(Loop *L) {
474   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
475     return TM_ForcedByUser;
476 
477   if (hasDisableAllTransformsHint(L))
478     return TM_Disable;
479 
480   return TM_Unspecified;
481 }
482 
483 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
484   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
485     return TM_SuppressedByUser;
486 
487   if (hasDisableAllTransformsHint(L))
488     return TM_Disable;
489 
490   return TM_Unspecified;
491 }
492 
493 /// Does a BFS from a given node to all of its children inside a given loop.
494 /// The returned vector of nodes includes the starting point.
495 SmallVector<DomTreeNode *, 16>
496 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
497   SmallVector<DomTreeNode *, 16> Worklist;
498   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
499     // Only include subregions in the top level loop.
500     BasicBlock *BB = DTN->getBlock();
501     if (CurLoop->contains(BB))
502       Worklist.push_back(DTN);
503   };
504 
505   AddRegionToWorklist(N);
506 
507   for (size_t I = 0; I < Worklist.size(); I++)
508     for (DomTreeNode *Child : Worklist[I]->getChildren())
509       AddRegionToWorklist(Child);
510 
511   return Worklist;
512 }
513 
514 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
515                           LoopInfo *LI, MemorySSA *MSSA) {
516   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
517   auto *Preheader = L->getLoopPreheader();
518   assert(Preheader && "Preheader should exist!");
519 
520   std::unique_ptr<MemorySSAUpdater> MSSAU;
521   if (MSSA)
522     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
523 
524   // Now that we know the removal is safe, remove the loop by changing the
525   // branch from the preheader to go to the single exit block.
526   //
527   // Because we're deleting a large chunk of code at once, the sequence in which
528   // we remove things is very important to avoid invalidation issues.
529 
530   // Tell ScalarEvolution that the loop is deleted. Do this before
531   // deleting the loop so that ScalarEvolution can look at the loop
532   // to determine what it needs to clean up.
533   if (SE)
534     SE->forgetLoop(L);
535 
536   auto *ExitBlock = L->getUniqueExitBlock();
537   assert(ExitBlock && "Should have a unique exit block!");
538   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
539 
540   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
541   assert(OldBr && "Preheader must end with a branch");
542   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
543   // Connect the preheader to the exit block. Keep the old edge to the header
544   // around to perform the dominator tree update in two separate steps
545   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
546   // preheader -> header.
547   //
548   //
549   // 0.  Preheader          1.  Preheader           2.  Preheader
550   //        |                    |   |                   |
551   //        V                    |   V                   |
552   //      Header <--\            | Header <--\           | Header <--\
553   //       |  |     |            |  |  |     |           |  |  |     |
554   //       |  V     |            |  |  V     |           |  |  V     |
555   //       | Body --/            |  | Body --/           |  | Body --/
556   //       V                     V  V                    V  V
557   //      Exit                   Exit                    Exit
558   //
559   // By doing this is two separate steps we can perform the dominator tree
560   // update without using the batch update API.
561   //
562   // Even when the loop is never executed, we cannot remove the edge from the
563   // source block to the exit block. Consider the case where the unexecuted loop
564   // branches back to an outer loop. If we deleted the loop and removed the edge
565   // coming to this inner loop, this will break the outer loop structure (by
566   // deleting the backedge of the outer loop). If the outer loop is indeed a
567   // non-loop, it will be deleted in a future iteration of loop deletion pass.
568   IRBuilder<> Builder(OldBr);
569   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
570   // Remove the old branch. The conditional branch becomes a new terminator.
571   OldBr->eraseFromParent();
572 
573   // Rewrite phis in the exit block to get their inputs from the Preheader
574   // instead of the exiting block.
575   for (PHINode &P : ExitBlock->phis()) {
576     // Set the zero'th element of Phi to be from the preheader and remove all
577     // other incoming values. Given the loop has dedicated exits, all other
578     // incoming values must be from the exiting blocks.
579     int PredIndex = 0;
580     P.setIncomingBlock(PredIndex, Preheader);
581     // Removes all incoming values from all other exiting blocks (including
582     // duplicate values from an exiting block).
583     // Nuke all entries except the zero'th entry which is the preheader entry.
584     // NOTE! We need to remove Incoming Values in the reverse order as done
585     // below, to keep the indices valid for deletion (removeIncomingValues
586     // updates getNumIncomingValues and shifts all values down into the operand
587     // being deleted).
588     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
589       P.removeIncomingValue(e - i, false);
590 
591     assert((P.getNumIncomingValues() == 1 &&
592             P.getIncomingBlock(PredIndex) == Preheader) &&
593            "Should have exactly one value and that's from the preheader!");
594   }
595 
596   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
597   if (DT) {
598     DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
599     if (MSSA) {
600       MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, *DT);
601       if (VerifyMemorySSA)
602         MSSA->verifyMemorySSA();
603     }
604   }
605 
606   // Disconnect the loop body by branching directly to its exit.
607   Builder.SetInsertPoint(Preheader->getTerminator());
608   Builder.CreateBr(ExitBlock);
609   // Remove the old branch.
610   Preheader->getTerminator()->eraseFromParent();
611 
612   if (DT) {
613     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
614     if (MSSA) {
615       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
616                           *DT);
617       if (VerifyMemorySSA)
618         MSSA->verifyMemorySSA();
619       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
620                                                    L->block_end());
621       MSSAU->removeBlocks(DeadBlockSet);
622     }
623   }
624 
625   // Use a map to unique and a vector to guarantee deterministic ordering.
626   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
627   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
628 
629   // Given LCSSA form is satisfied, we should not have users of instructions
630   // within the dead loop outside of the loop. However, LCSSA doesn't take
631   // unreachable uses into account. We handle them here.
632   // We could do it after drop all references (in this case all users in the
633   // loop will be already eliminated and we have less work to do but according
634   // to API doc of User::dropAllReferences only valid operation after dropping
635   // references, is deletion. So let's substitute all usages of
636   // instruction from the loop with undef value of corresponding type first.
637   for (auto *Block : L->blocks())
638     for (Instruction &I : *Block) {
639       auto *Undef = UndefValue::get(I.getType());
640       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
641         Use &U = *UI;
642         ++UI;
643         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
644           if (L->contains(Usr->getParent()))
645             continue;
646         // If we have a DT then we can check that uses outside a loop only in
647         // unreachable block.
648         if (DT)
649           assert(!DT->isReachableFromEntry(U) &&
650                  "Unexpected user in reachable block");
651         U.set(Undef);
652       }
653       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
654       if (!DVI)
655         continue;
656       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
657       if (Key != DeadDebugSet.end())
658         continue;
659       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
660       DeadDebugInst.push_back(DVI);
661     }
662 
663   // After the loop has been deleted all the values defined and modified
664   // inside the loop are going to be unavailable.
665   // Since debug values in the loop have been deleted, inserting an undef
666   // dbg.value truncates the range of any dbg.value before the loop where the
667   // loop used to be. This is particularly important for constant values.
668   DIBuilder DIB(*ExitBlock->getModule());
669   Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
670   assert(InsertDbgValueBefore &&
671          "There should be a non-PHI instruction in exit block, else these "
672          "instructions will have no parent.");
673   for (auto *DVI : DeadDebugInst)
674     DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
675                                 DVI->getVariable(), DVI->getExpression(),
676                                 DVI->getDebugLoc(), InsertDbgValueBefore);
677 
678   // Remove the block from the reference counting scheme, so that we can
679   // delete it freely later.
680   for (auto *Block : L->blocks())
681     Block->dropAllReferences();
682 
683   if (MSSA && VerifyMemorySSA)
684     MSSA->verifyMemorySSA();
685 
686   if (LI) {
687     // Erase the instructions and the blocks without having to worry
688     // about ordering because we already dropped the references.
689     // NOTE: This iteration is safe because erasing the block does not remove
690     // its entry from the loop's block list.  We do that in the next section.
691     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
692          LpI != LpE; ++LpI)
693       (*LpI)->eraseFromParent();
694 
695     // Finally, the blocks from loopinfo.  This has to happen late because
696     // otherwise our loop iterators won't work.
697 
698     SmallPtrSet<BasicBlock *, 8> blocks;
699     blocks.insert(L->block_begin(), L->block_end());
700     for (BasicBlock *BB : blocks)
701       LI->removeBlock(BB);
702 
703     // The last step is to update LoopInfo now that we've eliminated this loop.
704     // Note: LoopInfo::erase remove the given loop and relink its subloops with
705     // its parent. While removeLoop/removeChildLoop remove the given loop but
706     // not relink its subloops, which is what we want.
707     if (Loop *ParentLoop = L->getParentLoop()) {
708       Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L);
709       assert(I != ParentLoop->end() && "Couldn't find loop");
710       ParentLoop->removeChildLoop(I);
711     } else {
712       Loop::iterator I = find(LI->begin(), LI->end(), L);
713       assert(I != LI->end() && "Couldn't find loop");
714       LI->removeLoop(I);
715     }
716     LI->destroy(L);
717   }
718 }
719 
720 /// Checks if \p L has single exit through latch block except possibly
721 /// "deoptimizing" exits. Returns branch instruction terminating the loop
722 /// latch if above check is successful, nullptr otherwise.
723 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
724   BasicBlock *Latch = L->getLoopLatch();
725   if (!Latch)
726     return nullptr;
727 
728   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
729   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
730     return nullptr;
731 
732   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
733           LatchBR->getSuccessor(1) == L->getHeader()) &&
734          "At least one edge out of the latch must go to the header");
735 
736   SmallVector<BasicBlock *, 4> ExitBlocks;
737   L->getUniqueNonLatchExitBlocks(ExitBlocks);
738   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
739         return !EB->getTerminatingDeoptimizeCall();
740       }))
741     return nullptr;
742 
743   return LatchBR;
744 }
745 
746 Optional<unsigned>
747 llvm::getLoopEstimatedTripCount(Loop *L,
748                                 unsigned *EstimatedLoopInvocationWeight) {
749   // Support loops with an exiting latch and other existing exists only
750   // deoptimize.
751   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
752   if (!LatchBranch)
753     return None;
754 
755   // To estimate the number of times the loop body was executed, we want to
756   // know the number of times the backedge was taken, vs. the number of times
757   // we exited the loop.
758   uint64_t BackedgeTakenWeight, LatchExitWeight;
759   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
760     return None;
761 
762   if (LatchBranch->getSuccessor(0) != L->getHeader())
763     std::swap(BackedgeTakenWeight, LatchExitWeight);
764 
765   if (!LatchExitWeight)
766     return None;
767 
768   if (EstimatedLoopInvocationWeight)
769     *EstimatedLoopInvocationWeight = LatchExitWeight;
770 
771   // Estimated backedge taken count is a ratio of the backedge taken weight by
772   // the weight of the edge exiting the loop, rounded to nearest.
773   uint64_t BackedgeTakenCount =
774       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
775   // Estimated trip count is one plus estimated backedge taken count.
776   return BackedgeTakenCount + 1;
777 }
778 
779 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
780                                      unsigned EstimatedloopInvocationWeight) {
781   // Support loops with an exiting latch and other existing exists only
782   // deoptimize.
783   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
784   if (!LatchBranch)
785     return false;
786 
787   // Calculate taken and exit weights.
788   unsigned LatchExitWeight = 0;
789   unsigned BackedgeTakenWeight = 0;
790 
791   if (EstimatedTripCount > 0) {
792     LatchExitWeight = EstimatedloopInvocationWeight;
793     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
794   }
795 
796   // Make a swap if back edge is taken when condition is "false".
797   if (LatchBranch->getSuccessor(0) != L->getHeader())
798     std::swap(BackedgeTakenWeight, LatchExitWeight);
799 
800   MDBuilder MDB(LatchBranch->getContext());
801 
802   // Set/Update profile metadata.
803   LatchBranch->setMetadata(
804       LLVMContext::MD_prof,
805       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
806 
807   return true;
808 }
809 
810 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
811                                               ScalarEvolution &SE) {
812   Loop *OuterL = InnerLoop->getParentLoop();
813   if (!OuterL)
814     return true;
815 
816   // Get the backedge taken count for the inner loop
817   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
818   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
819   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
820       !InnerLoopBECountSC->getType()->isIntegerTy())
821     return false;
822 
823   // Get whether count is invariant to the outer loop
824   ScalarEvolution::LoopDisposition LD =
825       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
826   if (LD != ScalarEvolution::LoopInvariant)
827     return false;
828 
829   return true;
830 }
831 
832 Value *llvm::createMinMaxOp(IRBuilderBase &Builder,
833                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
834                             Value *Left, Value *Right) {
835   CmpInst::Predicate P = CmpInst::ICMP_NE;
836   switch (RK) {
837   default:
838     llvm_unreachable("Unknown min/max recurrence kind");
839   case RecurrenceDescriptor::MRK_UIntMin:
840     P = CmpInst::ICMP_ULT;
841     break;
842   case RecurrenceDescriptor::MRK_UIntMax:
843     P = CmpInst::ICMP_UGT;
844     break;
845   case RecurrenceDescriptor::MRK_SIntMin:
846     P = CmpInst::ICMP_SLT;
847     break;
848   case RecurrenceDescriptor::MRK_SIntMax:
849     P = CmpInst::ICMP_SGT;
850     break;
851   case RecurrenceDescriptor::MRK_FloatMin:
852     P = CmpInst::FCMP_OLT;
853     break;
854   case RecurrenceDescriptor::MRK_FloatMax:
855     P = CmpInst::FCMP_OGT;
856     break;
857   }
858 
859   // We only match FP sequences that are 'fast', so we can unconditionally
860   // set it on any generated instructions.
861   IRBuilderBase::FastMathFlagGuard FMFG(Builder);
862   FastMathFlags FMF;
863   FMF.setFast();
864   Builder.setFastMathFlags(FMF);
865 
866   Value *Cmp;
867   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
868       RK == RecurrenceDescriptor::MRK_FloatMax)
869     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
870   else
871     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
872 
873   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
874   return Select;
875 }
876 
877 // Helper to generate an ordered reduction.
878 Value *
879 llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
880                           unsigned Op,
881                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
882                           ArrayRef<Value *> RedOps) {
883   unsigned VF = Src->getType()->getVectorNumElements();
884 
885   // Extract and apply reduction ops in ascending order:
886   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
887   Value *Result = Acc;
888   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
889     Value *Ext =
890         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
891 
892     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
893       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
894                                    "bin.rdx");
895     } else {
896       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
897              "Invalid min/max");
898       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
899     }
900 
901     if (!RedOps.empty())
902       propagateIRFlags(Result, RedOps);
903   }
904 
905   return Result;
906 }
907 
908 // Helper to generate a log2 shuffle reduction.
909 Value *
910 llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op,
911                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
912                           ArrayRef<Value *> RedOps) {
913   unsigned VF = Src->getType()->getVectorNumElements();
914   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
915   // and vector ops, reducing the set of values being computed by half each
916   // round.
917   assert(isPowerOf2_32(VF) &&
918          "Reduction emission only supported for pow2 vectors!");
919   Value *TmpVec = Src;
920   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
921   for (unsigned i = VF; i != 1; i >>= 1) {
922     // Move the upper half of the vector to the lower half.
923     for (unsigned j = 0; j != i / 2; ++j)
924       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
925 
926     // Fill the rest of the mask with undef.
927     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
928               UndefValue::get(Builder.getInt32Ty()));
929 
930     Value *Shuf = Builder.CreateShuffleVector(
931         TmpVec, UndefValue::get(TmpVec->getType()),
932         ConstantVector::get(ShuffleMask), "rdx.shuf");
933 
934     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
935       // The builder propagates its fast-math-flags setting.
936       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
937                                    "bin.rdx");
938     } else {
939       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
940              "Invalid min/max");
941       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
942     }
943     if (!RedOps.empty())
944       propagateIRFlags(TmpVec, RedOps);
945 
946     // We may compute the reassociated scalar ops in a way that does not
947     // preserve nsw/nuw etc. Conservatively, drop those flags.
948     if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec))
949       ReductionInst->dropPoisonGeneratingFlags();
950   }
951   // The result is in the first element of the vector.
952   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
953 }
954 
955 /// Create a simple vector reduction specified by an opcode and some
956 /// flags (if generating min/max reductions).
957 Value *llvm::createSimpleTargetReduction(
958     IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
959     Value *Src, TargetTransformInfo::ReductionFlags Flags,
960     ArrayRef<Value *> RedOps) {
961   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
962 
963   std::function<Value *()> BuildFunc;
964   using RD = RecurrenceDescriptor;
965   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
966 
967   switch (Opcode) {
968   case Instruction::Add:
969     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
970     break;
971   case Instruction::Mul:
972     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
973     break;
974   case Instruction::And:
975     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
976     break;
977   case Instruction::Or:
978     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
979     break;
980   case Instruction::Xor:
981     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
982     break;
983   case Instruction::FAdd:
984     BuildFunc = [&]() {
985       auto Rdx = Builder.CreateFAddReduce(
986           Constant::getNullValue(Src->getType()->getVectorElementType()), Src);
987       return Rdx;
988     };
989     break;
990   case Instruction::FMul:
991     BuildFunc = [&]() {
992       Type *Ty = Src->getType()->getVectorElementType();
993       auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
994       return Rdx;
995     };
996     break;
997   case Instruction::ICmp:
998     if (Flags.IsMaxOp) {
999       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1000       BuildFunc = [&]() {
1001         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1002       };
1003     } else {
1004       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1005       BuildFunc = [&]() {
1006         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1007       };
1008     }
1009     break;
1010   case Instruction::FCmp:
1011     if (Flags.IsMaxOp) {
1012       MinMaxKind = RD::MRK_FloatMax;
1013       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1014     } else {
1015       MinMaxKind = RD::MRK_FloatMin;
1016       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1017     }
1018     break;
1019   default:
1020     llvm_unreachable("Unhandled opcode");
1021     break;
1022   }
1023   if (ForceReductionIntrinsic ||
1024       TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1025     return BuildFunc();
1026   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1027 }
1028 
1029 /// Create a vector reduction using a given recurrence descriptor.
1030 Value *llvm::createTargetReduction(IRBuilderBase &B,
1031                                    const TargetTransformInfo *TTI,
1032                                    RecurrenceDescriptor &Desc, Value *Src,
1033                                    bool NoNaN) {
1034   // TODO: Support in-order reductions based on the recurrence descriptor.
1035   using RD = RecurrenceDescriptor;
1036   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1037   TargetTransformInfo::ReductionFlags Flags;
1038   Flags.NoNaN = NoNaN;
1039 
1040   // All ops in the reduction inherit fast-math-flags from the recurrence
1041   // descriptor.
1042   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1043   B.setFastMathFlags(Desc.getFastMathFlags());
1044 
1045   switch (RecKind) {
1046   case RD::RK_FloatAdd:
1047     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
1048   case RD::RK_FloatMult:
1049     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
1050   case RD::RK_IntegerAdd:
1051     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
1052   case RD::RK_IntegerMult:
1053     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
1054   case RD::RK_IntegerAnd:
1055     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
1056   case RD::RK_IntegerOr:
1057     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
1058   case RD::RK_IntegerXor:
1059     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
1060   case RD::RK_IntegerMinMax: {
1061     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
1062     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
1063     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
1064     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1065   }
1066   case RD::RK_FloatMinMax: {
1067     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
1068     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1069   }
1070   default:
1071     llvm_unreachable("Unhandled RecKind");
1072   }
1073 }
1074 
1075 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1076   auto *VecOp = dyn_cast<Instruction>(I);
1077   if (!VecOp)
1078     return;
1079   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1080                                             : dyn_cast<Instruction>(OpValue);
1081   if (!Intersection)
1082     return;
1083   const unsigned Opcode = Intersection->getOpcode();
1084   VecOp->copyIRFlags(Intersection);
1085   for (auto *V : VL) {
1086     auto *Instr = dyn_cast<Instruction>(V);
1087     if (!Instr)
1088       continue;
1089     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1090       VecOp->andIRFlags(V);
1091   }
1092 }
1093 
1094 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1095                                  ScalarEvolution &SE) {
1096   const SCEV *Zero = SE.getZero(S->getType());
1097   return SE.isAvailableAtLoopEntry(S, L) &&
1098          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1099 }
1100 
1101 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1102                                     ScalarEvolution &SE) {
1103   const SCEV *Zero = SE.getZero(S->getType());
1104   return SE.isAvailableAtLoopEntry(S, L) &&
1105          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1106 }
1107 
1108 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1109                              bool Signed) {
1110   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1111   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1112     APInt::getMinValue(BitWidth);
1113   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1114   return SE.isAvailableAtLoopEntry(S, L) &&
1115          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1116                                      SE.getConstant(Min));
1117 }
1118 
1119 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1120                              bool Signed) {
1121   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1122   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1123     APInt::getMaxValue(BitWidth);
1124   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1125   return SE.isAvailableAtLoopEntry(S, L) &&
1126          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1127                                      SE.getConstant(Max));
1128 }
1129 
1130 //===----------------------------------------------------------------------===//
1131 // rewriteLoopExitValues - Optimize IV users outside the loop.
1132 // As a side effect, reduces the amount of IV processing within the loop.
1133 //===----------------------------------------------------------------------===//
1134 
1135 // Return true if the SCEV expansion generated by the rewriter can replace the
1136 // original value. SCEV guarantees that it produces the same value, but the way
1137 // it is produced may be illegal IR.  Ideally, this function will only be
1138 // called for verification.
1139 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) {
1140   // If an SCEV expression subsumed multiple pointers, its expansion could
1141   // reassociate the GEP changing the base pointer. This is illegal because the
1142   // final address produced by a GEP chain must be inbounds relative to its
1143   // underlying object. Otherwise basic alias analysis, among other things,
1144   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
1145   // producing an expression involving multiple pointers. Until then, we must
1146   // bail out here.
1147   //
1148   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
1149   // because it understands lcssa phis while SCEV does not.
1150   Value *FromPtr = FromVal;
1151   Value *ToPtr = ToVal;
1152   if (auto *GEP = dyn_cast<GEPOperator>(FromVal))
1153     FromPtr = GEP->getPointerOperand();
1154 
1155   if (auto *GEP = dyn_cast<GEPOperator>(ToVal))
1156     ToPtr = GEP->getPointerOperand();
1157 
1158   if (FromPtr != FromVal || ToPtr != ToVal) {
1159     // Quickly check the common case
1160     if (FromPtr == ToPtr)
1161       return true;
1162 
1163     // SCEV may have rewritten an expression that produces the GEP's pointer
1164     // operand. That's ok as long as the pointer operand has the same base
1165     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
1166     // base of a recurrence. This handles the case in which SCEV expansion
1167     // converts a pointer type recurrence into a nonrecurrent pointer base
1168     // indexed by an integer recurrence.
1169 
1170     // If the GEP base pointer is a vector of pointers, abort.
1171     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
1172       return false;
1173 
1174     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
1175     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
1176     if (FromBase == ToBase)
1177       return true;
1178 
1179     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out "
1180                       << *FromBase << " != " << *ToBase << "\n");
1181 
1182     return false;
1183   }
1184   return true;
1185 }
1186 
1187 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1188   SmallPtrSet<const Instruction *, 8> Visited;
1189   SmallVector<const Instruction *, 8> WorkList;
1190   Visited.insert(I);
1191   WorkList.push_back(I);
1192   while (!WorkList.empty()) {
1193     const Instruction *Curr = WorkList.pop_back_val();
1194     // This use is outside the loop, nothing to do.
1195     if (!L->contains(Curr))
1196       continue;
1197     // Do we assume it is a "hard" use which will not be eliminated easily?
1198     if (Curr->mayHaveSideEffects())
1199       return true;
1200     // Otherwise, add all its users to worklist.
1201     for (auto U : Curr->users()) {
1202       auto *UI = cast<Instruction>(U);
1203       if (Visited.insert(UI).second)
1204         WorkList.push_back(UI);
1205     }
1206   }
1207   return false;
1208 }
1209 
1210 // Collect information about PHI nodes which can be transformed in
1211 // rewriteLoopExitValues.
1212 struct RewritePhi {
1213   PHINode *PN;
1214   unsigned Ith;   // Ith incoming value.
1215   Value *Val;     // Exit value after expansion.
1216   bool HighCost;  // High Cost when expansion.
1217 
1218   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
1219       : PN(P), Ith(I), Val(V), HighCost(H) {}
1220 };
1221 
1222 // Check whether it is possible to delete the loop after rewriting exit
1223 // value. If it is possible, ignore ReplaceExitValue and do rewriting
1224 // aggressively.
1225 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1226   BasicBlock *Preheader = L->getLoopPreheader();
1227   // If there is no preheader, the loop will not be deleted.
1228   if (!Preheader)
1229     return false;
1230 
1231   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1232   // We obviate multiple ExitingBlocks case for simplicity.
1233   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1234   // after exit value rewriting, we can enhance the logic here.
1235   SmallVector<BasicBlock *, 4> ExitingBlocks;
1236   L->getExitingBlocks(ExitingBlocks);
1237   SmallVector<BasicBlock *, 8> ExitBlocks;
1238   L->getUniqueExitBlocks(ExitBlocks);
1239   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1240     return false;
1241 
1242   BasicBlock *ExitBlock = ExitBlocks[0];
1243   BasicBlock::iterator BI = ExitBlock->begin();
1244   while (PHINode *P = dyn_cast<PHINode>(BI)) {
1245     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1246 
1247     // If the Incoming value of P is found in RewritePhiSet, we know it
1248     // could be rewritten to use a loop invariant value in transformation
1249     // phase later. Skip it in the loop invariant check below.
1250     bool found = false;
1251     for (const RewritePhi &Phi : RewritePhiSet) {
1252       unsigned i = Phi.Ith;
1253       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1254         found = true;
1255         break;
1256       }
1257     }
1258 
1259     Instruction *I;
1260     if (!found && (I = dyn_cast<Instruction>(Incoming)))
1261       if (!L->hasLoopInvariantOperands(I))
1262         return false;
1263 
1264     ++BI;
1265   }
1266 
1267   for (auto *BB : L->blocks())
1268     if (llvm::any_of(*BB, [](Instruction &I) {
1269           return I.mayHaveSideEffects();
1270         }))
1271       return false;
1272 
1273   return true;
1274 }
1275 
1276 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
1277                                 ScalarEvolution *SE,
1278                                 const TargetTransformInfo *TTI,
1279                                 SCEVExpander &Rewriter, DominatorTree *DT,
1280                                 ReplaceExitVal ReplaceExitValue,
1281                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1282   // Check a pre-condition.
1283   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1284          "Indvars did not preserve LCSSA!");
1285 
1286   SmallVector<BasicBlock*, 8> ExitBlocks;
1287   L->getUniqueExitBlocks(ExitBlocks);
1288 
1289   SmallVector<RewritePhi, 8> RewritePhiSet;
1290   // Find all values that are computed inside the loop, but used outside of it.
1291   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
1292   // the exit blocks of the loop to find them.
1293   for (BasicBlock *ExitBB : ExitBlocks) {
1294     // If there are no PHI nodes in this exit block, then no values defined
1295     // inside the loop are used on this path, skip it.
1296     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1297     if (!PN) continue;
1298 
1299     unsigned NumPreds = PN->getNumIncomingValues();
1300 
1301     // Iterate over all of the PHI nodes.
1302     BasicBlock::iterator BBI = ExitBB->begin();
1303     while ((PN = dyn_cast<PHINode>(BBI++))) {
1304       if (PN->use_empty())
1305         continue; // dead use, don't replace it
1306 
1307       if (!SE->isSCEVable(PN->getType()))
1308         continue;
1309 
1310       // It's necessary to tell ScalarEvolution about this explicitly so that
1311       // it can walk the def-use list and forget all SCEVs, as it may not be
1312       // watching the PHI itself. Once the new exit value is in place, there
1313       // may not be a def-use connection between the loop and every instruction
1314       // which got a SCEVAddRecExpr for that loop.
1315       SE->forgetValue(PN);
1316 
1317       // Iterate over all of the values in all the PHI nodes.
1318       for (unsigned i = 0; i != NumPreds; ++i) {
1319         // If the value being merged in is not integer or is not defined
1320         // in the loop, skip it.
1321         Value *InVal = PN->getIncomingValue(i);
1322         if (!isa<Instruction>(InVal))
1323           continue;
1324 
1325         // If this pred is for a subloop, not L itself, skip it.
1326         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1327           continue; // The Block is in a subloop, skip it.
1328 
1329         // Check that InVal is defined in the loop.
1330         Instruction *Inst = cast<Instruction>(InVal);
1331         if (!L->contains(Inst))
1332           continue;
1333 
1334         // Okay, this instruction has a user outside of the current loop
1335         // and varies predictably *inside* the loop.  Evaluate the value it
1336         // contains when the loop exits, if possible.  We prefer to start with
1337         // expressions which are true for all exits (so as to maximize
1338         // expression reuse by the SCEVExpander), but resort to per-exit
1339         // evaluation if that fails.
1340         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1341         if (isa<SCEVCouldNotCompute>(ExitValue) ||
1342             !SE->isLoopInvariant(ExitValue, L) ||
1343             !isSafeToExpand(ExitValue, *SE)) {
1344           // TODO: This should probably be sunk into SCEV in some way; maybe a
1345           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
1346           // most SCEV expressions and other recurrence types (e.g. shift
1347           // recurrences).  Is there existing code we can reuse?
1348           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1349           if (isa<SCEVCouldNotCompute>(ExitCount))
1350             continue;
1351           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1352             if (AddRec->getLoop() == L)
1353               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1354           if (isa<SCEVCouldNotCompute>(ExitValue) ||
1355               !SE->isLoopInvariant(ExitValue, L) ||
1356               !isSafeToExpand(ExitValue, *SE))
1357             continue;
1358         }
1359 
1360         // Computing the value outside of the loop brings no benefit if it is
1361         // definitely used inside the loop in a way which can not be optimized
1362         // away. Avoid doing so unless we know we have a value which computes
1363         // the ExitValue already. TODO: This should be merged into SCEV
1364         // expander to leverage its knowledge of existing expressions.
1365         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1366             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1367           continue;
1368 
1369         bool HighCost = Rewriter.isHighCostExpansion(
1370             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1371         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
1372 
1373         LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = "
1374                           << *ExitVal << '\n' << "  LoopVal = " << *Inst
1375                           << "\n");
1376 
1377         if (!isValidRewrite(SE, Inst, ExitVal)) {
1378           DeadInsts.push_back(ExitVal);
1379           continue;
1380         }
1381 
1382 #ifndef NDEBUG
1383         // If we reuse an instruction from a loop which is neither L nor one of
1384         // its containing loops, we end up breaking LCSSA form for this loop by
1385         // creating a new use of its instruction.
1386         if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1387           if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1388             if (EVL != L)
1389               assert(EVL->contains(L) && "LCSSA breach detected!");
1390 #endif
1391 
1392         // Collect all the candidate PHINodes to be rewritten.
1393         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
1394       }
1395     }
1396   }
1397 
1398   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1399   int NumReplaced = 0;
1400 
1401   // Transformation.
1402   for (const RewritePhi &Phi : RewritePhiSet) {
1403     PHINode *PN = Phi.PN;
1404     Value *ExitVal = Phi.Val;
1405 
1406     // Only do the rewrite when the ExitValue can be expanded cheaply.
1407     // If LoopCanBeDel is true, rewrite exit value aggressively.
1408     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
1409       DeadInsts.push_back(ExitVal);
1410       continue;
1411     }
1412 
1413     NumReplaced++;
1414     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
1415     PN->setIncomingValue(Phi.Ith, ExitVal);
1416 
1417     // If this instruction is dead now, delete it. Don't do it now to avoid
1418     // invalidating iterators.
1419     if (isInstructionTriviallyDead(Inst, TLI))
1420       DeadInsts.push_back(Inst);
1421 
1422     // Replace PN with ExitVal if that is legal and does not break LCSSA.
1423     if (PN->getNumIncomingValues() == 1 &&
1424         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
1425       PN->replaceAllUsesWith(ExitVal);
1426       PN->eraseFromParent();
1427     }
1428   }
1429 
1430   // The insertion point instruction may have been deleted; clear it out
1431   // so that the rewriter doesn't trip over it later.
1432   Rewriter.clearInsertPoint();
1433   return NumReplaced;
1434 }
1435 
1436 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1437 /// \p OrigLoop.
1438 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1439                                         Loop *RemainderLoop, uint64_t UF) {
1440   assert(UF > 0 && "Zero unrolled factor is not supported");
1441   assert(UnrolledLoop != RemainderLoop &&
1442          "Unrolled and Remainder loops are expected to distinct");
1443 
1444   // Get number of iterations in the original scalar loop.
1445   unsigned OrigLoopInvocationWeight = 0;
1446   Optional<unsigned> OrigAverageTripCount =
1447       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1448   if (!OrigAverageTripCount)
1449     return;
1450 
1451   // Calculate number of iterations in unrolled loop.
1452   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1453   // Calculate number of iterations for remainder loop.
1454   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1455 
1456   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1457                             OrigLoopInvocationWeight);
1458   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1459                             OrigLoopInvocationWeight);
1460 }
1461 
1462 /// Utility that implements appending of loops onto a worklist.
1463 /// Loops are added in preorder (analogous for reverse postorder for trees),
1464 /// and the worklist is processed LIFO.
1465 template <typename RangeT>
1466 void llvm::appendReversedLoopsToWorklist(
1467     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1468   // We use an internal worklist to build up the preorder traversal without
1469   // recursion.
1470   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1471 
1472   // We walk the initial sequence of loops in reverse because we generally want
1473   // to visit defs before uses and the worklist is LIFO.
1474   for (Loop *RootL : Loops) {
1475     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1476     assert(PreOrderWorklist.empty() &&
1477            "Must start with an empty preorder walk worklist.");
1478     PreOrderWorklist.push_back(RootL);
1479     do {
1480       Loop *L = PreOrderWorklist.pop_back_val();
1481       PreOrderWorklist.append(L->begin(), L->end());
1482       PreOrderLoops.push_back(L);
1483     } while (!PreOrderWorklist.empty());
1484 
1485     Worklist.insert(std::move(PreOrderLoops));
1486     PreOrderLoops.clear();
1487   }
1488 }
1489 
1490 template <typename RangeT>
1491 void llvm::appendLoopsToWorklist(RangeT &&Loops,
1492                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1493   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1494 }
1495 
1496 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1497     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1498 
1499 template void
1500 llvm::appendLoopsToWorklist<Loop &>(Loop &L,
1501                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
1502 
1503 void llvm::appendLoopsToWorklist(LoopInfo &LI,
1504                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1505   appendReversedLoopsToWorklist(LI, Worklist);
1506 }
1507 
1508 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
1509                       LoopInfo *LI, LPPassManager *LPM) {
1510   Loop &New = *LI->AllocateLoop();
1511   if (PL)
1512     PL->addChildLoop(&New);
1513   else
1514     LI->addTopLevelLoop(&New);
1515 
1516   if (LPM)
1517     LPM->addLoop(New);
1518 
1519   // Add all of the blocks in L to the new loop.
1520   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1521        I != E; ++I)
1522     if (LI->getLoopFor(*I) == L)
1523       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
1524 
1525   // Add all of the subloops to the new loop.
1526   for (Loop *I : *L)
1527     cloneLoop(I, &New, VM, LI, LPM);
1528 
1529   return &New;
1530 }
1531