LLVM 23.0.0git
LoopFlatten.cpp
Go to the documentation of this file.
1//===- LoopFlatten.cpp - Loop flattening 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 pass flattens pairs nested loops into a single loop.
10//
11// The intention is to optimise loop nests like this, which together access an
12// array linearly:
13//
14// for (int i = 0; i < N; ++i)
15// for (int j = 0; j < M; ++j)
16// f(A[i*M+j]);
17//
18// into one loop:
19//
20// for (int i = 0; i < (N*M); ++i)
21// f(A[i]);
22//
23// It can also flatten loops where the induction variables are not used in the
24// loop. This is only worth doing if the induction variables are only used in an
25// expression like i*M+j. If they had any other uses, we would have to insert a
26// div/mod to reconstruct the original values, so this wouldn't be profitable.
27//
28// We also need to prove that N*M will not overflow. The preferred solution is
29// to widen the IV, which avoids overflow checks, so that is tried first. If
30// the IV cannot be widened, then we try to determine that this new tripcount
31// expression won't overflow.
32//
33// Q: Does LoopFlatten use SCEV?
34// Short answer: Yes and no.
35//
36// Long answer:
37// For this transformation to be valid, we require all uses of the induction
38// variables to be linear expressions of the form i*M+j. The different Loop
39// APIs are used to get some loop components like the induction variable,
40// compare statement, etc. In addition, we do some pattern matching to find the
41// linear expressions and other loop components like the loop increment. The
42// latter are examples of expressions that do use the induction variable, but
43// are safe to ignore when we check all uses to be of the form i*M+j. We keep
44// track of all of this in bookkeeping struct FlattenInfo.
45// We assume the loops to be canonical, i.e. starting at 0 and increment with
46// 1. This makes RHS of the compare the loop tripcount (with the right
47// predicate). We use SCEV to then sanity check that this tripcount matches
48// with the tripcount as computed by SCEV.
49//
50//===----------------------------------------------------------------------===//
51
53
54#include "llvm/ADT/Statistic.h"
64#include "llvm/IR/Dominators.h"
65#include "llvm/IR/Function.h"
66#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/Module.h"
69#include "llvm/Support/Debug.h"
77#include <optional>
78
79using namespace llvm;
80using namespace llvm::PatternMatch;
81
82#define DEBUG_TYPE "loop-flatten"
83
84STATISTIC(NumFlattened, "Number of loops flattened");
85
87 "loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
88 cl::desc("Limit on the cost of instructions that can be repeated due to "
89 "loop flattening"));
90
91static cl::opt<bool>
92 AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
93 cl::init(false),
94 cl::desc("Assume that the product of the two iteration "
95 "trip counts will never overflow"));
96
97static cl::opt<bool>
98 WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
99 cl::desc("Widen the loop induction variables, if possible, so "
100 "overflow checks won't reject flattening"));
101
102static cl::opt<bool>
103 VersionLoops("loop-flatten-version-loops", cl::Hidden, cl::init(true),
104 cl::desc("Version loops if flattened loop could overflow"));
105
106namespace {
107// We require all uses of both induction variables to match this pattern:
108//
109// (OuterPHI * InnerTripCount) + InnerPHI
110//
111// I.e., it needs to be a linear expression of the induction variables and the
112// inner loop trip count. We keep track of all different expressions on which
113// checks will be performed in this bookkeeping struct.
114//
115struct FlattenInfo {
116 Loop *OuterLoop = nullptr; // The loop pair to be flattened.
117 Loop *InnerLoop = nullptr;
118
119 PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
120 PHINode *OuterInductionPHI = nullptr; // induction variables, which are
121 // expected to start at zero and
122 // increment by one on each loop.
123
124 Value *InnerTripCount = nullptr; // The product of these two tripcounts
125 Value *OuterTripCount = nullptr; // will be the new flattened loop
126 // tripcount. Also used to recognise a
127 // linear expression that will be replaced.
128
129 SmallPtrSet<Value *, 4> LinearIVUses; // Contains the linear expressions
130 // of the form i*M+j that will be
131 // replaced.
132
133 BinaryOperator *InnerIncrement = nullptr; // Uses of induction variables in
134 BinaryOperator *OuterIncrement = nullptr; // loop control statements that
135 BranchInst *InnerBranch = nullptr; // are safe to ignore.
136
137 BranchInst *OuterBranch = nullptr; // The instruction that needs to be
138 // updated with new tripcount.
139
140 SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
141
142 bool Widened = false; // Whether this holds the flatten info before or after
143 // widening.
144
145 PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
146 PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
147 // has been applied. Used to skip
148 // checks on phi nodes.
149
150 Value *NewTripCount = nullptr; // The tripcount of the flattened loop.
151
152 FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
153
154 bool isNarrowInductionPhi(PHINode *Phi) {
155 // This can't be the narrow phi if we haven't widened the IV first.
156 if (!Widened)
157 return false;
158 return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
159 }
160 bool isInnerLoopIncrement(User *U) {
161 return InnerIncrement == U;
162 }
163 bool isOuterLoopIncrement(User *U) {
164 return OuterIncrement == U;
165 }
166 bool isInnerLoopTest(User *U) {
167 return InnerBranch->getCondition() == U;
168 }
169
170 bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
171 for (User *U : OuterInductionPHI->users()) {
172 if (isOuterLoopIncrement(U))
173 continue;
174
175 auto IsValidOuterPHIUses = [&] (User *U) -> bool {
176 LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
177 if (!ValidOuterPHIUses.count(U)) {
178 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
179 return false;
180 }
181 LLVM_DEBUG(dbgs() << "Use is optimisable\n");
182 return true;
183 };
184
185 if (auto *V = dyn_cast<TruncInst>(U)) {
186 for (auto *K : V->users()) {
187 if (!IsValidOuterPHIUses(K))
188 return false;
189 }
190 continue;
191 }
192
193 if (!IsValidOuterPHIUses(U))
194 return false;
195 }
196 return true;
197 }
198
199 bool matchLinearIVUser(User *U, Value *InnerTripCount,
200 SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
201 LLVM_DEBUG(dbgs() << "Checking linear i*M+j expression for: "; U->dump());
202 Value *MatchedMul = nullptr;
203 Value *MatchedItCount = nullptr;
204
205 bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
206 m_Value(MatchedMul))) &&
207 match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
208 m_Value(MatchedItCount)));
209
210 // Matches the same pattern as above, except it also looks for truncs
211 // on the phi, which can be the result of widening the induction variables.
212 bool IsAddTrunc =
213 match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
214 m_Value(MatchedMul))) &&
215 match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
216 m_Value(MatchedItCount)));
217
218 // Matches the pattern ptr+i*M+j, with the two additions being done via GEP.
219 bool IsGEP = match(U, m_GEP(m_GEP(m_Value(), m_Value(MatchedMul)),
220 m_Specific(InnerInductionPHI))) &&
221 match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
222 m_Value(MatchedItCount)));
223
224 if (!MatchedItCount)
225 return false;
226
227 LLVM_DEBUG(dbgs() << "Matched multiplication: "; MatchedMul->dump());
228 LLVM_DEBUG(dbgs() << "Matched iteration count: "; MatchedItCount->dump());
229
230 // The mul should not have any other uses. Widening may leave trivially dead
231 // uses, which can be ignored.
232 if (count_if(MatchedMul->users(), [](User *U) {
233 return !isInstructionTriviallyDead(cast<Instruction>(U));
234 }) > 1) {
235 LLVM_DEBUG(dbgs() << "Multiply has more than one use\n");
236 return false;
237 }
238
239 // Look through extends if the IV has been widened. Don't look through
240 // extends if we already looked through a trunc.
241 if (Widened && (IsAdd || IsGEP) &&
242 (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
243 assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
244 "Unexpected type mismatch in types after widening");
245 MatchedItCount = isa<SExtInst>(MatchedItCount)
246 ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
247 : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
248 }
249
250 LLVM_DEBUG(dbgs() << "Looking for inner trip count: ";
251 InnerTripCount->dump());
252
253 if ((IsAdd || IsAddTrunc || IsGEP) && MatchedItCount == InnerTripCount) {
254 LLVM_DEBUG(dbgs() << "Found. This sse is optimisable\n");
255 ValidOuterPHIUses.insert(MatchedMul);
256 LinearIVUses.insert(U);
257 return true;
258 }
259
260 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
261 return false;
262 }
263
264 bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
265 Value *SExtInnerTripCount = InnerTripCount;
266 if (Widened &&
267 (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
268 SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
269
270 for (User *U : InnerInductionPHI->users()) {
271 LLVM_DEBUG(dbgs() << "Checking User: "; U->dump());
272 if (isInnerLoopIncrement(U)) {
273 LLVM_DEBUG(dbgs() << "Use is inner loop increment, continuing\n");
274 continue;
275 }
276
277 // After widening the IVs, a trunc instruction might have been introduced,
278 // so look through truncs.
279 if (isa<TruncInst>(U)) {
280 if (!U->hasOneUse())
281 return false;
282 U = *U->user_begin();
283 }
284
285 // If the use is in the compare (which is also the condition of the inner
286 // branch) then the compare has been altered by another transformation e.g
287 // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
288 // a constant. Ignore this use as the compare gets removed later anyway.
289 if (isInnerLoopTest(U)) {
290 LLVM_DEBUG(dbgs() << "Use is the inner loop test, continuing\n");
291 continue;
292 }
293
294 if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses)) {
295 LLVM_DEBUG(dbgs() << "Not a linear IV user\n");
296 return false;
297 }
298 LLVM_DEBUG(dbgs() << "Linear IV users found!\n");
299 }
300 return true;
301 }
302};
303} // namespace
304
305static bool
307 SmallPtrSetImpl<Instruction *> &IterationInstructions) {
308 TripCount = TC;
309 IterationInstructions.insert(Increment);
310 LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
311 LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
312 LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
313 return true;
314}
315
316// Given the RHS of the loop latch compare instruction, verify with SCEV
317// that this is indeed the loop tripcount.
318// TODO: This used to be a straightforward check but has grown to be quite
319// complicated now. It is therefore worth revisiting what the additional
320// benefits are of this (compared to relying on canonical loops and pattern
321// matching).
322static bool verifyTripCount(Value *RHS, Loop *L,
323 SmallPtrSetImpl<Instruction *> &IterationInstructions,
324 PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
325 BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
326 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
327 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
328 LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
329 return false;
330 }
331
332 // Evaluating in the trip count's type can not overflow here as the overflow
333 // checks are performed in checkOverflow, but are first tried to avoid by
334 // widening the IV.
335 const SCEV *SCEVTripCount =
336 SE->getTripCountFromExitCount(BackedgeTakenCount,
337 BackedgeTakenCount->getType(), L);
338
339 const SCEV *SCEVRHS = SE->getSCEV(RHS);
340 if (SCEVRHS == SCEVTripCount)
341 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
342 ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
343 if (ConstantRHS) {
344 const SCEV *BackedgeTCExt = nullptr;
345 if (IsWidened) {
346 const SCEV *SCEVTripCountExt;
347 // Find the extended backedge taken count and extended trip count using
348 // SCEV. One of these should now match the RHS of the compare.
349 BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
350 SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt,
351 RHS->getType(), L);
352 if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
353 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
354 return false;
355 }
356 }
357 // If the RHS of the compare is equal to the backedge taken count we need
358 // to add one to get the trip count.
359 if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
360 Value *NewRHS = ConstantInt::get(ConstantRHS->getContext(),
361 ConstantRHS->getValue() + 1);
362 return setLoopComponents(NewRHS, TripCount, Increment,
363 IterationInstructions);
364 }
365 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
366 }
367 // If the RHS isn't a constant then check that the reason it doesn't match
368 // the SCEV trip count is because the RHS is a ZExt or SExt instruction
369 // (and take the trip count to be the RHS).
370 if (!IsWidened) {
371 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
372 return false;
373 }
374 auto *TripCountInst = dyn_cast<Instruction>(RHS);
375 if (!TripCountInst) {
376 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
377 return false;
378 }
379 if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
380 SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
381 LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
382 return false;
383 }
384 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
385}
386
387// Finds the induction variable, increment and trip count for a simple loop that
388// we can flatten.
390 Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
391 PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
392 BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
393 LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
394
395 if (!L->isLoopSimplifyForm()) {
396 LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
397 return false;
398 }
399
400 // Currently, to simplify the implementation, the Loop induction variable must
401 // start at zero and increment with a step size of one.
402 if (!L->isCanonical(*SE)) {
403 LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
404 return false;
405 }
406
407 // There must be exactly one exiting block, and it must be the same at the
408 // latch.
409 BasicBlock *Latch = L->getLoopLatch();
410 if (L->getExitingBlock() != Latch) {
411 LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
412 return false;
413 }
414
415 // Find the induction PHI. If there is no induction PHI, we can't do the
416 // transformation. TODO: could other variables trigger this? Do we have to
417 // search for the best one?
418 InductionPHI = L->getInductionVariable(*SE);
419 if (!InductionPHI) {
420 LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
421 return false;
422 }
423 LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
424
425 bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
426 auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
427 if (ContinueOnTrue)
428 return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
429 else
430 return Pred == CmpInst::ICMP_EQ;
431 };
432
433 // Find Compare and make sure it is valid. getLatchCmpInst checks that the
434 // back branch of the latch is conditional.
435 ICmpInst *Compare = L->getLatchCmpInst();
436 if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
437 Compare->hasNUsesOrMore(2)) {
438 LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
439 return false;
440 }
441 BackBranch = cast<BranchInst>(Latch->getTerminator());
442 IterationInstructions.insert(BackBranch);
443 LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
444 IterationInstructions.insert(Compare);
445 LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
446
447 // Find increment and trip count.
448 // There are exactly 2 incoming values to the induction phi; one from the
449 // pre-header and one from the latch. The incoming latch value is the
450 // increment variable.
451 Increment =
453 if ((Compare->getOperand(0) != Increment || !Increment->hasNUses(2)) &&
454 !Increment->hasNUses(1)) {
455 LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
456 return false;
457 }
458 // The trip count is the RHS of the compare. If this doesn't match the trip
459 // count computed by SCEV then this is because the trip count variable
460 // has been widened so the types don't match, or because it is a constant and
461 // another transformation has changed the compare (e.g. icmp ult %inc,
462 // tripcount -> icmp ult %j, tripcount-1), or both.
463 Value *RHS = Compare->getOperand(1);
464
465 return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
466 Increment, BackBranch, SE, IsWidened);
467}
468
469static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
470 // All PHIs in the inner and outer headers must either be:
471 // - The induction PHI, which we are going to rewrite as one induction in
472 // the new loop. This is already checked by findLoopComponents.
473 // - An outer header PHI with all incoming values from outside the loop.
474 // LoopSimplify guarantees we have a pre-header, so we don't need to
475 // worry about that here.
476 // - Pairs of PHIs in the inner and outer headers, which implement a
477 // loop-carried dependency that will still be valid in the new loop. To
478 // be valid, this variable must be modified only in the inner loop.
479
480 // The set of PHI nodes in the outer loop header that we know will still be
481 // valid after the transformation. These will not need to be modified (with
482 // the exception of the induction variable), but we do need to check that
483 // there are no unsafe PHI nodes.
484 SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
485 SafeOuterPHIs.insert(FI.OuterInductionPHI);
486
487 // Check that all PHI nodes in the inner loop header match one of the valid
488 // patterns.
489 for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
490 // The induction PHIs break these rules, and that's OK because we treat
491 // them specially when doing the transformation.
492 if (&InnerPHI == FI.InnerInductionPHI)
493 continue;
494 if (FI.isNarrowInductionPhi(&InnerPHI))
495 continue;
496
497 // Each inner loop PHI node must have two incoming values/blocks - one
498 // from the pre-header, and one from the latch.
499 assert(InnerPHI.getNumIncomingValues() == 2);
500 Value *PreHeaderValue =
501 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
502 Value *LatchValue =
503 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
504
505 // The incoming value from the outer loop must be the PHI node in the
506 // outer loop header, with no modifications made in the top of the outer
507 // loop.
508 PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
509 if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
510 LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
511 return false;
512 }
513
514 // The other incoming value must come from the inner loop, without any
515 // modifications in the tail end of the outer loop. We are in LCSSA form,
516 // so this will actually be a PHI in the inner loop's exit block, which
517 // only uses values from inside the inner loop.
518 PHINode *LCSSAPHI = dyn_cast<PHINode>(
519 OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
520 if (!LCSSAPHI) {
521 LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
522 return false;
523 }
524
525 // The value used by the LCSSA PHI must be the same one that the inner
526 // loop's PHI uses.
527 if (LCSSAPHI->hasConstantValue() != LatchValue) {
529 dbgs() << "LCSSA PHI incoming value does not match latch value\n");
530 return false;
531 }
532
533 LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
534 LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump());
535 LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump());
536 SafeOuterPHIs.insert(OuterPHI);
537 FI.InnerPHIsToTransform.insert(&InnerPHI);
538 }
539
540 for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
541 if (FI.isNarrowInductionPhi(&OuterPHI))
542 continue;
543 if (!SafeOuterPHIs.count(&OuterPHI)) {
544 LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
545 return false;
546 }
547 }
548
549 LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
550 return true;
551}
552
553static bool
554checkOuterLoopInsts(FlattenInfo &FI,
555 SmallPtrSetImpl<Instruction *> &IterationInstructions,
556 const TargetTransformInfo *TTI) {
557 // Check for instructions in the outer but not inner loop. If any of these
558 // have side-effects then this transformation is not legal, and if there is
559 // a significant amount of code here which can't be optimised out that it's
560 // not profitable (as these instructions would get executed for each
561 // iteration of the inner loop).
562 InstructionCost RepeatedInstrCost = 0;
563 for (auto *B : FI.OuterLoop->getBlocks()) {
564 if (FI.InnerLoop->contains(B))
565 continue;
566
567 for (auto &I : *B) {
568 if (!isa<PHINode>(&I) && !I.isTerminator() &&
570 LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
571 "side effects: ";
572 I.dump());
573 return false;
574 }
575 // The execution count of the outer loop's iteration instructions
576 // (increment, compare and branch) will be increased, but the
577 // equivalent instructions will be removed from the inner loop, so
578 // they make a net difference of zero.
579 if (IterationInstructions.count(&I))
580 continue;
581 // The unconditional branch to the inner loop's header will turn into
582 // a fall-through, so adds no cost.
584 if (Br && Br->isUnconditional() &&
585 Br->getSuccessor(0) == FI.InnerLoop->getHeader())
586 continue;
587 // Multiplies of the outer iteration variable and inner iteration
588 // count will be optimised out.
589 if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
590 m_Specific(FI.InnerTripCount))))
591 continue;
592 InstructionCost Cost =
593 TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
594 LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
595 RepeatedInstrCost += Cost;
596 }
597 }
598
599 LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
600 << RepeatedInstrCost << "\n");
601 // Bail out if flattening the loops would cause instructions in the outer
602 // loop but not in the inner loop to be executed extra times.
603 if (RepeatedInstrCost > RepeatedInstructionThreshold) {
604 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
605 return false;
606 }
607
608 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
609 return true;
610}
611
612
613
614// We require all uses of both induction variables to match this pattern:
615//
616// (OuterPHI * InnerTripCount) + InnerPHI
617//
618// Any uses of the induction variables not matching that pattern would
619// require a div/mod to reconstruct in the flattened loop, so the
620// transformation wouldn't be profitable.
621static bool checkIVUsers(FlattenInfo &FI) {
622 // Check that all uses of the inner loop's induction variable match the
623 // expected pattern, recording the uses of the outer IV.
624 SmallPtrSet<Value *, 4> ValidOuterPHIUses;
625 if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
626 return false;
627
628 // Check that there are no uses of the outer IV other than the ones found
629 // as part of the pattern above.
630 if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
631 return false;
632
633 LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
634 dbgs() << "Found " << FI.LinearIVUses.size()
635 << " value(s) that can be replaced:\n";
636 for (Value *V : FI.LinearIVUses) {
637 dbgs() << " ";
638 V->dump();
639 });
640 return true;
641}
642
643// Return an OverflowResult dependant on if overflow of the multiplication of
644// InnerTripCount and OuterTripCount can be assumed not to happen.
645static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
646 AssumptionCache *AC) {
647 Function *F = FI.OuterLoop->getHeader()->getParent();
648 const DataLayout &DL = F->getDataLayout();
649
650 // For debugging/testing.
653
654 // Check if the multiply could not overflow due to known ranges of the
655 // input values.
657 FI.InnerTripCount, FI.OuterTripCount,
658 SimplifyQuery(DL, DT, AC,
659 FI.OuterLoop->getLoopPreheader()->getTerminator()));
661 return OR;
662
663 auto CheckGEP = [&](GetElementPtrInst *GEP, Value *GEPOperand) {
664 for (Value *GEPUser : GEP->users()) {
665 auto *GEPUserInst = cast<Instruction>(GEPUser);
666 if (!isa<LoadInst>(GEPUserInst) &&
667 !(isa<StoreInst>(GEPUserInst) && GEP == GEPUserInst->getOperand(1)))
668 continue;
669 if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst, FI.InnerLoop))
670 continue;
671 // The IV is used as the operand of a GEP which dominates the loop
672 // latch, and the IV is at least as wide as the address space of the
673 // GEP. In this case, the GEP would wrap around the address space
674 // before the IV increment wraps, which would be UB.
675 if (GEP->isInBounds() &&
676 GEPOperand->getType()->getIntegerBitWidth() >=
677 DL.getPointerTypeSizeInBits(GEP->getType())) {
679 dbgs() << "use of linear IV would be UB if overflow occurred: ";
680 GEP->dump());
681 return true;
682 }
683 }
684 return false;
685 };
686
687 // Check if any IV user is, or is used by, a GEP that would cause UB if the
688 // multiply overflows.
689 for (Value *V : FI.LinearIVUses) {
690 if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
691 if (GEP->getNumIndices() == 1 && CheckGEP(GEP, GEP->getOperand(1)))
693 for (Value *U : V->users())
694 if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
695 if (CheckGEP(GEP, V))
697 }
698
700}
701
702static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
704 const TargetTransformInfo *TTI) {
705 SmallPtrSet<Instruction *, 8> IterationInstructions;
706 if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
707 FI.InnerInductionPHI, FI.InnerTripCount,
708 FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
709 return false;
710 if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
711 FI.OuterInductionPHI, FI.OuterTripCount,
712 FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
713 return false;
714
715 // Both of the loop trip count values must be invariant in the outer loop
716 // (non-instructions are all inherently invariant).
717 if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
718 LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
719 return false;
720 }
721 if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
722 LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
723 return false;
724 }
725
726 if (!checkPHIs(FI, TTI))
727 return false;
728
729 // FIXME: it should be possible to handle different types correctly.
730 if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
731 return false;
732
733 if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
734 return false;
735
736 // Find the values in the loop that can be replaced with the linearized
737 // induction variable, and check that there are no other uses of the inner
738 // or outer induction variable. If there were, we could still do this
739 // transformation, but we'd have to insert a div/mod to calculate the
740 // original IVs, so it wouldn't be profitable.
741 if (!checkIVUsers(FI))
742 return false;
743
744 LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
745 return true;
746}
747
748static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
751 MemorySSAUpdater *MSSAU) {
752 Function *F = FI.OuterLoop->getHeader()->getParent();
753 LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
754 {
755 using namespace ore;
756 OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
757 FI.InnerLoop->getHeader());
759 Remark << "Flattened into outer loop";
760 ORE.emit(Remark);
761 }
762
763 if (!FI.NewTripCount) {
764 FI.NewTripCount = BinaryOperator::CreateMul(
765 FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
766 FI.OuterLoop->getLoopPreheader()->getTerminator()->getIterator());
767 LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
768 FI.NewTripCount->dump());
769 }
770
771 // Fix up PHI nodes that take values from the inner loop back-edge, which
772 // we are about to remove.
773 FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
774
775 // The old Phi will be optimised away later, but for now we can't leave
776 // leave it in an invalid state, so are updating them too.
777 for (PHINode *PHI : FI.InnerPHIsToTransform)
778 PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
779
780 // Modify the trip count of the outer loop to be the product of the two
781 // trip counts.
782 cast<User>(FI.OuterBranch->getCondition())->setOperand(1, FI.NewTripCount);
783
784 // Replace the inner loop backedge with an unconditional branch to the exit.
785 BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
786 BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
787 Instruction *Term = InnerExitingBlock->getTerminator();
788 Instruction *BI = BranchInst::Create(InnerExitBlock, InnerExitingBlock);
789 BI->setDebugLoc(Term->getDebugLoc());
790 Term->eraseFromParent();
791
792 // Update the DomTree and MemorySSA.
793 DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
794 if (MSSAU)
795 MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
796
797 // Replace all uses of the polynomial calculated from the two induction
798 // variables with the one new one.
799 IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
800 for (Value *V : FI.LinearIVUses) {
801 Value *OuterValue = FI.OuterInductionPHI;
802 if (FI.Widened)
803 OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
804 "flatten.trunciv");
805
806 if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
807 // Replace the GEP with one that uses OuterValue as the offset.
808 auto *InnerGEP = cast<GetElementPtrInst>(GEP->getOperand(0));
809 Value *Base = InnerGEP->getOperand(0);
810 // When the base of the GEP doesn't dominate the outer induction phi then
811 // we need to insert the new GEP where the old GEP was.
812 if (!DT->dominates(Base, &*Builder.GetInsertPoint()))
813 Builder.SetInsertPoint(cast<Instruction>(V));
814 OuterValue =
815 Builder.CreateGEP(GEP->getSourceElementType(), Base, OuterValue,
816 "flatten." + V->getName(),
817 GEP->isInBounds() && InnerGEP->isInBounds());
818 }
819
820 LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with: ";
821 OuterValue->dump());
822 V->replaceAllUsesWith(OuterValue);
823 }
824
825 // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
826 // deleted, and invalidate any outer loop information.
827 SE->forgetLoop(FI.OuterLoop);
829 if (U)
830 U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
831 LI->erase(FI.InnerLoop);
832
833 // Increment statistic value.
834 NumFlattened++;
835
836 return true;
837}
838
839static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
841 const TargetTransformInfo *TTI) {
842 if (!WidenIV) {
843 LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
844 return false;
845 }
846
847 LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
848 Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
849 auto &DL = M->getDataLayout();
850 auto *InnerType = FI.InnerInductionPHI->getType();
851 auto *OuterType = FI.OuterInductionPHI->getType();
852 unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
853 auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
854
855 // If both induction types are less than the maximum legal integer width,
856 // promote both to the widest type available so we know calculating
857 // (OuterTripCount * InnerTripCount) as the new trip count is safe.
858 if (InnerType != OuterType ||
859 InnerType->getScalarSizeInBits() >= MaxLegalSize ||
860 MaxLegalType->getScalarSizeInBits() <
861 InnerType->getScalarSizeInBits() * 2) {
862 LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
863 return false;
864 }
865
866 SCEVExpander Rewriter(*SE, "loopflatten");
868 unsigned ElimExt = 0;
869 unsigned Widened = 0;
870
871 auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
872 PHINode *WidePhi =
873 createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
874 true /* HasGuards */, true /* UsePostIncrementRanges */);
875 if (!WidePhi)
876 return false;
877 LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
878 LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
880 return true;
881 };
882
883 bool Deleted;
884 if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
885 return false;
886 // Add the narrow phi to list, so that it will be adjusted later when the
887 // the transformation is performed.
888 if (!Deleted)
889 FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
890
891 if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
892 return false;
893
894 assert(Widened && "Widened IV expected");
895 FI.Widened = true;
896
897 // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
898 FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
899 FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
900
901 // After widening, rediscover all the loop components.
902 return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
903}
904
905static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
908 MemorySSAUpdater *MSSAU,
909 const LoopAccessInfo &LAI) {
911 dbgs() << "Loop flattening running on outer loop "
912 << FI.OuterLoop->getHeader()->getName() << " and inner loop "
913 << FI.InnerLoop->getHeader()->getName() << " in "
914 << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
915
916 if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
917 return false;
918
919 // Check if we can widen the induction variables to avoid overflow checks.
920 bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
921
922 // It can happen that after widening of the IV, flattening may not be
923 // possible/happening, e.g. when it is deemed unprofitable. So bail here if
924 // that is the case.
925 // TODO: IV widening without performing the actual flattening transformation
926 // is not ideal. While this codegen change should not matter much, it is an
927 // unnecessary change which is better to avoid. It's unlikely this happens
928 // often, because if it's unprofitibale after widening, it should be
929 // unprofitabe before widening as checked in the first round of checks. But
930 // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
931 // relaxed. Because this is making a code change (the IV widening, but not
932 // the flattening), we return true here.
933 if (FI.Widened && !CanFlatten)
934 return true;
935
936 // If we have widened and can perform the transformation, do that here.
937 if (CanFlatten)
938 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
939
940 // Otherwise, if we haven't widened the IV, check if the new iteration
941 // variable might overflow. In this case, we need to version the loop, and
942 // select the original version at runtime if the iteration space is too
943 // large.
944 OverflowResult OR = checkOverflow(FI, DT, AC);
947 LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
948 return false;
949 } else if (OR == OverflowResult::MayOverflow) {
950 Module *M = FI.OuterLoop->getHeader()->getParent()->getParent();
951 const DataLayout &DL = M->getDataLayout();
952 if (!VersionLoops) {
953 LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
954 return false;
955 } else if (!DL.isLegalInteger(
956 FI.OuterTripCount->getType()->getScalarSizeInBits())) {
957 // If the trip count type isn't legal then it won't be possible to check
958 // for overflow using only a single multiply instruction, so don't
959 // flatten.
961 dbgs() << "Can't check overflow efficiently, not flattening\n");
962 return false;
963 }
964 LLVM_DEBUG(dbgs() << "Multiply might overflow, versioning loop\n");
965
966 // Version the loop. The overflow check isn't a runtime pointer check, so we
967 // pass an empty list of runtime pointer checks, causing LoopVersioning to
968 // emit 'false' as the branch condition, and add our own check afterwards.
969 BasicBlock *CheckBlock = FI.OuterLoop->getLoopPreheader();
970 ArrayRef<RuntimePointerCheck> Checks(nullptr, nullptr);
971 LoopVersioning LVer(LAI, Checks, FI.OuterLoop, LI, DT, SE);
972 LVer.versionLoop();
973
974 // Check for overflow by calculating the new tripcount using
975 // umul_with_overflow and then checking if it overflowed.
976 BranchInst *Br = cast<BranchInst>(CheckBlock->getTerminator());
977 assert(Br->isConditional() &&
978 "Expected LoopVersioning to generate a conditional branch");
979 assert(match(Br->getCondition(), m_Zero()) &&
980 "Expected branch condition to be false");
981 IRBuilder<> Builder(Br);
982 Value *Call = Builder.CreateIntrinsic(
983 Intrinsic::umul_with_overflow, FI.OuterTripCount->getType(),
984 {FI.OuterTripCount, FI.InnerTripCount},
985 /*FMFSource=*/nullptr, "flatten.mul");
986 FI.NewTripCount = Builder.CreateExtractValue(Call, 0, "flatten.tripcount");
987 Value *Overflow = Builder.CreateExtractValue(Call, 1, "flatten.overflow");
988 Br->setCondition(Overflow);
989 } else {
990 LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
991 }
992
993 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
994}
995
998 LPMUpdater &U) {
999
1000 bool Changed = false;
1001
1002 std::optional<MemorySSAUpdater> MSSAU;
1003 if (AR.MSSA) {
1004 MSSAU = MemorySSAUpdater(AR.MSSA);
1005 if (VerifyMemorySSA)
1006 AR.MSSA->verifyMemorySSA();
1007 }
1008
1009 // The loop flattening pass requires loops to be
1010 // in simplified form, and also needs LCSSA. Running
1011 // this pass will simplify all loops that contain inner loops,
1012 // regardless of whether anything ends up being flattened.
1013 LoopAccessInfoManager LAIM(AR.SE, AR.AA, AR.DT, AR.LI, &AR.TTI, nullptr,
1014 &AR.AC);
1015 for (Loop *InnerLoop : LN.getLoops()) {
1016 auto *OuterLoop = InnerLoop->getParentLoop();
1017 if (!OuterLoop)
1018 continue;
1019 FlattenInfo FI(OuterLoop, InnerLoop);
1020 Changed |=
1021 FlattenLoopPair(FI, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
1022 MSSAU ? &*MSSAU : nullptr, LAIM.getInfo(*OuterLoop));
1023 }
1024
1025 if (!Changed)
1026 return PreservedAnalyses::all();
1027
1028 if (AR.MSSA && VerifyMemorySSA)
1029 AR.MSSA->verifyMemorySSA();
1030
1031 auto PA = getLoopPassPreservedAnalyses();
1032 if (AR.MSSA)
1033 PA.preserve<MemorySSAAnalysis>();
1034 return PA;
1035}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI)
static bool verifyTripCount(Value *RHS, Loop *L, SmallPtrSetImpl< Instruction * > &IterationInstructions, PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened)
static cl::opt< bool > WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true), cl::desc("Widen the loop induction variables, if possible, so " "overflow checks won't reject flattening"))
static bool setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment, SmallPtrSetImpl< Instruction * > &IterationInstructions)
static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI, LPMUpdater *U, MemorySSAUpdater *MSSAU)
static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI, LPMUpdater *U, MemorySSAUpdater *MSSAU, const LoopAccessInfo &LAI)
static bool checkIVUsers(FlattenInfo &FI)
static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, const TargetTransformInfo *TTI)
static cl::opt< bool > VersionLoops("loop-flatten-version-loops", cl::Hidden, cl::init(true), cl::desc("Version loops if flattened loop could overflow"))
static bool findLoopComponents(Loop *L, SmallPtrSetImpl< Instruction * > &IterationInstructions, PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened)
static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, AssumptionCache *AC)
static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI)
static cl::opt< unsigned > RepeatedInstructionThreshold("loop-flatten-cost-threshold", cl::Hidden, cl::init(2), cl::desc("Limit on the cost of instructions that can be repeated due to " "loop flattening"))
static cl::opt< bool > AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, cl::init(false), cl::desc("Assume that the product of the two iteration " "trip counts will never overflow"))
static bool checkOuterLoopInsts(FlattenInfo &FI, SmallPtrSetImpl< Instruction * > &IterationInstructions, const TargetTransformInfo *TTI)
This file defines the interface for the loop nest analysis.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
LoopAnalysisManager LAM
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:114
This pass exposes codegen information to IR-level passes.
Virtual Register Rewriter
Value * RHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
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:539
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ ICMP_NE
not equal
Definition InstrTypes.h:698
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
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.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2794
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
LLVM_ABI const LoopAccessInfo & getInfo(Loop &L, bool AllowPartial=false)
Drive the analysis of memory accesses in the loop.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
BlockT * getHeader() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
PreservedAnalyses run(LoopNest &LN, LoopAnalysisManager &LAM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition LoopInfo.cpp:887
This class represents a loop nest and can be used to query its properties.
ArrayRef< Loop * > getLoops() const
Get the loops in the nest.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
void versionLoop()
Performs the CFG manipulation part of versioning the loop including the DominatorTree and LoopInfo up...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:632
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:61
StringRef getName() const
Definition LoopInfo.h:389
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:936
LLVM_ABI void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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.
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
LLVM_ABI Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value,...
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 uses information about analyze scalars to rewrite expressions in canonical form.
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
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 const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
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...
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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 is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1106
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Changed
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_GEP(const OperandTypes &...Ops)
Matches GetElementPtrInst.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
PHINode * createWideIV(const WideIVInfo &WI, LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, unsigned &NumElimExt, unsigned &NumWidened, bool HasGuards, bool UsePostIncrementRanges)
Widen Induction Variables - Extend the width of an IV to cover its widest uses.
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:84
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2009
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:641
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Collect information about induction variables that are used by sign/zero extend operations.