blob: 98b31295ada082ff7525c7e02b1e48c0f922a3a9 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the LoopInfo class that is used to identify natural loops
10// and determine the loop depth of various nodes of the CFG. A natural loop
11// has exactly one entry-point, which is called the header. Note that natural
12// loops may actually be several loops that share the same header node.
13//
14// This analysis calculates the nesting structure of loops in a function. For
15// each natural loop identified, this analysis identifies natural loops
16// contained entirely within the loop and the basic blocks the make up the loop.
17//
18// It can calculate on the fly various bits of information, for example:
19//
20// * whether there is a preheader for the loop
21// * the number of back edges to the header
22// * whether or not a particular block branches out of the loop
23// * the successor blocks of the loop
24// * the loop depth
25// * etc...
26//
27// Note that this analysis specifically identifies *Loops* not cycles or SCCs
28// in the CFG. There can be strongly connected components in the CFG which
29// this analysis will not recognize and that will not be represented by a Loop
30// instance. In particular, a Loop might be inside such a non-loop SCC, or a
31// non-loop SCC might contain a sub-SCC which is a Loop.
32//
33//===----------------------------------------------------------------------===//
34
35#ifndef LLVM_ANALYSIS_LOOPINFO_H
36#define LLVM_ANALYSIS_LOOPINFO_H
37
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/GraphTraits.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/IR/CFG.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/PassManager.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/Allocator.h"
49#include <algorithm>
50#include <utility>
51
52namespace llvm {
53
54class DominatorTree;
55class LoopInfo;
56class Loop;
Andrew Walbran3d2c1972020-04-07 12:24:26 +010057class InductionDescriptor;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010058class MDNode;
Andrew Walbran3d2c1972020-04-07 12:24:26 +010059class MemorySSAUpdater;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010060class PHINode;
Andrew Walbran3d2c1972020-04-07 12:24:26 +010061class ScalarEvolution;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010062class raw_ostream;
63template <class N, bool IsPostDom> class DominatorTreeBase;
64template <class N, class M> class LoopInfoBase;
65template <class N, class M> class LoopBase;
66
67//===----------------------------------------------------------------------===//
68/// Instances of this class are used to represent loops that are detected in the
69/// flow graph.
70///
71template <class BlockT, class LoopT> class LoopBase {
72 LoopT *ParentLoop;
73 // Loops contained entirely within this one.
74 std::vector<LoopT *> SubLoops;
75
76 // The list of blocks in this loop. First entry is the header node.
77 std::vector<BlockT *> Blocks;
78
79 SmallPtrSet<const BlockT *, 8> DenseBlockSet;
80
81#if LLVM_ENABLE_ABI_BREAKING_CHECKS
82 /// Indicator that this loop is no longer a valid loop.
83 bool IsInvalid = false;
84#endif
85
86 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
87 const LoopBase<BlockT, LoopT> &
88 operator=(const LoopBase<BlockT, LoopT> &) = delete;
89
90public:
91 /// Return the nesting level of this loop. An outer-most loop has depth 1,
92 /// for consistency with loop depth values used for basic blocks, where depth
93 /// 0 is used for blocks not inside any loops.
94 unsigned getLoopDepth() const {
95 assert(!isInvalid() && "Loop not in a valid state!");
96 unsigned D = 1;
97 for (const LoopT *CurLoop = ParentLoop; CurLoop;
98 CurLoop = CurLoop->ParentLoop)
99 ++D;
100 return D;
101 }
102 BlockT *getHeader() const { return getBlocks().front(); }
103 LoopT *getParentLoop() const { return ParentLoop; }
104
105 /// This is a raw interface for bypassing addChildLoop.
106 void setParentLoop(LoopT *L) {
107 assert(!isInvalid() && "Loop not in a valid state!");
108 ParentLoop = L;
109 }
110
111 /// Return true if the specified loop is contained within in this loop.
112 bool contains(const LoopT *L) const {
113 assert(!isInvalid() && "Loop not in a valid state!");
114 if (L == this)
115 return true;
116 if (!L)
117 return false;
118 return contains(L->getParentLoop());
119 }
120
121 /// Return true if the specified basic block is in this loop.
122 bool contains(const BlockT *BB) const {
123 assert(!isInvalid() && "Loop not in a valid state!");
124 return DenseBlockSet.count(BB);
125 }
126
127 /// Return true if the specified instruction is in this loop.
128 template <class InstT> bool contains(const InstT *Inst) const {
129 return contains(Inst->getParent());
130 }
131
132 /// Return the loops contained entirely within this loop.
133 const std::vector<LoopT *> &getSubLoops() const {
134 assert(!isInvalid() && "Loop not in a valid state!");
135 return SubLoops;
136 }
137 std::vector<LoopT *> &getSubLoopsVector() {
138 assert(!isInvalid() && "Loop not in a valid state!");
139 return SubLoops;
140 }
141 typedef typename std::vector<LoopT *>::const_iterator iterator;
142 typedef
143 typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
144 iterator begin() const { return getSubLoops().begin(); }
145 iterator end() const { return getSubLoops().end(); }
146 reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
147 reverse_iterator rend() const { return getSubLoops().rend(); }
148 bool empty() const { return getSubLoops().empty(); }
149
150 /// Get a list of the basic blocks which make up this loop.
151 ArrayRef<BlockT *> getBlocks() const {
152 assert(!isInvalid() && "Loop not in a valid state!");
153 return Blocks;
154 }
155 typedef typename ArrayRef<BlockT *>::const_iterator block_iterator;
156 block_iterator block_begin() const { return getBlocks().begin(); }
157 block_iterator block_end() const { return getBlocks().end(); }
158 inline iterator_range<block_iterator> blocks() const {
159 assert(!isInvalid() && "Loop not in a valid state!");
160 return make_range(block_begin(), block_end());
161 }
162
163 /// Get the number of blocks in this loop in constant time.
164 /// Invalidate the loop, indicating that it is no longer a loop.
165 unsigned getNumBlocks() const {
166 assert(!isInvalid() && "Loop not in a valid state!");
167 return Blocks.size();
168 }
169
170 /// Return a direct, mutable handle to the blocks vector so that we can
171 /// mutate it efficiently with techniques like `std::remove`.
172 std::vector<BlockT *> &getBlocksVector() {
173 assert(!isInvalid() && "Loop not in a valid state!");
174 return Blocks;
175 }
176 /// Return a direct, mutable handle to the blocks set so that we can
177 /// mutate it efficiently.
178 SmallPtrSetImpl<const BlockT *> &getBlocksSet() {
179 assert(!isInvalid() && "Loop not in a valid state!");
180 return DenseBlockSet;
181 }
182
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100183 /// Return a direct, immutable handle to the blocks set.
184 const SmallPtrSetImpl<const BlockT *> &getBlocksSet() const {
185 assert(!isInvalid() && "Loop not in a valid state!");
186 return DenseBlockSet;
187 }
188
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100189 /// Return true if this loop is no longer valid. The only valid use of this
190 /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
191 /// true by the destructor. In other words, if this accessor returns true,
192 /// the caller has already triggered UB by calling this accessor; and so it
193 /// can only be called in a context where a return value of true indicates a
194 /// programmer error.
195 bool isInvalid() const {
196#if LLVM_ENABLE_ABI_BREAKING_CHECKS
197 return IsInvalid;
198#else
199 return false;
200#endif
201 }
202
203 /// True if terminator in the block can branch to another block that is
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100204 /// outside of the current loop. \p BB must be inside the loop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100205 bool isLoopExiting(const BlockT *BB) const {
206 assert(!isInvalid() && "Loop not in a valid state!");
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100207 assert(contains(BB) && "Exiting block must be part of the loop");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100208 for (const auto &Succ : children<const BlockT *>(BB)) {
209 if (!contains(Succ))
210 return true;
211 }
212 return false;
213 }
214
215 /// Returns true if \p BB is a loop-latch.
216 /// A latch block is a block that contains a branch back to the header.
217 /// This function is useful when there are multiple latches in a loop
218 /// because \fn getLoopLatch will return nullptr in that case.
219 bool isLoopLatch(const BlockT *BB) const {
220 assert(!isInvalid() && "Loop not in a valid state!");
221 assert(contains(BB) && "block does not belong to the loop");
222
223 BlockT *Header = getHeader();
224 auto PredBegin = GraphTraits<Inverse<BlockT *>>::child_begin(Header);
225 auto PredEnd = GraphTraits<Inverse<BlockT *>>::child_end(Header);
226 return std::find(PredBegin, PredEnd, BB) != PredEnd;
227 }
228
229 /// Calculate the number of back edges to the loop header.
230 unsigned getNumBackEdges() const {
231 assert(!isInvalid() && "Loop not in a valid state!");
232 unsigned NumBackEdges = 0;
233 BlockT *H = getHeader();
234
235 for (const auto Pred : children<Inverse<BlockT *>>(H))
236 if (contains(Pred))
237 ++NumBackEdges;
238
239 return NumBackEdges;
240 }
241
242 //===--------------------------------------------------------------------===//
243 // APIs for simple analysis of the loop.
244 //
245 // Note that all of these methods can fail on general loops (ie, there may not
246 // be a preheader, etc). For best success, the loop simplification and
247 // induction variable canonicalization pass should be used to normalize loops
248 // for easy analysis. These methods assume canonical loops.
249
250 /// Return all blocks inside the loop that have successors outside of the
251 /// loop. These are the blocks _inside of the current loop_ which branch out.
252 /// The returned list is always unique.
253 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
254
255 /// If getExitingBlocks would return exactly one block, return that block.
256 /// Otherwise return null.
257 BlockT *getExitingBlock() const;
258
259 /// Return all of the successor blocks of this loop. These are the blocks
260 /// _outside of the current loop_ which are branched to.
261 void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
262
263 /// If getExitBlocks would return exactly one block, return that block.
264 /// Otherwise return null.
265 BlockT *getExitBlock() const;
266
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100267 /// Return true if no exit block for the loop has a predecessor that is
268 /// outside the loop.
269 bool hasDedicatedExits() const;
270
271 /// Return all unique successor blocks of this loop.
272 /// These are the blocks _outside of the current loop_ which are branched to.
273 /// This assumes that loop exits are in canonical form, i.e. all exits are
274 /// dedicated exits.
275 void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
276
277 /// If getUniqueExitBlocks would return exactly one block, return that block.
278 /// Otherwise return null.
279 BlockT *getUniqueExitBlock() const;
280
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100281 /// Edge type.
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100282 typedef std::pair<BlockT *, BlockT *> Edge;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100283
284 /// Return all pairs of (_inside_block_,_outside_block_).
285 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
286
287 /// If there is a preheader for this loop, return it. A loop has a preheader
288 /// if there is only one edge to the header of the loop from outside of the
289 /// loop. If this is the case, the block branching to the header of the loop
290 /// is the preheader node.
291 ///
292 /// This method returns null if there is no preheader for the loop.
293 BlockT *getLoopPreheader() const;
294
295 /// If the given loop's header has exactly one unique predecessor outside the
296 /// loop, return it. Otherwise return null.
297 /// This is less strict that the loop "preheader" concept, which requires
298 /// the predecessor to have exactly one successor.
299 BlockT *getLoopPredecessor() const;
300
301 /// If there is a single latch block for this loop, return it.
302 /// A latch block is a block that contains a branch back to the header.
303 BlockT *getLoopLatch() const;
304
305 /// Return all loop latch blocks of this loop. A latch block is a block that
306 /// contains a branch back to the header.
307 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
308 assert(!isInvalid() && "Loop not in a valid state!");
309 BlockT *H = getHeader();
310 for (const auto Pred : children<Inverse<BlockT *>>(H))
311 if (contains(Pred))
312 LoopLatches.push_back(Pred);
313 }
314
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100315 /// Return all inner loops in the loop nest rooted by the loop in preorder,
316 /// with siblings in forward program order.
317 template <class Type>
318 static void getInnerLoopsInPreorder(const LoopT &L,
319 SmallVectorImpl<Type> &PreOrderLoops) {
320 SmallVector<LoopT *, 4> PreOrderWorklist;
321 PreOrderWorklist.append(L.rbegin(), L.rend());
322
323 while (!PreOrderWorklist.empty()) {
324 LoopT *L = PreOrderWorklist.pop_back_val();
325 // Sub-loops are stored in forward program order, but will process the
326 // worklist backwards so append them in reverse order.
327 PreOrderWorklist.append(L->rbegin(), L->rend());
328 PreOrderLoops.push_back(L);
329 }
330 }
331
332 /// Return all loops in the loop nest rooted by the loop in preorder, with
333 /// siblings in forward program order.
334 SmallVector<const LoopT *, 4> getLoopsInPreorder() const {
335 SmallVector<const LoopT *, 4> PreOrderLoops;
336 const LoopT *CurLoop = static_cast<const LoopT *>(this);
337 PreOrderLoops.push_back(CurLoop);
338 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
339 return PreOrderLoops;
340 }
341 SmallVector<LoopT *, 4> getLoopsInPreorder() {
342 SmallVector<LoopT *, 4> PreOrderLoops;
343 LoopT *CurLoop = static_cast<LoopT *>(this);
344 PreOrderLoops.push_back(CurLoop);
345 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
346 return PreOrderLoops;
347 }
348
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100349 //===--------------------------------------------------------------------===//
350 // APIs for updating loop information after changing the CFG
351 //
352
353 /// This method is used by other analyses to update loop information.
354 /// NewBB is set to be a new member of the current loop.
355 /// Because of this, it is added as a member of all parent loops, and is added
356 /// to the specified LoopInfo object as being in the current basic block. It
357 /// is not valid to replace the loop header with this method.
358 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
359
360 /// This is used when splitting loops up. It replaces the OldChild entry in
361 /// our children list with NewChild, and updates the parent pointer of
362 /// OldChild to be null and the NewChild to be this loop.
363 /// This updates the loop depth of the new child.
364 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
365
366 /// Add the specified loop to be a child of this loop.
367 /// This updates the loop depth of the new child.
368 void addChildLoop(LoopT *NewChild) {
369 assert(!isInvalid() && "Loop not in a valid state!");
370 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
371 NewChild->ParentLoop = static_cast<LoopT *>(this);
372 SubLoops.push_back(NewChild);
373 }
374
375 /// This removes the specified child from being a subloop of this loop. The
376 /// loop is not deleted, as it will presumably be inserted into another loop.
377 LoopT *removeChildLoop(iterator I) {
378 assert(!isInvalid() && "Loop not in a valid state!");
379 assert(I != SubLoops.end() && "Cannot remove end iterator!");
380 LoopT *Child = *I;
381 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
382 SubLoops.erase(SubLoops.begin() + (I - begin()));
383 Child->ParentLoop = nullptr;
384 return Child;
385 }
386
387 /// This removes the specified child from being a subloop of this loop. The
388 /// loop is not deleted, as it will presumably be inserted into another loop.
389 LoopT *removeChildLoop(LoopT *Child) {
390 return removeChildLoop(llvm::find(*this, Child));
391 }
392
393 /// This adds a basic block directly to the basic block list.
394 /// This should only be used by transformations that create new loops. Other
395 /// transformations should use addBasicBlockToLoop.
396 void addBlockEntry(BlockT *BB) {
397 assert(!isInvalid() && "Loop not in a valid state!");
398 Blocks.push_back(BB);
399 DenseBlockSet.insert(BB);
400 }
401
402 /// interface to reverse Blocks[from, end of loop] in this loop
403 void reverseBlock(unsigned from) {
404 assert(!isInvalid() && "Loop not in a valid state!");
405 std::reverse(Blocks.begin() + from, Blocks.end());
406 }
407
408 /// interface to do reserve() for Blocks
409 void reserveBlocks(unsigned size) {
410 assert(!isInvalid() && "Loop not in a valid state!");
411 Blocks.reserve(size);
412 }
413
414 /// This method is used to move BB (which must be part of this loop) to be the
415 /// loop header of the loop (the block that dominates all others).
416 void moveToHeader(BlockT *BB) {
417 assert(!isInvalid() && "Loop not in a valid state!");
418 if (Blocks[0] == BB)
419 return;
420 for (unsigned i = 0;; ++i) {
421 assert(i != Blocks.size() && "Loop does not contain BB!");
422 if (Blocks[i] == BB) {
423 Blocks[i] = Blocks[0];
424 Blocks[0] = BB;
425 return;
426 }
427 }
428 }
429
430 /// This removes the specified basic block from the current loop, updating the
431 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
432 /// class.
433 void removeBlockFromLoop(BlockT *BB) {
434 assert(!isInvalid() && "Loop not in a valid state!");
435 auto I = find(Blocks, BB);
436 assert(I != Blocks.end() && "N is not in this list!");
437 Blocks.erase(I);
438
439 DenseBlockSet.erase(BB);
440 }
441
442 /// Verify loop structure
443 void verifyLoop() const;
444
445 /// Verify loop structure of this loop and all nested loops.
446 void verifyLoopNest(DenseSet<const LoopT *> *Loops) const;
447
Andrew Walbran16937d02019-10-22 13:54:20 +0100448 /// Returns true if the loop is annotated parallel.
449 ///
450 /// Derived classes can override this method using static template
451 /// polymorphism.
452 bool isAnnotatedParallel() const { return false; }
453
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100454 /// Print loop with all the BBs inside it.
455 void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
456
457protected:
458 friend class LoopInfoBase<BlockT, LoopT>;
459
460 /// This creates an empty loop.
461 LoopBase() : ParentLoop(nullptr) {}
462
463 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
464 Blocks.push_back(BB);
465 DenseBlockSet.insert(BB);
466 }
467
468 // Since loop passes like SCEV are allowed to key analysis results off of
469 // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
470 // This means loop passes should not be `delete` ing `Loop` objects directly
471 // (and risk a later `Loop` allocation re-using the address of a previous one)
472 // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
473 // pointer till the end of the lifetime of the `LoopInfo` object.
474 //
475 // To make it easier to follow this rule, we mark the destructor as
476 // non-public.
477 ~LoopBase() {
478 for (auto *SubLoop : SubLoops)
479 SubLoop->~LoopT();
480
481#if LLVM_ENABLE_ABI_BREAKING_CHECKS
482 IsInvalid = true;
483#endif
484 SubLoops.clear();
485 Blocks.clear();
486 DenseBlockSet.clear();
487 ParentLoop = nullptr;
488 }
489};
490
491template <class BlockT, class LoopT>
492raw_ostream &operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
493 Loop.print(OS);
494 return OS;
495}
496
497// Implementation in LoopInfoImpl.h
498extern template class LoopBase<BasicBlock, Loop>;
499
500/// Represents a single loop in the control flow graph. Note that not all SCCs
501/// in the CFG are necessarily loops.
502class Loop : public LoopBase<BasicBlock, Loop> {
503public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100504 /// A range representing the start and end location of a loop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100505 class LocRange {
506 DebugLoc Start;
507 DebugLoc End;
508
509 public:
510 LocRange() {}
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100511 LocRange(DebugLoc Start) : Start(Start), End(Start) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100512 LocRange(DebugLoc Start, DebugLoc End)
513 : Start(std::move(Start)), End(std::move(End)) {}
514
515 const DebugLoc &getStart() const { return Start; }
516 const DebugLoc &getEnd() const { return End; }
517
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100518 /// Check for null.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100519 ///
520 explicit operator bool() const { return Start && End; }
521 };
522
523 /// Return true if the specified value is loop invariant.
524 bool isLoopInvariant(const Value *V) const;
525
526 /// Return true if all the operands of the specified instruction are loop
527 /// invariant.
528 bool hasLoopInvariantOperands(const Instruction *I) const;
529
530 /// If the given value is an instruction inside of the loop and it can be
531 /// hoisted, do so to make it trivially loop-invariant.
532 /// Return true if the value after any hoisting is loop invariant. This
533 /// function can be used as a slightly more aggressive replacement for
534 /// isLoopInvariant.
535 ///
536 /// If InsertPt is specified, it is the point to hoist instructions to.
537 /// If null, the terminator of the loop preheader is used.
538 bool makeLoopInvariant(Value *V, bool &Changed,
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100539 Instruction *InsertPt = nullptr,
540 MemorySSAUpdater *MSSAU = nullptr) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100541
542 /// If the given instruction is inside of the loop and it can be hoisted, do
543 /// so to make it trivially loop-invariant.
544 /// Return true if the instruction after any hoisting is loop invariant. This
545 /// function can be used as a slightly more aggressive replacement for
546 /// isLoopInvariant.
547 ///
548 /// If InsertPt is specified, it is the point to hoist instructions to.
549 /// If null, the terminator of the loop preheader is used.
550 ///
551 bool makeLoopInvariant(Instruction *I, bool &Changed,
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100552 Instruction *InsertPt = nullptr,
553 MemorySSAUpdater *MSSAU = nullptr) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100554
555 /// Check to see if the loop has a canonical induction variable: an integer
556 /// recurrence that starts at 0 and increments by one each time through the
557 /// loop. If so, return the phi node that corresponds to it.
558 ///
559 /// The IndVarSimplify pass transforms loops to have a canonical induction
560 /// variable.
561 ///
562 PHINode *getCanonicalInductionVariable() const;
563
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100564 /// Obtain the unique incoming and back edge. Return false if they are
565 /// non-unique or the loop is dead; otherwise, return true.
566 bool getIncomingAndBackEdge(BasicBlock *&Incoming,
567 BasicBlock *&Backedge) const;
568
569 /// Below are some utilities to get loop bounds and induction variable, and
570 /// check if a given phinode is an auxiliary induction variable, as well as
571 /// checking if the loop is canonical.
572 ///
573 /// Here is an example:
574 /// \code
575 /// for (int i = lb; i < ub; i+=step)
576 /// <loop body>
577 /// --- pseudo LLVMIR ---
578 /// beforeloop:
579 /// guardcmp = (lb < ub)
580 /// if (guardcmp) goto preheader; else goto afterloop
581 /// preheader:
582 /// loop:
583 /// i_1 = phi[{lb, preheader}, {i_2, latch}]
584 /// <loop body>
585 /// i_2 = i_1 + step
586 /// latch:
587 /// cmp = (i_2 < ub)
588 /// if (cmp) goto loop
589 /// exit:
590 /// afterloop:
591 /// \endcode
592 ///
593 /// - getBounds
594 /// - getInitialIVValue --> lb
595 /// - getStepInst --> i_2 = i_1 + step
596 /// - getStepValue --> step
597 /// - getFinalIVValue --> ub
598 /// - getCanonicalPredicate --> '<'
599 /// - getDirection --> Increasing
600 ///
601 /// - getInductionVariable --> i_1
602 /// - isAuxiliaryInductionVariable(x) --> true if x == i_1
603 /// - isCanonical --> false
604 struct LoopBounds {
605 /// Return the LoopBounds object if
606 /// - the given \p IndVar is an induction variable
607 /// - the initial value of the induction variable can be found
608 /// - the step instruction of the induction variable can be found
609 /// - the final value of the induction variable can be found
610 ///
611 /// Else None.
612 static Optional<Loop::LoopBounds> getBounds(const Loop &L, PHINode &IndVar,
613 ScalarEvolution &SE);
614
615 /// Get the initial value of the loop induction variable.
616 Value &getInitialIVValue() const { return InitialIVValue; }
617
618 /// Get the instruction that updates the loop induction variable.
619 Instruction &getStepInst() const { return StepInst; }
620
621 /// Get the step that the loop induction variable gets updated by in each
622 /// loop iteration. Return nullptr if not found.
623 Value *getStepValue() const { return StepValue; }
624
625 /// Get the final value of the loop induction variable.
626 Value &getFinalIVValue() const { return FinalIVValue; }
627
628 /// Return the canonical predicate for the latch compare instruction, if
629 /// able to be calcuated. Else BAD_ICMP_PREDICATE.
630 ///
631 /// A predicate is considered as canonical if requirements below are all
632 /// satisfied:
633 /// 1. The first successor of the latch branch is the loop header
634 /// If not, inverse the predicate.
635 /// 2. One of the operands of the latch comparison is StepInst
636 /// If not, and
637 /// - if the current calcuated predicate is not ne or eq, flip the
638 /// predicate.
639 /// - else if the loop is increasing, return slt
640 /// (notice that it is safe to change from ne or eq to sign compare)
641 /// - else if the loop is decreasing, return sgt
642 /// (notice that it is safe to change from ne or eq to sign compare)
643 ///
644 /// Here is an example when both (1) and (2) are not satisfied:
645 /// \code
646 /// loop.header:
647 /// %iv = phi [%initialiv, %loop.preheader], [%inc, %loop.header]
648 /// %inc = add %iv, %step
649 /// %cmp = slt %iv, %finaliv
650 /// br %cmp, %loop.exit, %loop.header
651 /// loop.exit:
652 /// \endcode
653 /// - The second successor of the latch branch is the loop header instead
654 /// of the first successor (slt -> sge)
655 /// - The first operand of the latch comparison (%cmp) is the IndVar (%iv)
656 /// instead of the StepInst (%inc) (sge -> sgt)
657 ///
658 /// The predicate would be sgt if both (1) and (2) are satisfied.
659 /// getCanonicalPredicate() returns sgt for this example.
660 /// Note: The IR is not changed.
661 ICmpInst::Predicate getCanonicalPredicate() const;
662
663 /// An enum for the direction of the loop
664 /// - for (int i = 0; i < ub; ++i) --> Increasing
665 /// - for (int i = ub; i > 0; --i) --> Descresing
666 /// - for (int i = x; i != y; i+=z) --> Unknown
667 enum class Direction { Increasing, Decreasing, Unknown };
668
669 /// Get the direction of the loop.
670 Direction getDirection() const;
671
672 private:
673 LoopBounds(const Loop &Loop, Value &I, Instruction &SI, Value *SV, Value &F,
674 ScalarEvolution &SE)
675 : L(Loop), InitialIVValue(I), StepInst(SI), StepValue(SV),
676 FinalIVValue(F), SE(SE) {}
677
678 const Loop &L;
679
680 // The initial value of the loop induction variable
681 Value &InitialIVValue;
682
683 // The instruction that updates the loop induction variable
684 Instruction &StepInst;
685
686 // The value that the loop induction variable gets updated by in each loop
687 // iteration
688 Value *StepValue;
689
690 // The final value of the loop induction variable
691 Value &FinalIVValue;
692
693 ScalarEvolution &SE;
694 };
695
696 /// Return the struct LoopBounds collected if all struct members are found,
697 /// else None.
698 Optional<LoopBounds> getBounds(ScalarEvolution &SE) const;
699
700 /// Return the loop induction variable if found, else return nullptr.
701 /// An instruction is considered as the loop induction variable if
702 /// - it is an induction variable of the loop; and
703 /// - it is used to determine the condition of the branch in the loop latch
704 ///
705 /// Note: the induction variable doesn't need to be canonical, i.e. starts at
706 /// zero and increments by one each time through the loop (but it can be).
707 PHINode *getInductionVariable(ScalarEvolution &SE) const;
708
709 /// Get the loop induction descriptor for the loop induction variable. Return
710 /// true if the loop induction variable is found.
711 bool getInductionDescriptor(ScalarEvolution &SE,
712 InductionDescriptor &IndDesc) const;
713
714 /// Return true if the given PHINode \p AuxIndVar is
715 /// - in the loop header
716 /// - not used outside of the loop
717 /// - incremented by a loop invariant step for each loop iteration
718 /// - step instruction opcode should be add or sub
719 /// Note: auxiliary induction variable is not required to be used in the
720 /// conditional branch in the loop latch. (but it can be)
721 bool isAuxiliaryInductionVariable(PHINode &AuxIndVar,
722 ScalarEvolution &SE) const;
723
724 /// Return true if the loop induction variable starts at zero and increments
725 /// by one each time through the loop.
726 bool isCanonical(ScalarEvolution &SE) const;
727
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100728 /// Return true if the Loop is in LCSSA form.
729 bool isLCSSAForm(DominatorTree &DT) const;
730
731 /// Return true if this Loop and all inner subloops are in LCSSA form.
732 bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
733
734 /// Return true if the Loop is in the form that the LoopSimplify form
735 /// transforms loops to, which is sometimes called normal form.
736 bool isLoopSimplifyForm() const;
737
738 /// Return true if the loop body is safe to clone in practice.
739 bool isSafeToClone() const;
740
741 /// Returns true if the loop is annotated parallel.
742 ///
743 /// A parallel loop can be assumed to not contain any dependencies between
744 /// iterations by the compiler. That is, any loop-carried dependency checking
745 /// can be skipped completely when parallelizing the loop on the target
746 /// machine. Thus, if the parallel loop information originates from the
747 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
748 /// programmer's responsibility to ensure there are no loop-carried
749 /// dependencies. The final execution order of the instructions across
750 /// iterations is not guaranteed, thus, the end result might or might not
751 /// implement actual concurrent execution of instructions across multiple
752 /// iterations.
753 bool isAnnotatedParallel() const;
754
755 /// Return the llvm.loop loop id metadata node for this loop if it is present.
756 ///
757 /// If this loop contains the same llvm.loop metadata on each branch to the
758 /// header then the node is returned. If any latch instruction does not
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100759 /// contain llvm.loop or if multiple latches contain different nodes then
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100760 /// 0 is returned.
761 MDNode *getLoopID() const;
762 /// Set the llvm.loop loop id metadata for this loop.
763 ///
764 /// The LoopID metadata node will be added to each terminator instruction in
765 /// the loop that branches to the loop header.
766 ///
767 /// The LoopID metadata node should have one or more operands and the first
768 /// operand should be the node itself.
769 void setLoopID(MDNode *LoopID) const;
770
771 /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
772 ///
773 /// Remove existing unroll metadata and add unroll disable metadata to
774 /// indicate the loop has already been unrolled. This prevents a loop
775 /// from being unrolled more than is directed by a pragma if the loop
776 /// unrolling pass is run more than once (which it generally is).
777 void setLoopAlreadyUnrolled();
778
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100779 void dump() const;
780 void dumpVerbose() const;
781
782 /// Return the debug location of the start of this loop.
783 /// This looks for a BB terminating instruction with a known debug
784 /// location by looking at the preheader and header blocks. If it
785 /// cannot find a terminating instruction with location information,
786 /// it returns an unknown location.
787 DebugLoc getStartLoc() const;
788
789 /// Return the source code span of the loop.
790 LocRange getLocRange() const;
791
792 StringRef getName() const {
793 if (BasicBlock *Header = getHeader())
794 if (Header->hasName())
795 return Header->getName();
796 return "<unnamed loop>";
797 }
798
799private:
800 Loop() = default;
801
802 friend class LoopInfoBase<BasicBlock, Loop>;
803 friend class LoopBase<BasicBlock, Loop>;
804 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
805 ~Loop() = default;
806};
807
808//===----------------------------------------------------------------------===//
809/// This class builds and contains all of the top-level loop
810/// structures in the specified function.
811///
812
813template <class BlockT, class LoopT> class LoopInfoBase {
814 // BBMap - Mapping of basic blocks to the inner most loop they occur in
815 DenseMap<const BlockT *, LoopT *> BBMap;
816 std::vector<LoopT *> TopLevelLoops;
817 BumpPtrAllocator LoopAllocator;
818
819 friend class LoopBase<BlockT, LoopT>;
820 friend class LoopInfo;
821
822 void operator=(const LoopInfoBase &) = delete;
823 LoopInfoBase(const LoopInfoBase &) = delete;
824
825public:
826 LoopInfoBase() {}
827 ~LoopInfoBase() { releaseMemory(); }
828
829 LoopInfoBase(LoopInfoBase &&Arg)
830 : BBMap(std::move(Arg.BBMap)),
831 TopLevelLoops(std::move(Arg.TopLevelLoops)),
832 LoopAllocator(std::move(Arg.LoopAllocator)) {
833 // We have to clear the arguments top level loops as we've taken ownership.
834 Arg.TopLevelLoops.clear();
835 }
836 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
837 BBMap = std::move(RHS.BBMap);
838
839 for (auto *L : TopLevelLoops)
840 L->~LoopT();
841
842 TopLevelLoops = std::move(RHS.TopLevelLoops);
843 LoopAllocator = std::move(RHS.LoopAllocator);
844 RHS.TopLevelLoops.clear();
845 return *this;
846 }
847
848 void releaseMemory() {
849 BBMap.clear();
850
851 for (auto *L : TopLevelLoops)
852 L->~LoopT();
853 TopLevelLoops.clear();
854 LoopAllocator.Reset();
855 }
856
857 template <typename... ArgsTy> LoopT *AllocateLoop(ArgsTy &&... Args) {
858 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
859 return new (Storage) LoopT(std::forward<ArgsTy>(Args)...);
860 }
861
862 /// iterator/begin/end - The interface to the top-level loops in the current
863 /// function.
864 ///
865 typedef typename std::vector<LoopT *>::const_iterator iterator;
866 typedef
867 typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
868 iterator begin() const { return TopLevelLoops.begin(); }
869 iterator end() const { return TopLevelLoops.end(); }
870 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
871 reverse_iterator rend() const { return TopLevelLoops.rend(); }
872 bool empty() const { return TopLevelLoops.empty(); }
873
874 /// Return all of the loops in the function in preorder across the loop
875 /// nests, with siblings in forward program order.
876 ///
877 /// Note that because loops form a forest of trees, preorder is equivalent to
878 /// reverse postorder.
879 SmallVector<LoopT *, 4> getLoopsInPreorder();
880
881 /// Return all of the loops in the function in preorder across the loop
882 /// nests, with siblings in *reverse* program order.
883 ///
884 /// Note that because loops form a forest of trees, preorder is equivalent to
885 /// reverse postorder.
886 ///
887 /// Also note that this is *not* a reverse preorder. Only the siblings are in
888 /// reverse program order.
889 SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
890
891 /// Return the inner most loop that BB lives in. If a basic block is in no
892 /// loop (for example the entry node), null is returned.
893 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
894
895 /// Same as getLoopFor.
896 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
897
898 /// Return the loop nesting level of the specified block. A depth of 0 means
899 /// the block is not inside any loop.
900 unsigned getLoopDepth(const BlockT *BB) const {
901 const LoopT *L = getLoopFor(BB);
902 return L ? L->getLoopDepth() : 0;
903 }
904
905 // True if the block is a loop header node
906 bool isLoopHeader(const BlockT *BB) const {
907 const LoopT *L = getLoopFor(BB);
908 return L && L->getHeader() == BB;
909 }
910
911 /// This removes the specified top-level loop from this loop info object.
912 /// The loop is not deleted, as it will presumably be inserted into
913 /// another loop.
914 LoopT *removeLoop(iterator I) {
915 assert(I != end() && "Cannot remove end iterator!");
916 LoopT *L = *I;
917 assert(!L->getParentLoop() && "Not a top-level loop!");
918 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
919 return L;
920 }
921
922 /// Change the top-level loop that contains BB to the specified loop.
923 /// This should be used by transformations that restructure the loop hierarchy
924 /// tree.
925 void changeLoopFor(BlockT *BB, LoopT *L) {
926 if (!L) {
927 BBMap.erase(BB);
928 return;
929 }
930 BBMap[BB] = L;
931 }
932
933 /// Replace the specified loop in the top-level loops list with the indicated
934 /// loop.
935 void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
936 auto I = find(TopLevelLoops, OldLoop);
937 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
938 *I = NewLoop;
939 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
940 "Loops already embedded into a subloop!");
941 }
942
943 /// This adds the specified loop to the collection of top-level loops.
944 void addTopLevelLoop(LoopT *New) {
945 assert(!New->getParentLoop() && "Loop already in subloop!");
946 TopLevelLoops.push_back(New);
947 }
948
949 /// This method completely removes BB from all data structures,
950 /// including all of the Loop objects it is nested in and our mapping from
951 /// BasicBlocks to loops.
952 void removeBlock(BlockT *BB) {
953 auto I = BBMap.find(BB);
954 if (I != BBMap.end()) {
955 for (LoopT *L = I->second; L; L = L->getParentLoop())
956 L->removeBlockFromLoop(BB);
957
958 BBMap.erase(I);
959 }
960 }
961
962 // Internals
963
964 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
965 const LoopT *ParentLoop) {
966 if (!SubLoop)
967 return true;
968 if (SubLoop == ParentLoop)
969 return false;
970 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
971 }
972
973 /// Create the loop forest using a stable algorithm.
974 void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
975
976 // Debugging
977 void print(raw_ostream &OS) const;
978
979 void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
980
981 /// Destroy a loop that has been removed from the `LoopInfo` nest.
982 ///
983 /// This runs the destructor of the loop object making it invalid to
984 /// reference afterward. The memory is retained so that the *pointer* to the
985 /// loop remains valid.
986 ///
987 /// The caller is responsible for removing this loop from the loop nest and
988 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
989 /// Callers that don't naturally handle this themselves should probably call
990 /// `erase' instead.
991 void destroy(LoopT *L) {
992 L->~LoopT();
993
994 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
995 // \c L, but the pointer remains valid for non-dereferencing uses.
996 LoopAllocator.Deallocate(L);
997 }
998};
999
1000// Implementation in LoopInfoImpl.h
1001extern template class LoopInfoBase<BasicBlock, Loop>;
1002
1003class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
1004 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
1005
1006 friend class LoopBase<BasicBlock, Loop>;
1007
1008 void operator=(const LoopInfo &) = delete;
1009 LoopInfo(const LoopInfo &) = delete;
1010
1011public:
1012 LoopInfo() {}
1013 explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
1014
1015 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
1016 LoopInfo &operator=(LoopInfo &&RHS) {
1017 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
1018 return *this;
1019 }
1020
1021 /// Handle invalidation explicitly.
1022 bool invalidate(Function &F, const PreservedAnalyses &PA,
1023 FunctionAnalysisManager::Invalidator &);
1024
1025 // Most of the public interface is provided via LoopInfoBase.
1026
1027 /// Update LoopInfo after removing the last backedge from a loop. This updates
1028 /// the loop forest and parent loops for each block so that \c L is no longer
1029 /// referenced, but does not actually delete \c L immediately. The pointer
1030 /// will remain valid until this LoopInfo's memory is released.
1031 void erase(Loop *L);
1032
1033 /// Returns true if replacing From with To everywhere is guaranteed to
1034 /// preserve LCSSA form.
1035 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
1036 // Preserving LCSSA form is only problematic if the replacing value is an
1037 // instruction.
1038 Instruction *I = dyn_cast<Instruction>(To);
1039 if (!I)
1040 return true;
1041 // If both instructions are defined in the same basic block then replacement
1042 // cannot break LCSSA form.
1043 if (I->getParent() == From->getParent())
1044 return true;
1045 // If the instruction is not defined in a loop then it can safely replace
1046 // anything.
1047 Loop *ToLoop = getLoopFor(I->getParent());
1048 if (!ToLoop)
1049 return true;
1050 // If the replacing instruction is defined in the same loop as the original
1051 // instruction, or in a loop that contains it as an inner loop, then using
1052 // it as a replacement will not break LCSSA form.
1053 return ToLoop->contains(getLoopFor(From->getParent()));
1054 }
1055
1056 /// Checks if moving a specific instruction can break LCSSA in any loop.
1057 ///
1058 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
1059 /// assuming that the function containing \p Inst and \p NewLoc is currently
1060 /// in LCSSA form.
1061 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
1062 assert(Inst->getFunction() == NewLoc->getFunction() &&
1063 "Can't reason about IPO!");
1064
1065 auto *OldBB = Inst->getParent();
1066 auto *NewBB = NewLoc->getParent();
1067
1068 // Movement within the same loop does not break LCSSA (the equality check is
1069 // to avoid doing a hashtable lookup in case of intra-block movement).
1070 if (OldBB == NewBB)
1071 return true;
1072
1073 auto *OldLoop = getLoopFor(OldBB);
1074 auto *NewLoop = getLoopFor(NewBB);
1075
1076 if (OldLoop == NewLoop)
1077 return true;
1078
1079 // Check if Outer contains Inner; with the null loop counting as the
1080 // "outermost" loop.
1081 auto Contains = [](const Loop *Outer, const Loop *Inner) {
1082 return !Outer || Outer->contains(Inner);
1083 };
1084
1085 // To check that the movement of Inst to before NewLoc does not break LCSSA,
1086 // we need to check two sets of uses for possible LCSSA violations at
1087 // NewLoc: the users of NewInst, and the operands of NewInst.
1088
1089 // If we know we're hoisting Inst out of an inner loop to an outer loop,
1090 // then the uses *of* Inst don't need to be checked.
1091
1092 if (!Contains(NewLoop, OldLoop)) {
1093 for (Use &U : Inst->uses()) {
1094 auto *UI = cast<Instruction>(U.getUser());
1095 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
1096 : UI->getParent();
1097 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
1098 return false;
1099 }
1100 }
1101
1102 // If we know we're sinking Inst from an outer loop into an inner loop, then
1103 // the *operands* of Inst don't need to be checked.
1104
1105 if (!Contains(OldLoop, NewLoop)) {
1106 // See below on why we can't handle phi nodes here.
1107 if (isa<PHINode>(Inst))
1108 return false;
1109
1110 for (Use &U : Inst->operands()) {
1111 auto *DefI = dyn_cast<Instruction>(U.get());
1112 if (!DefI)
1113 return false;
1114
1115 // This would need adjustment if we allow Inst to be a phi node -- the
1116 // new use block won't simply be NewBB.
1117
1118 auto *DefBlock = DefI->getParent();
1119 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
1120 return false;
1121 }
1122 }
1123
1124 return true;
1125 }
1126};
1127
1128// Allow clients to walk the list of nested loops...
1129template <> struct GraphTraits<const Loop *> {
1130 typedef const Loop *NodeRef;
1131 typedef LoopInfo::iterator ChildIteratorType;
1132
1133 static NodeRef getEntryNode(const Loop *L) { return L; }
1134 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
1135 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
1136};
1137
1138template <> struct GraphTraits<Loop *> {
1139 typedef Loop *NodeRef;
1140 typedef LoopInfo::iterator ChildIteratorType;
1141
1142 static NodeRef getEntryNode(Loop *L) { return L; }
1143 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
1144 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
1145};
1146
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001147/// Analysis pass that exposes the \c LoopInfo for a function.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001148class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
1149 friend AnalysisInfoMixin<LoopAnalysis>;
1150 static AnalysisKey Key;
1151
1152public:
1153 typedef LoopInfo Result;
1154
1155 LoopInfo run(Function &F, FunctionAnalysisManager &AM);
1156};
1157
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001158/// Printer pass for the \c LoopAnalysis results.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001159class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
1160 raw_ostream &OS;
1161
1162public:
1163 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
1164 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
1165};
1166
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001167/// Verifier pass for the \c LoopAnalysis results.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001168struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
1169 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
1170};
1171
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001172/// The legacy pass manager's analysis pass to compute loop information.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001173class LoopInfoWrapperPass : public FunctionPass {
1174 LoopInfo LI;
1175
1176public:
1177 static char ID; // Pass identification, replacement for typeid
1178
1179 LoopInfoWrapperPass() : FunctionPass(ID) {
1180 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
1181 }
1182
1183 LoopInfo &getLoopInfo() { return LI; }
1184 const LoopInfo &getLoopInfo() const { return LI; }
1185
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001186 /// Calculate the natural loop information for a given function.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001187 bool runOnFunction(Function &F) override;
1188
1189 void verifyAnalysis() const override;
1190
1191 void releaseMemory() override { LI.releaseMemory(); }
1192
1193 void print(raw_ostream &O, const Module *M = nullptr) const override;
1194
1195 void getAnalysisUsage(AnalysisUsage &AU) const override;
1196};
1197
1198/// Function to print a loop's contents as LLVM's text IR assembly.
1199void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
1200
Andrew Walbran16937d02019-10-22 13:54:20 +01001201/// Find and return the loop attribute node for the attribute @p Name in
1202/// @p LoopID. Return nullptr if there is no such attribute.
1203MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name);
1204
1205/// Find string metadata for a loop.
1206///
1207/// Returns the MDNode where the first operand is the metadata's name. The
1208/// following operands are the metadata's values. If no metadata with @p Name is
1209/// found, return nullptr.
1210MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
1211
1212/// Return whether an MDNode might represent an access group.
1213///
1214/// Access group metadata nodes have to be distinct and empty. Being
1215/// always-empty ensures that it never needs to be changed (which -- because
1216/// MDNodes are designed immutable -- would require creating a new MDNode). Note
1217/// that this is not a sufficient condition: not every distinct and empty NDNode
1218/// is representing an access group.
1219bool isValidAsAccessGroup(MDNode *AccGroup);
1220
1221/// Create a new LoopID after the loop has been transformed.
1222///
1223/// This can be used when no follow-up loop attributes are defined
1224/// (llvm::makeFollowupLoopID returning None) to stop transformations to be
1225/// applied again.
1226///
1227/// @param Context The LLVMContext in which to create the new LoopID.
1228/// @param OrigLoopID The original LoopID; can be nullptr if the original
1229/// loop has no LoopID.
1230/// @param RemovePrefixes Remove all loop attributes that have these prefixes.
1231/// Use to remove metadata of the transformation that has
1232/// been applied.
1233/// @param AddAttrs Add these loop attributes to the new LoopID.
1234///
1235/// @return A new LoopID that can be applied using Loop::setLoopID().
1236llvm::MDNode *
1237makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
1238 llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
1239 llvm::ArrayRef<llvm::MDNode *> AddAttrs);
1240
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001241} // End llvm namespace
1242
1243#endif