LLVM 24.0.0git
LoopDeletion.cpp
Go to the documentation of this file.
1//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
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 implements the Dead Loop Deletion Pass. This pass is responsible
10// for eliminating loops with non-infinite computable trip counts that have no
11// side effects or volatile instructions, and do not contribute to the
12// computation of the function's return value.
13//
14//===----------------------------------------------------------------------===//
15
17#include "ScalarOptions.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/CFG.h"
27#include "llvm/IR/Dominators.h"
28
32
33using namespace llvm;
34
35#define DEBUG_TYPE "loop-delete"
36
37STATISTIC(NumDeleted, "Number of loops deleted");
38STATISTIC(NumBackedgesBroken,
39 "Number of loops for which we managed to break the backedge");
40
46
54
55/// Determines if a loop is dead.
56///
57/// This assumes that we've already checked for unique exit and exiting blocks,
58/// and that the code is in LCSSA form.
59static bool isLoopDead(Loop *L, ScalarEvolution &SE,
60 SmallVectorImpl<BasicBlock *> &ExitingBlocks,
61 BasicBlock *ExitBlock, bool &Changed,
62 BasicBlock *Preheader, LoopInfo &LI) {
63 // Make sure that all PHI entries coming from the loop are loop invariant.
64 // Because the code is in LCSSA form, any values used outside of the loop
65 // must pass through a PHI in the exit block, meaning that this check is
66 // sufficient to guarantee that no loop-variant values are used outside
67 // of the loop.
68 bool AllEntriesInvariant = true;
69 bool AllOutgoingValuesSame = true;
70 if (ExitBlock) {
71 for (PHINode &P : ExitBlock->phis()) {
72 Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]);
73
74 // Make sure all exiting blocks produce the same incoming value for the
75 // block. If there are different incoming values for different exiting
76 // blocks, then it is impossible to statically determine which value
77 // should be used.
78 AllOutgoingValuesSame =
79 all_of(ArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
80 return incoming == P.getIncomingValueForBlock(BB);
81 });
82
83 if (!AllOutgoingValuesSame)
84 break;
85
86 if (Instruction *I = dyn_cast<Instruction>(incoming)) {
87 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator(),
88 /*MSSAU=*/nullptr, &SE)) {
89 AllEntriesInvariant = false;
90 break;
91 }
92 }
93 }
94 }
95
96 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
97 return false;
98
99 // Make sure that no instructions in the block have potential side-effects.
100 // This includes instructions that could write to memory, and loads that are
101 // marked volatile.
102 for (const auto &I : L->blocks())
103 if (any_of(*I, [](Instruction &I) {
104 return I.mayHaveSideEffects() && !I.isDroppable();
105 }))
106 return false;
107
108 // The loop or any of its sub-loops looping infinitely is legal. The loop can
109 // only be considered dead if either
110 // a. the function is mustprogress.
111 // b. all (sub-)loops are mustprogress or have a known trip-count.
112 if (L->getHeader()->getParent()->mustProgress())
113 return true;
114
115 LoopBlocksRPO RPOT(L);
116 RPOT.perform(&LI);
117 // If the loop contains an irreducible cycle, it may loop infinitely.
119 return false;
120
121 SmallVector<Loop *, 8> WorkList;
122 WorkList.push_back(L);
123 while (!WorkList.empty()) {
124 Loop *Current = WorkList.pop_back_val();
125 if (hasMustProgress(Current))
126 continue;
127
128 const SCEV *S = SE.getConstantMaxBackedgeTakenCount(Current);
131 dbgs() << "Could not compute SCEV MaxBackedgeTakenCount and was "
132 "not required to make progress.\n");
133 return false;
134 }
135 WorkList.append(Current->begin(), Current->end());
136 }
137 return true;
138}
139
140/// This function returns true if there is no viable path from the
141/// entry block to the header of \p L. Right now, it only does
142/// a local search to save compile time.
143static bool isLoopNeverExecuted(Loop *L) {
144 using namespace PatternMatch;
145
146 auto *Preheader = L->getLoopPreheader();
147 // TODO: We can relax this constraint, since we just need a loop
148 // predecessor.
149 assert(Preheader && "Needs preheader!");
150
151 if (Preheader->isEntryBlock())
152 return false;
153 // All predecessors of the preheader should have a constant conditional
154 // branch, with the loop's preheader as not-taken.
155 for (auto *Pred: predecessors(Preheader)) {
156 BasicBlock *Taken, *NotTaken;
158 if (!match(Pred->getTerminator(),
159 m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
160 return false;
161 if (!Cond->getZExtValue())
162 std::swap(Taken, NotTaken);
163 if (Taken == Preheader)
164 return false;
165 }
166 assert(!pred_empty(Preheader) &&
167 "Preheader should have predecessors at this point!");
168 // All the predecessors have the loop preheader as not-taken target.
169 return true;
170}
171
172static Value *
174 const SimplifyQuery &SQ) {
175 // Quick hack: do not flood cache with non-instruction values.
176 if (!isa<Instruction>(V))
177 return V;
178 // Do we already know cached result?
179 auto Existing = FirstIterValue.find(V);
180 if (Existing != FirstIterValue.end())
181 return Existing->second;
182 Value *FirstIterV = nullptr;
183 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
184 Value *LHS =
185 getValueOnFirstIteration(BO->getOperand(0), FirstIterValue, SQ);
186 Value *RHS =
187 getValueOnFirstIteration(BO->getOperand(1), FirstIterValue, SQ);
188 FirstIterV = simplifyBinOp(BO->getOpcode(), LHS, RHS, SQ);
189 } else if (auto *Cmp = dyn_cast<ICmpInst>(V)) {
190 Value *LHS =
191 getValueOnFirstIteration(Cmp->getOperand(0), FirstIterValue, SQ);
192 Value *RHS =
193 getValueOnFirstIteration(Cmp->getOperand(1), FirstIterValue, SQ);
194 FirstIterV = simplifyICmpInst(Cmp->getPredicate(), LHS, RHS, SQ);
195 } else if (auto *Select = dyn_cast<SelectInst>(V)) {
196 Value *Cond =
197 getValueOnFirstIteration(Select->getCondition(), FirstIterValue, SQ);
198 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
199 auto *Selected = C->isAllOnesValue() ? Select->getTrueValue()
200 : Select->getFalseValue();
201 FirstIterV = getValueOnFirstIteration(Selected, FirstIterValue, SQ);
202 }
203 }
204 if (!FirstIterV)
205 FirstIterV = V;
206 FirstIterValue[V] = FirstIterV;
207 return FirstIterV;
208}
209
210// Try to prove that one of conditions that dominates the latch must exit on 1st
211// iteration.
213 LoopInfo &LI) {
214 // Disabled by option.
215 if (!ScalarOptions::Global.loop_deletion_enable_symbolic_execution)
216 return false;
217
218 BasicBlock *Predecessor = L->getLoopPredecessor();
219 BasicBlock *Latch = L->getLoopLatch();
220
221 if (!Predecessor || !Latch)
222 return false;
223
224 LoopBlocksRPO RPOT(L);
225 RPOT.perform(&LI);
226
227 // For the optimization to be correct, we need RPOT to have a property that
228 // each block is processed after all its predecessors, which may only be
229 // violated for headers of the current loop and all nested loops. Irreducible
230 // CFG provides multiple ways to break this assumption, so we do not want to
231 // deal with it.
233 return false;
234
235 BasicBlock *Header = L->getHeader();
236 // Blocks that are reachable on the 1st iteration.
238 // Edges that are reachable on the 1st iteration.
239 DenseSet<BasicBlockEdge> LiveEdges;
240 LiveBlocks.insert(Header);
241
243 auto MarkLiveEdge = [&](BasicBlock *From, BasicBlock *To) {
244 assert(LiveBlocks.count(From) && "Must be live!");
245 assert((LI.isLoopHeader(To) || !Visited.count(To)) &&
246 "Only canonical backedges are allowed. Irreducible CFG?");
247 assert((LiveBlocks.count(To) || !Visited.count(To)) &&
248 "We already discarded this block as dead!");
249 LiveBlocks.insert(To);
250 LiveEdges.insert({ From, To });
251 };
252
253 auto MarkAllSuccessorsLive = [&](BasicBlock *BB) {
254 for (auto *Succ : successors(BB))
255 MarkLiveEdge(BB, Succ);
256 };
257
258 // Check if there is only one value coming from all live predecessor blocks.
259 // Note that because we iterate in RPOT, we have already visited all its
260 // (non-latch) predecessors.
261 auto GetSoleInputOnFirstIteration = [&](PHINode & PN)->Value * {
262 BasicBlock *BB = PN.getParent();
263 bool HasLivePreds = false;
264 (void)HasLivePreds;
265 if (BB == Header)
266 return PN.getIncomingValueForBlock(Predecessor);
267 Value *OnlyInput = nullptr;
268 for (auto *Pred : predecessors(BB))
269 if (LiveEdges.count({ Pred, BB })) {
270 HasLivePreds = true;
271 Value *Incoming = PN.getIncomingValueForBlock(Pred);
272 // Skip poison. If they are present, we can assume they are equal to
273 // the non-poison input.
274 if (isa<PoisonValue>(Incoming))
275 continue;
276 // Two inputs.
277 if (OnlyInput && OnlyInput != Incoming)
278 return nullptr;
279 OnlyInput = Incoming;
280 }
281
282 assert(HasLivePreds && "No live predecessors?");
283 // If all incoming live value were poison, return poison.
284 return OnlyInput ? OnlyInput : PoisonValue::get(PN.getType());
285 };
286 DenseMap<Value *, Value *> FirstIterValue;
287
288 // Use the following algorithm to prove we never take the latch on the 1st
289 // iteration:
290 // 1. Traverse in topological order, so that whenever we visit a block, all
291 // its predecessors are already visited.
292 // 2. If we can prove that the block may have only 1 predecessor on the 1st
293 // iteration, map all its phis onto input from this predecessor.
294 // 3a. If we can prove which successor of out block is taken on the 1st
295 // iteration, mark this successor live.
296 // 3b. If we cannot prove it, conservatively assume that all successors are
297 // live.
298 auto &DL = Header->getDataLayout();
299 const SimplifyQuery SQ(DL);
300 for (auto *BB : RPOT) {
301 Visited.insert(BB);
302
303 // This block is not reachable on the 1st iterations.
304 if (!LiveBlocks.count(BB))
305 continue;
306
307 // Skip inner loops.
308 if (LI.getLoopFor(BB) != L) {
309 MarkAllSuccessorsLive(BB);
310 continue;
311 }
312
313 // If Phi has only one input from all live input blocks, use it.
314 for (auto &PN : BB->phis()) {
315 if (!PN.getType()->isIntegerTy())
316 continue;
317 auto *Incoming = GetSoleInputOnFirstIteration(PN);
318 if (Incoming && DT.dominates(Incoming, BB->getTerminator())) {
319 Value *FirstIterV =
320 getValueOnFirstIteration(Incoming, FirstIterValue, SQ);
321 FirstIterValue[&PN] = FirstIterV;
322 }
323 }
324
325 using namespace PatternMatch;
326 Value *Cond;
327 BasicBlock *IfTrue, *IfFalse;
328 auto *Term = BB->getTerminator();
329 if (match(Term, m_Br(m_Value(Cond),
330 m_BasicBlock(IfTrue), m_BasicBlock(IfFalse)))) {
331 auto *ICmp = dyn_cast<ICmpInst>(Cond);
332 if (!ICmp || !ICmp->getType()->isIntegerTy()) {
333 MarkAllSuccessorsLive(BB);
334 continue;
335 }
336
337 // Can we prove constant true or false for this condition?
338 auto *KnownCondition = getValueOnFirstIteration(ICmp, FirstIterValue, SQ);
339 if (KnownCondition == ICmp) {
340 // Failed to simplify.
341 MarkAllSuccessorsLive(BB);
342 continue;
343 }
344 if (isa<UndefValue>(KnownCondition)) {
345 // TODO: According to langref, branching by undef is undefined behavior.
346 // It means that, theoretically, we should be able to just continue
347 // without marking any successors as live. However, we are not certain
348 // how correct our compiler is at handling such cases. So we are being
349 // very conservative here.
350 //
351 // If there is a non-loop successor, always assume this branch leaves the
352 // loop. Otherwise, arbitrarily take IfTrue.
353 //
354 // Once we are certain that branching by undef is handled correctly by
355 // other transforms, we should not mark any successors live here.
356 if (L->contains(IfTrue) && L->contains(IfFalse))
357 MarkLiveEdge(BB, IfTrue);
358 continue;
359 }
360 auto *ConstCondition = dyn_cast<ConstantInt>(KnownCondition);
361 if (!ConstCondition) {
362 // Non-constant condition, cannot analyze any further.
363 MarkAllSuccessorsLive(BB);
364 continue;
365 }
366 if (ConstCondition->isAllOnesValue())
367 MarkLiveEdge(BB, IfTrue);
368 else
369 MarkLiveEdge(BB, IfFalse);
370 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
371 auto *SwitchValue = SI->getCondition();
372 auto *SwitchValueOnFirstIter =
373 getValueOnFirstIteration(SwitchValue, FirstIterValue, SQ);
374 auto *ConstSwitchValue = dyn_cast<ConstantInt>(SwitchValueOnFirstIter);
375 if (!ConstSwitchValue) {
376 MarkAllSuccessorsLive(BB);
377 continue;
378 }
379 auto CaseIterator = SI->findCaseValue(ConstSwitchValue);
380 MarkLiveEdge(BB, CaseIterator->getCaseSuccessor());
381 } else {
382 MarkAllSuccessorsLive(BB);
383 continue;
384 }
385 }
386
387 // We can break the latch if it wasn't live.
388 return !LiveEdges.count({ Latch, Header });
389}
390
391/// If we can prove the backedge is untaken, remove it. This destroys the
392/// loop, but leaves the (now trivially loop invariant) control flow and
393/// side effects (if any) in place.
396 LoopInfo &LI, MemorySSA *MSSA,
398 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
399
400 if (!L->getLoopLatch())
402
403 const SCEV *BTCMax = SE.getConstantMaxBackedgeTakenCount(L);
404 if (!BTCMax->isZero()) {
405 const SCEV *BTC = SE.getBackedgeTakenCount(L);
406 if (!BTC->isZero()) {
407 if (!isa<SCEVCouldNotCompute>(BTC) && SE.isKnownNonZero(BTC))
409 if (!canProveExitOnFirstIteration(L, DT, LI))
411 }
412 }
413 ++NumBackedgesBroken;
414 breakLoopBackedge(L, DT, SE, LI, MSSA);
416}
417
418/// Remove a loop if it is dead.
419///
420/// A loop is considered dead either if it does not impact the observable
421/// behavior of the program other than finite running time, or if it is
422/// required to make progress by an attribute such as 'mustprogress' or
423/// 'llvm.loop.mustprogress' and does not make any. This may remove
424/// infinite loops that have been required to make progress.
425///
426/// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
427/// order to make various safety checks work.
428///
429/// \returns true if any changes were made. This may mutate the loop even if it
430/// is unable to delete it due to hoisting trivially loop invariant
431/// instructions out of the loop.
433 ScalarEvolution &SE, LoopInfo &LI,
434 MemorySSA *MSSA,
436 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
437
438 // We can only remove the loop if there is a preheader that we can branch from
439 // after removing it. Also, if LoopSimplify form is not available, stay out
440 // of trouble.
441 BasicBlock *Preheader = L->getLoopPreheader();
442 if (!Preheader || !L->hasDedicatedExits()) {
444 dbgs()
445 << "Deletion requires Loop with preheader and dedicated exits.\n");
447 }
448
449 BasicBlock *ExitBlock = L->getUniqueExitBlock();
450
451 // We can't directly branch to an EH pad. Don't bother handling this edge
452 // case.
453 if (ExitBlock && ExitBlock->isEHPad()) {
454 LLVM_DEBUG(dbgs() << "Cannot delete loop exiting to EH pad.\n");
456 }
457
458 if (ExitBlock && isLoopNeverExecuted(L)) {
459 LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!\n");
460 // We need to forget the loop before setting the incoming values of the exit
461 // phis to poison, so we properly invalidate the SCEV expressions for those
462 // phis.
463 SE.forgetLoop(L);
464 // Set incoming value to poison for phi nodes in the exit block.
465 for (PHINode &P : ExitBlock->phis()) {
466 llvm::fill(P.incoming_values(), PoisonValue::get(P.getType()));
467 }
468 ORE.emit([&]() {
469 return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(),
470 L->getHeader())
471 << "Loop deleted because it never executes";
472 });
473 deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
474 ++NumDeleted;
476 }
477
478 // The remaining checks below are for a loop being dead because all statements
479 // in the loop are invariant.
480 SmallVector<BasicBlock *, 4> ExitingBlocks;
481 L->getExitingBlocks(ExitingBlocks);
482
483 // We require that the loop has at most one exit block. Otherwise, we'd be in
484 // the situation of needing to be able to solve statically which exit block
485 // will be branched to, or trying to preserve the branching logic in a loop
486 // invariant manner.
487 if (!ExitBlock && !LI.hasNoExitBlocks(*L)) {
488 LLVM_DEBUG(dbgs() << "Deletion requires at most one exit block.\n");
490 }
491
492 // Finally, we have to check that the loop really is dead.
493 bool Changed = false;
494 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader, LI)) {
495 LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
498 }
499
500 LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!\n");
501 ORE.emit([&]() {
502 return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(),
503 L->getHeader())
504 << "Loop deleted because it is invariant";
505 });
506 deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
507 ++NumDeleted;
508
510}
511
514 LPMUpdater &Updater) {
515
516 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
517 LLVM_DEBUG(L.dump());
518 std::string LoopName = std::string(L.getName());
519 // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
520 // pass. Function analyses need to be preserved across loop transformations
521 // but ORE cannot be preserved (see comment before the pass definition).
522 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
523 auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE);
524
525 // If we can prove the backedge isn't taken, just break it and be done. This
526 // leaves the loop structure in place which means it can handle dispatching
527 // to the right exit based on whatever loop invariant structure remains.
528 if (Result != LoopDeletionResult::Deleted)
529 Result = merge(Result, breakBackedgeIfNotTaken(&L, AR.DT, AR.SE, AR.LI,
530 AR.MSSA, ORE));
531
532 if (Result == LoopDeletionResult::Unmodified)
533 return PreservedAnalyses::all();
534
535 if (Result == LoopDeletionResult::Deleted)
536 Updater.markLoopAsDeleted(L, LoopName);
537
539 if (AR.MSSA)
540 PA.preserve<MemorySSAAnalysis>();
541 return PA;
542}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
LoopDeletionResult
static LoopDeletionResult breakBackedgeIfNotTaken(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA, OptimizationRemarkEmitter &ORE)
If we can prove the backedge is untaken, remove it.
static Value * getValueOnFirstIteration(Value *V, DenseMap< Value *, Value * > &FirstIterValue, const SimplifyQuery &SQ)
static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA, OptimizationRemarkEmitter &ORE)
Remove a loop if it is dead.
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
static bool isLoopNeverExecuted(Loop *L)
This function returns true if there is no viable path from the entry block to the header of L.
static bool canProveExitOnFirstIteration(Loop *L, DominatorTree &DT, LoopInfo &LI)
static bool isLoopDead(Loop *L, ScalarEvolution &SE, SmallVectorImpl< BasicBlock * > &ExitingBlocks, BasicBlock *ExitBlock, bool &Changed, BasicBlock *Preheader, LoopInfo &LI)
Determines if a loop is dead.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:689
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This is the shared class of boolean and integer constants.
Definition Constants.h:87
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
iterator end() const
iterator begin() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
bool hasNoExitBlocks(const LoopT &L) const
Return true if L does not have any exit blocks.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Multiway switch.
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
Changed
bool match(Val *V, const Pattern &P)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
Definition CFG.h:154
LLVM_ABI void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI, MemorySSA *MSSA=nullptr)
This function deletes dead loops.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
@ Unmodified
The loop was not modified.
Definition UnrollLoop.h:60
LLVM_ABI void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...