1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines common loop utility functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/LoopUtils.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/BasicAliasAnalysis.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/MustExecute.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25 #include "llvm/Analysis/ScalarEvolutionExpander.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DomTreeUpdater.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 
42 using namespace llvm;
43 using namespace llvm::PatternMatch;
44 
45 #define DEBUG_TYPE "loop-utils"
46 
47 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
48 
49 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
50                                    bool PreserveLCSSA) {
51   bool Changed = false;
52 
53   // We re-use a vector for the in-loop predecesosrs.
54   SmallVector<BasicBlock *, 4> InLoopPredecessors;
55 
56   auto RewriteExit = [&](BasicBlock *BB) {
57     assert(InLoopPredecessors.empty() &&
58            "Must start with an empty predecessors list!");
59     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
60 
61     // See if there are any non-loop predecessors of this exit block and
62     // keep track of the in-loop predecessors.
63     bool IsDedicatedExit = true;
64     for (auto *PredBB : predecessors(BB))
65       if (L->contains(PredBB)) {
66         if (isa<IndirectBrInst>(PredBB->getTerminator()))
67           // We cannot rewrite exiting edges from an indirectbr.
68           return false;
69 
70         InLoopPredecessors.push_back(PredBB);
71       } else {
72         IsDedicatedExit = false;
73       }
74 
75     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
76 
77     // Nothing to do if this is already a dedicated exit.
78     if (IsDedicatedExit)
79       return false;
80 
81     auto *NewExitBB = SplitBlockPredecessors(
82         BB, InLoopPredecessors, ".loopexit", DT, LI, nullptr, PreserveLCSSA);
83 
84     if (!NewExitBB)
85       LLVM_DEBUG(
86           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
87                  << *L << "\n");
88     else
89       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
90                         << NewExitBB->getName() << "\n");
91     return true;
92   };
93 
94   // Walk the exit blocks directly rather than building up a data structure for
95   // them, but only visit each one once.
96   SmallPtrSet<BasicBlock *, 4> Visited;
97   for (auto *BB : L->blocks())
98     for (auto *SuccBB : successors(BB)) {
99       // We're looking for exit blocks so skip in-loop successors.
100       if (L->contains(SuccBB))
101         continue;
102 
103       // Visit each exit block exactly once.
104       if (!Visited.insert(SuccBB).second)
105         continue;
106 
107       Changed |= RewriteExit(SuccBB);
108     }
109 
110   return Changed;
111 }
112 
113 /// Returns the instructions that use values defined in the loop.
114 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
115   SmallVector<Instruction *, 8> UsedOutside;
116 
117   for (auto *Block : L->getBlocks())
118     // FIXME: I believe that this could use copy_if if the Inst reference could
119     // be adapted into a pointer.
120     for (auto &Inst : *Block) {
121       auto Users = Inst.users();
122       if (any_of(Users, [&](User *U) {
123             auto *Use = cast<Instruction>(U);
124             return !L->contains(Use->getParent());
125           }))
126         UsedOutside.push_back(&Inst);
127     }
128 
129   return UsedOutside;
130 }
131 
132 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
133   // By definition, all loop passes need the LoopInfo analysis and the
134   // Dominator tree it depends on. Because they all participate in the loop
135   // pass manager, they must also preserve these.
136   AU.addRequired<DominatorTreeWrapperPass>();
137   AU.addPreserved<DominatorTreeWrapperPass>();
138   AU.addRequired<LoopInfoWrapperPass>();
139   AU.addPreserved<LoopInfoWrapperPass>();
140 
141   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
142   // here because users shouldn't directly get them from this header.
143   extern char &LoopSimplifyID;
144   extern char &LCSSAID;
145   AU.addRequiredID(LoopSimplifyID);
146   AU.addPreservedID(LoopSimplifyID);
147   AU.addRequiredID(LCSSAID);
148   AU.addPreservedID(LCSSAID);
149   // This is used in the LPPassManager to perform LCSSA verification on passes
150   // which preserve lcssa form
151   AU.addRequired<LCSSAVerificationPass>();
152   AU.addPreserved<LCSSAVerificationPass>();
153 
154   // Loop passes are designed to run inside of a loop pass manager which means
155   // that any function analyses they require must be required by the first loop
156   // pass in the manager (so that it is computed before the loop pass manager
157   // runs) and preserved by all loop pasess in the manager. To make this
158   // reasonably robust, the set needed for most loop passes is maintained here.
159   // If your loop pass requires an analysis not listed here, you will need to
160   // carefully audit the loop pass manager nesting structure that results.
161   AU.addRequired<AAResultsWrapperPass>();
162   AU.addPreserved<AAResultsWrapperPass>();
163   AU.addPreserved<BasicAAWrapperPass>();
164   AU.addPreserved<GlobalsAAWrapperPass>();
165   AU.addPreserved<SCEVAAWrapperPass>();
166   AU.addRequired<ScalarEvolutionWrapperPass>();
167   AU.addPreserved<ScalarEvolutionWrapperPass>();
168 }
169 
170 /// Manually defined generic "LoopPass" dependency initialization. This is used
171 /// to initialize the exact set of passes from above in \c
172 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
173 /// with:
174 ///
175 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
176 ///
177 /// As-if "LoopPass" were a pass.
178 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
179   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
180   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
181   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
182   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
183   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
184   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
185   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
186   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
187   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
188 }
189 
190 /// Find string metadata for loop
191 ///
192 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
193 /// operand or null otherwise.  If the string metadata is not found return
194 /// Optional's not-a-value.
195 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
196                                                             StringRef Name) {
197   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
198   if (!MD)
199     return None;
200   switch (MD->getNumOperands()) {
201   case 1:
202     return nullptr;
203   case 2:
204     return &MD->getOperand(1);
205   default:
206     llvm_unreachable("loop metadata has 0 or 1 operand");
207   }
208 }
209 
210 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
211                                                    StringRef Name) {
212   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
213   if (!MD)
214     return None;
215   switch (MD->getNumOperands()) {
216   case 1:
217     // When the value is absent it is interpreted as 'attribute set'.
218     return true;
219   case 2:
220     return mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get());
221   }
222   llvm_unreachable("unexpected number of options");
223 }
224 
225 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
226   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
227 }
228 
229 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
230                                                       StringRef Name) {
231   const MDOperand *AttrMD =
232       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
233   if (!AttrMD)
234     return None;
235 
236   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
237   if (!IntMD)
238     return None;
239 
240   return IntMD->getSExtValue();
241 }
242 
243 Optional<MDNode *> llvm::makeFollowupLoopID(
244     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
245     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
246   if (!OrigLoopID) {
247     if (AlwaysNew)
248       return nullptr;
249     return None;
250   }
251 
252   assert(OrigLoopID->getOperand(0) == OrigLoopID);
253 
254   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
255   bool InheritSomeAttrs =
256       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
257   SmallVector<Metadata *, 8> MDs;
258   MDs.push_back(nullptr);
259 
260   bool Changed = false;
261   if (InheritAllAttrs || InheritSomeAttrs) {
262     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
263       MDNode *Op = cast<MDNode>(Existing.get());
264 
265       auto InheritThisAttribute = [InheritSomeAttrs,
266                                    InheritOptionsExceptPrefix](MDNode *Op) {
267         if (!InheritSomeAttrs)
268           return false;
269 
270         // Skip malformatted attribute metadata nodes.
271         if (Op->getNumOperands() == 0)
272           return true;
273         Metadata *NameMD = Op->getOperand(0).get();
274         if (!isa<MDString>(NameMD))
275           return true;
276         StringRef AttrName = cast<MDString>(NameMD)->getString();
277 
278         // Do not inherit excluded attributes.
279         return !AttrName.startswith(InheritOptionsExceptPrefix);
280       };
281 
282       if (InheritThisAttribute(Op))
283         MDs.push_back(Op);
284       else
285         Changed = true;
286     }
287   } else {
288     // Modified if we dropped at least one attribute.
289     Changed = OrigLoopID->getNumOperands() > 1;
290   }
291 
292   bool HasAnyFollowup = false;
293   for (StringRef OptionName : FollowupOptions) {
294     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
295     if (!FollowupNode)
296       continue;
297 
298     HasAnyFollowup = true;
299     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
300       MDs.push_back(Option.get());
301       Changed = true;
302     }
303   }
304 
305   // Attributes of the followup loop not specified explicity, so signal to the
306   // transformation pass to add suitable attributes.
307   if (!AlwaysNew && !HasAnyFollowup)
308     return None;
309 
310   // If no attributes were added or remove, the previous loop Id can be reused.
311   if (!AlwaysNew && !Changed)
312     return OrigLoopID;
313 
314   // No attributes is equivalent to having no !llvm.loop metadata at all.
315   if (MDs.size() == 1)
316     return nullptr;
317 
318   // Build the new loop ID.
319   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
320   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
321   return FollowupLoopID;
322 }
323 
324 bool llvm::hasDisableAllTransformsHint(const Loop *L) {
325   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
326 }
327 
328 TransformationMode llvm::hasUnrollTransformation(Loop *L) {
329   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
330     return TM_SuppressedByUser;
331 
332   Optional<int> Count =
333       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
334   if (Count.hasValue())
335     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
336 
337   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
338     return TM_ForcedByUser;
339 
340   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
341     return TM_ForcedByUser;
342 
343   if (hasDisableAllTransformsHint(L))
344     return TM_Disable;
345 
346   return TM_Unspecified;
347 }
348 
349 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
350   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
351     return TM_SuppressedByUser;
352 
353   Optional<int> Count =
354       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
355   if (Count.hasValue())
356     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
357 
358   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
359     return TM_ForcedByUser;
360 
361   if (hasDisableAllTransformsHint(L))
362     return TM_Disable;
363 
364   return TM_Unspecified;
365 }
366 
367 TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
368   Optional<bool> Enable =
369       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
370 
371   if (Enable == false)
372     return TM_SuppressedByUser;
373 
374   Optional<int> VectorizeWidth =
375       getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
376   Optional<int> InterleaveCount =
377       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
378 
379   if (Enable == true) {
380     // 'Forcing' vector width and interleave count to one effectively disables
381     // this tranformation.
382     if (VectorizeWidth == 1 && InterleaveCount == 1)
383       return TM_SuppressedByUser;
384     return TM_ForcedByUser;
385   }
386 
387   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
388     return TM_Disable;
389 
390   if (VectorizeWidth == 1 && InterleaveCount == 1)
391     return TM_Disable;
392 
393   if (VectorizeWidth > 1 || InterleaveCount > 1)
394     return TM_Enable;
395 
396   if (hasDisableAllTransformsHint(L))
397     return TM_Disable;
398 
399   return TM_Unspecified;
400 }
401 
402 TransformationMode llvm::hasDistributeTransformation(Loop *L) {
403   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
404     return TM_ForcedByUser;
405 
406   if (hasDisableAllTransformsHint(L))
407     return TM_Disable;
408 
409   return TM_Unspecified;
410 }
411 
412 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
413   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
414     return TM_SuppressedByUser;
415 
416   if (hasDisableAllTransformsHint(L))
417     return TM_Disable;
418 
419   return TM_Unspecified;
420 }
421 
422 /// Does a BFS from a given node to all of its children inside a given loop.
423 /// The returned vector of nodes includes the starting point.
424 SmallVector<DomTreeNode *, 16>
425 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
426   SmallVector<DomTreeNode *, 16> Worklist;
427   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
428     // Only include subregions in the top level loop.
429     BasicBlock *BB = DTN->getBlock();
430     if (CurLoop->contains(BB))
431       Worklist.push_back(DTN);
432   };
433 
434   AddRegionToWorklist(N);
435 
436   for (size_t I = 0; I < Worklist.size(); I++)
437     for (DomTreeNode *Child : Worklist[I]->getChildren())
438       AddRegionToWorklist(Child);
439 
440   return Worklist;
441 }
442 
443 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
444                           ScalarEvolution *SE = nullptr,
445                           LoopInfo *LI = nullptr) {
446   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
447   auto *Preheader = L->getLoopPreheader();
448   assert(Preheader && "Preheader should exist!");
449 
450   // Now that we know the removal is safe, remove the loop by changing the
451   // branch from the preheader to go to the single exit block.
452   //
453   // Because we're deleting a large chunk of code at once, the sequence in which
454   // we remove things is very important to avoid invalidation issues.
455 
456   // Tell ScalarEvolution that the loop is deleted. Do this before
457   // deleting the loop so that ScalarEvolution can look at the loop
458   // to determine what it needs to clean up.
459   if (SE)
460     SE->forgetLoop(L);
461 
462   auto *ExitBlock = L->getUniqueExitBlock();
463   assert(ExitBlock && "Should have a unique exit block!");
464   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
465 
466   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
467   assert(OldBr && "Preheader must end with a branch");
468   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
469   // Connect the preheader to the exit block. Keep the old edge to the header
470   // around to perform the dominator tree update in two separate steps
471   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
472   // preheader -> header.
473   //
474   //
475   // 0.  Preheader          1.  Preheader           2.  Preheader
476   //        |                    |   |                   |
477   //        V                    |   V                   |
478   //      Header <--\            | Header <--\           | Header <--\
479   //       |  |     |            |  |  |     |           |  |  |     |
480   //       |  V     |            |  |  V     |           |  |  V     |
481   //       | Body --/            |  | Body --/           |  | Body --/
482   //       V                     V  V                    V  V
483   //      Exit                   Exit                    Exit
484   //
485   // By doing this is two separate steps we can perform the dominator tree
486   // update without using the batch update API.
487   //
488   // Even when the loop is never executed, we cannot remove the edge from the
489   // source block to the exit block. Consider the case where the unexecuted loop
490   // branches back to an outer loop. If we deleted the loop and removed the edge
491   // coming to this inner loop, this will break the outer loop structure (by
492   // deleting the backedge of the outer loop). If the outer loop is indeed a
493   // non-loop, it will be deleted in a future iteration of loop deletion pass.
494   IRBuilder<> Builder(OldBr);
495   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
496   // Remove the old branch. The conditional branch becomes a new terminator.
497   OldBr->eraseFromParent();
498 
499   // Rewrite phis in the exit block to get their inputs from the Preheader
500   // instead of the exiting block.
501   for (PHINode &P : ExitBlock->phis()) {
502     // Set the zero'th element of Phi to be from the preheader and remove all
503     // other incoming values. Given the loop has dedicated exits, all other
504     // incoming values must be from the exiting blocks.
505     int PredIndex = 0;
506     P.setIncomingBlock(PredIndex, Preheader);
507     // Removes all incoming values from all other exiting blocks (including
508     // duplicate values from an exiting block).
509     // Nuke all entries except the zero'th entry which is the preheader entry.
510     // NOTE! We need to remove Incoming Values in the reverse order as done
511     // below, to keep the indices valid for deletion (removeIncomingValues
512     // updates getNumIncomingValues and shifts all values down into the operand
513     // being deleted).
514     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
515       P.removeIncomingValue(e - i, false);
516 
517     assert((P.getNumIncomingValues() == 1 &&
518             P.getIncomingBlock(PredIndex) == Preheader) &&
519            "Should have exactly one value and that's from the preheader!");
520   }
521 
522   // Disconnect the loop body by branching directly to its exit.
523   Builder.SetInsertPoint(Preheader->getTerminator());
524   Builder.CreateBr(ExitBlock);
525   // Remove the old branch.
526   Preheader->getTerminator()->eraseFromParent();
527 
528   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
529   if (DT) {
530     // Update the dominator tree by informing it about the new edge from the
531     // preheader to the exit.
532     DTU.insertEdge(Preheader, ExitBlock);
533     // Inform the dominator tree about the removed edge.
534     DTU.deleteEdge(Preheader, L->getHeader());
535   }
536 
537   // Use a map to unique and a vector to guarantee deterministic ordering.
538   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
539   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
540 
541   // Given LCSSA form is satisfied, we should not have users of instructions
542   // within the dead loop outside of the loop. However, LCSSA doesn't take
543   // unreachable uses into account. We handle them here.
544   // We could do it after drop all references (in this case all users in the
545   // loop will be already eliminated and we have less work to do but according
546   // to API doc of User::dropAllReferences only valid operation after dropping
547   // references, is deletion. So let's substitute all usages of
548   // instruction from the loop with undef value of corresponding type first.
549   for (auto *Block : L->blocks())
550     for (Instruction &I : *Block) {
551       auto *Undef = UndefValue::get(I.getType());
552       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
553         Use &U = *UI;
554         ++UI;
555         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
556           if (L->contains(Usr->getParent()))
557             continue;
558         // If we have a DT then we can check that uses outside a loop only in
559         // unreachable block.
560         if (DT)
561           assert(!DT->isReachableFromEntry(U) &&
562                  "Unexpected user in reachable block");
563         U.set(Undef);
564       }
565       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
566       if (!DVI)
567         continue;
568       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
569       if (Key != DeadDebugSet.end())
570         continue;
571       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
572       DeadDebugInst.push_back(DVI);
573     }
574 
575   // After the loop has been deleted all the values defined and modified
576   // inside the loop are going to be unavailable.
577   // Since debug values in the loop have been deleted, inserting an undef
578   // dbg.value truncates the range of any dbg.value before the loop where the
579   // loop used to be. This is particularly important for constant values.
580   DIBuilder DIB(*ExitBlock->getModule());
581   for (auto *DVI : DeadDebugInst)
582     DIB.insertDbgValueIntrinsic(
583         UndefValue::get(Builder.getInt32Ty()), DVI->getVariable(),
584         DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI());
585 
586   // Remove the block from the reference counting scheme, so that we can
587   // delete it freely later.
588   for (auto *Block : L->blocks())
589     Block->dropAllReferences();
590 
591   if (LI) {
592     // Erase the instructions and the blocks without having to worry
593     // about ordering because we already dropped the references.
594     // NOTE: This iteration is safe because erasing the block does not remove
595     // its entry from the loop's block list.  We do that in the next section.
596     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
597          LpI != LpE; ++LpI)
598       (*LpI)->eraseFromParent();
599 
600     // Finally, the blocks from loopinfo.  This has to happen late because
601     // otherwise our loop iterators won't work.
602 
603     SmallPtrSet<BasicBlock *, 8> blocks;
604     blocks.insert(L->block_begin(), L->block_end());
605     for (BasicBlock *BB : blocks)
606       LI->removeBlock(BB);
607 
608     // The last step is to update LoopInfo now that we've eliminated this loop.
609     LI->erase(L);
610   }
611 }
612 
613 Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
614   // Only support loops with a unique exiting block, and a latch.
615   if (!L->getExitingBlock())
616     return None;
617 
618   // Get the branch weights for the loop's backedge.
619   BranchInst *LatchBR =
620       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
621   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
622     return None;
623 
624   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
625           LatchBR->getSuccessor(1) == L->getHeader()) &&
626          "At least one edge out of the latch must go to the header");
627 
628   // To estimate the number of times the loop body was executed, we want to
629   // know the number of times the backedge was taken, vs. the number of times
630   // we exited the loop.
631   uint64_t TrueVal, FalseVal;
632   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
633     return None;
634 
635   if (!TrueVal || !FalseVal)
636     return 0;
637 
638   // Divide the count of the backedge by the count of the edge exiting the loop,
639   // rounding to nearest.
640   if (LatchBR->getSuccessor(0) == L->getHeader())
641     return (TrueVal + (FalseVal / 2)) / FalseVal;
642   else
643     return (FalseVal + (TrueVal / 2)) / TrueVal;
644 }
645 
646 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
647                                               ScalarEvolution &SE) {
648   Loop *OuterL = InnerLoop->getParentLoop();
649   if (!OuterL)
650     return true;
651 
652   // Get the backedge taken count for the inner loop
653   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
654   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
655   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
656       !InnerLoopBECountSC->getType()->isIntegerTy())
657     return false;
658 
659   // Get whether count is invariant to the outer loop
660   ScalarEvolution::LoopDisposition LD =
661       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
662   if (LD != ScalarEvolution::LoopInvariant)
663     return false;
664 
665   return true;
666 }
667 
668 /// Adds a 'fast' flag to floating point operations.
669 static Value *addFastMathFlag(Value *V) {
670   if (isa<FPMathOperator>(V)) {
671     FastMathFlags Flags;
672     Flags.setFast();
673     cast<Instruction>(V)->setFastMathFlags(Flags);
674   }
675   return V;
676 }
677 
678 Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
679                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
680                             Value *Left, Value *Right) {
681   CmpInst::Predicate P = CmpInst::ICMP_NE;
682   switch (RK) {
683   default:
684     llvm_unreachable("Unknown min/max recurrence kind");
685   case RecurrenceDescriptor::MRK_UIntMin:
686     P = CmpInst::ICMP_ULT;
687     break;
688   case RecurrenceDescriptor::MRK_UIntMax:
689     P = CmpInst::ICMP_UGT;
690     break;
691   case RecurrenceDescriptor::MRK_SIntMin:
692     P = CmpInst::ICMP_SLT;
693     break;
694   case RecurrenceDescriptor::MRK_SIntMax:
695     P = CmpInst::ICMP_SGT;
696     break;
697   case RecurrenceDescriptor::MRK_FloatMin:
698     P = CmpInst::FCMP_OLT;
699     break;
700   case RecurrenceDescriptor::MRK_FloatMax:
701     P = CmpInst::FCMP_OGT;
702     break;
703   }
704 
705   // We only match FP sequences that are 'fast', so we can unconditionally
706   // set it on any generated instructions.
707   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
708   FastMathFlags FMF;
709   FMF.setFast();
710   Builder.setFastMathFlags(FMF);
711 
712   Value *Cmp;
713   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
714       RK == RecurrenceDescriptor::MRK_FloatMax)
715     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
716   else
717     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
718 
719   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
720   return Select;
721 }
722 
723 // Helper to generate an ordered reduction.
724 Value *
725 llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
726                           unsigned Op,
727                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
728                           ArrayRef<Value *> RedOps) {
729   unsigned VF = Src->getType()->getVectorNumElements();
730 
731   // Extract and apply reduction ops in ascending order:
732   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
733   Value *Result = Acc;
734   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
735     Value *Ext =
736         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
737 
738     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
739       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
740                                    "bin.rdx");
741     } else {
742       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
743              "Invalid min/max");
744       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
745     }
746 
747     if (!RedOps.empty())
748       propagateIRFlags(Result, RedOps);
749   }
750 
751   return Result;
752 }
753 
754 // Helper to generate a log2 shuffle reduction.
755 Value *
756 llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
757                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
758                           ArrayRef<Value *> RedOps) {
759   unsigned VF = Src->getType()->getVectorNumElements();
760   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
761   // and vector ops, reducing the set of values being computed by half each
762   // round.
763   assert(isPowerOf2_32(VF) &&
764          "Reduction emission only supported for pow2 vectors!");
765   Value *TmpVec = Src;
766   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
767   for (unsigned i = VF; i != 1; i >>= 1) {
768     // Move the upper half of the vector to the lower half.
769     for (unsigned j = 0; j != i / 2; ++j)
770       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
771 
772     // Fill the rest of the mask with undef.
773     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
774               UndefValue::get(Builder.getInt32Ty()));
775 
776     Value *Shuf = Builder.CreateShuffleVector(
777         TmpVec, UndefValue::get(TmpVec->getType()),
778         ConstantVector::get(ShuffleMask), "rdx.shuf");
779 
780     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
781       // Floating point operations had to be 'fast' to enable the reduction.
782       TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
783                                                    TmpVec, Shuf, "bin.rdx"));
784     } else {
785       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
786              "Invalid min/max");
787       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
788     }
789     if (!RedOps.empty())
790       propagateIRFlags(TmpVec, RedOps);
791   }
792   // The result is in the first element of the vector.
793   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
794 }
795 
796 /// Create a simple vector reduction specified by an opcode and some
797 /// flags (if generating min/max reductions).
798 Value *llvm::createSimpleTargetReduction(
799     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
800     Value *Src, TargetTransformInfo::ReductionFlags Flags,
801     ArrayRef<Value *> RedOps) {
802   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
803 
804   Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
805   std::function<Value *()> BuildFunc;
806   using RD = RecurrenceDescriptor;
807   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
808   // TODO: Support creating ordered reductions.
809   FastMathFlags FMFFast;
810   FMFFast.setFast();
811 
812   switch (Opcode) {
813   case Instruction::Add:
814     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
815     break;
816   case Instruction::Mul:
817     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
818     break;
819   case Instruction::And:
820     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
821     break;
822   case Instruction::Or:
823     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
824     break;
825   case Instruction::Xor:
826     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
827     break;
828   case Instruction::FAdd:
829     BuildFunc = [&]() {
830       auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
831       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
832       return Rdx;
833     };
834     break;
835   case Instruction::FMul:
836     BuildFunc = [&]() {
837       auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
838       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
839       return Rdx;
840     };
841     break;
842   case Instruction::ICmp:
843     if (Flags.IsMaxOp) {
844       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
845       BuildFunc = [&]() {
846         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
847       };
848     } else {
849       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
850       BuildFunc = [&]() {
851         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
852       };
853     }
854     break;
855   case Instruction::FCmp:
856     if (Flags.IsMaxOp) {
857       MinMaxKind = RD::MRK_FloatMax;
858       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
859     } else {
860       MinMaxKind = RD::MRK_FloatMin;
861       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
862     }
863     break;
864   default:
865     llvm_unreachable("Unhandled opcode");
866     break;
867   }
868   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
869     return BuildFunc();
870   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
871 }
872 
873 /// Create a vector reduction using a given recurrence descriptor.
874 Value *llvm::createTargetReduction(IRBuilder<> &B,
875                                    const TargetTransformInfo *TTI,
876                                    RecurrenceDescriptor &Desc, Value *Src,
877                                    bool NoNaN) {
878   // TODO: Support in-order reductions based on the recurrence descriptor.
879   using RD = RecurrenceDescriptor;
880   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
881   TargetTransformInfo::ReductionFlags Flags;
882   Flags.NoNaN = NoNaN;
883   switch (RecKind) {
884   case RD::RK_FloatAdd:
885     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
886   case RD::RK_FloatMult:
887     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
888   case RD::RK_IntegerAdd:
889     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
890   case RD::RK_IntegerMult:
891     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
892   case RD::RK_IntegerAnd:
893     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
894   case RD::RK_IntegerOr:
895     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
896   case RD::RK_IntegerXor:
897     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
898   case RD::RK_IntegerMinMax: {
899     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
900     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
901     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
902     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
903   }
904   case RD::RK_FloatMinMax: {
905     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
906     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
907   }
908   default:
909     llvm_unreachable("Unhandled RecKind");
910   }
911 }
912 
913 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
914   auto *VecOp = dyn_cast<Instruction>(I);
915   if (!VecOp)
916     return;
917   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
918                                             : dyn_cast<Instruction>(OpValue);
919   if (!Intersection)
920     return;
921   const unsigned Opcode = Intersection->getOpcode();
922   VecOp->copyIRFlags(Intersection);
923   for (auto *V : VL) {
924     auto *Instr = dyn_cast<Instruction>(V);
925     if (!Instr)
926       continue;
927     if (OpValue == nullptr || Opcode == Instr->getOpcode())
928       VecOp->andIRFlags(V);
929   }
930 }
931