LLVM 24.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#include "ScalarOptions.h"
54
55#include "llvm/ADT/Statistic.h"
65#include "llvm/IR/Dominators.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/Module.h"
70#include "llvm/Support/Debug.h"
78#include <optional>
79
80using namespace llvm;
81using namespace llvm::PatternMatch;
82
83#define DEBUG_TYPE "loop-flatten"
84
85STATISTIC(NumFlattened, "Number of loops flattened");
86
87namespace {
88// We require all uses of both induction variables to match this pattern:
89//
90// (OuterPHI * InnerTripCount) + InnerPHI
91//
92// I.e., it needs to be a linear expression of the induction variables and the
93// inner loop trip count. We keep track of all different expressions on which
94// checks will be performed in this bookkeeping struct.
95//
96struct FlattenInfo {
97 const ScalarOptions &Opts;
98 Loop *OuterLoop = nullptr; // The loop pair to be flattened.
99 Loop *InnerLoop = nullptr;
100
101 PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
102 PHINode *OuterInductionPHI = nullptr; // induction variables, which are
103 // expected to start at zero and
104 // increment by one on each loop.
105
106 Value *InnerTripCount = nullptr; // The product of these two tripcounts
107 Value *OuterTripCount = nullptr; // will be the new flattened loop
108 // tripcount. Also used to recognise a
109 // linear expression that will be replaced.
110
111 SmallPtrSet<Value *, 4> LinearIVUses; // Contains the linear expressions
112 // of the form i*M+j that will be
113 // replaced.
114
115 BinaryOperator *InnerIncrement = nullptr; // Uses of induction variables in
116 BinaryOperator *OuterIncrement = nullptr; // loop control statements that
117 CondBrInst *InnerBranch = nullptr; // are safe to ignore.
118
119 CondBrInst *OuterBranch = nullptr; // The instruction that needs to be
120 // updated with new tripcount.
121
122 SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
123
124 bool Widened = false; // Whether this holds the flatten info before or after
125 // widening.
126
127 PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
128 PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
129 // has been applied. Used to skip
130 // checks on phi nodes.
131
132 Value *NewTripCount = nullptr; // The tripcount of the flattened loop.
133
134 FlattenInfo(Loop *OL, Loop *IL)
135 : Opts(ScalarOptions::Global), OuterLoop(OL), InnerLoop(IL) {}
136
137 bool isNarrowInductionPhi(PHINode *Phi) {
138 // This can't be the narrow phi if we haven't widened the IV first.
139 if (!Widened)
140 return false;
141 return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
142 }
143 bool isInnerLoopIncrement(User *U) {
144 return InnerIncrement == U;
145 }
146 bool isOuterLoopIncrement(User *U) {
147 return OuterIncrement == U;
148 }
149 bool isInnerLoopTest(User *U) {
150 return InnerBranch->getCondition() == U;
151 }
152
153 bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
154 for (User *U : OuterInductionPHI->users()) {
155 if (isOuterLoopIncrement(U))
156 continue;
157
158 auto IsValidOuterPHIUses = [&] (User *U) -> bool {
159 LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
160 if (!ValidOuterPHIUses.count(U)) {
161 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
162 return false;
163 }
164 LLVM_DEBUG(dbgs() << "Use is optimisable\n");
165 return true;
166 };
167
168 if (auto *V = dyn_cast<TruncInst>(U)) {
169 for (auto *K : V->users()) {
170 if (!IsValidOuterPHIUses(K))
171 return false;
172 }
173 continue;
174 }
175
176 if (!IsValidOuterPHIUses(U))
177 return false;
178 }
179 return true;
180 }
181
182 bool matchLinearIVUser(User *U, Value *InnerTripCount,
183 SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
184 LLVM_DEBUG(dbgs() << "Checking linear i*M+j expression for: "; U->dump());
185 Value *MatchedMul = nullptr;
186 Value *MatchedItCount = nullptr;
187
188 bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
189 m_Value(MatchedMul))) &&
190 match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
191 m_Value(MatchedItCount)));
192
193 // Matches the same pattern as above, except it also looks for truncs
194 // on the phi, which can be the result of widening the induction variables.
195 bool IsAddTrunc =
196 match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
197 m_Value(MatchedMul))) &&
198 match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
199 m_Value(MatchedItCount)));
200
201 // Matches the pattern ptr+i*M+j, with the two additions being done via GEP.
202 bool IsGEP = match(U, m_GEP(m_GEP(m_Value(), m_Value(MatchedMul)),
203 m_Specific(InnerInductionPHI))) &&
204 match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
205 m_Value(MatchedItCount)));
206
207 if (!MatchedItCount)
208 return false;
209
210 LLVM_DEBUG(dbgs() << "Matched multiplication: "; MatchedMul->dump());
211 LLVM_DEBUG(dbgs() << "Matched iteration count: "; MatchedItCount->dump());
212
213 // The mul should not have any other uses. Widening may leave trivially dead
214 // uses, which can be ignored.
215 if (count_if(MatchedMul->users(), [](User *U) {
216 return !isInstructionTriviallyDead(cast<Instruction>(U));
217 }) > 1) {
218 LLVM_DEBUG(dbgs() << "Multiply has more than one use\n");
219 return false;
220 }
221
222 // Look through extends if the IV has been widened. Don't look through
223 // extends if we already looked through a trunc.
224 if (Widened && (IsAdd || IsGEP) &&
225 (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
226 assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
227 "Unexpected type mismatch in types after widening");
228 MatchedItCount = isa<SExtInst>(MatchedItCount)
229 ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
230 : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
231 }
232
233 LLVM_DEBUG(dbgs() << "Looking for inner trip count: ";
234 InnerTripCount->dump());
235
236 if ((IsAdd || IsAddTrunc || IsGEP) && MatchedItCount == InnerTripCount) {
237 LLVM_DEBUG(dbgs() << "Found. This sse is optimisable\n");
238 ValidOuterPHIUses.insert(MatchedMul);
239 LinearIVUses.insert(U);
240 return true;
241 }
242
243 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
244 return false;
245 }
246
247 bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
248 Value *SExtInnerTripCount = InnerTripCount;
249 if (Widened &&
250 (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
251 SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
252
253 for (User *U : InnerInductionPHI->users()) {
254 LLVM_DEBUG(dbgs() << "Checking User: "; U->dump());
255 if (isInnerLoopIncrement(U)) {
256 LLVM_DEBUG(dbgs() << "Use is inner loop increment, continuing\n");
257 continue;
258 }
259
260 // After widening the IVs, a trunc instruction might have been introduced,
261 // so look through truncs.
262 if (isa<TruncInst>(U)) {
263 if (!U->hasOneUse())
264 return false;
265 U = *U->user_begin();
266 }
267
268 // If the use is in the compare (which is also the condition of the inner
269 // branch) then the compare has been altered by another transformation e.g
270 // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
271 // a constant. Ignore this use as the compare gets removed later anyway.
272 if (isInnerLoopTest(U)) {
273 LLVM_DEBUG(dbgs() << "Use is the inner loop test, continuing\n");
274 continue;
275 }
276
277 if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses)) {
278 LLVM_DEBUG(dbgs() << "Not a linear IV user\n");
279 return false;
280 }
281 LLVM_DEBUG(dbgs() << "Linear IV users found!\n");
282 }
283 return true;
284 }
285};
286} // namespace
287
288static bool
290 SmallPtrSetImpl<Instruction *> &IterationInstructions) {
291 TripCount = TC;
292 IterationInstructions.insert(Increment);
293 LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
294 LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
295 LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
296 return true;
297}
298
299// Given the RHS of the loop latch compare instruction, verify with SCEV
300// that this is indeed the loop tripcount.
301// TODO: This used to be a straightforward check but has grown to be quite
302// complicated now. It is therefore worth revisiting what the additional
303// benefits are of this (compared to relying on canonical loops and pattern
304// matching).
305static bool verifyTripCount(
306 Value *RHS, Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
307 PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
308 CondBrInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
309 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
310 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
311 LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
312 return false;
313 }
314
315 // Evaluating in the trip count's type can not overflow here as the overflow
316 // checks are performed in checkOverflow, but are first tried to avoid by
317 // widening the IV.
318 const SCEV *SCEVTripCount =
319 SE->getTripCountFromExitCount(BackedgeTakenCount,
320 BackedgeTakenCount->getType(), L);
321
322 const SCEV *SCEVRHS = SE->getSCEV(RHS);
323 if (SCEVRHS == SCEVTripCount)
324 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
325 ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
326 if (ConstantRHS) {
327 const SCEV *BackedgeTCExt = nullptr;
328 if (IsWidened) {
329 const SCEV *SCEVTripCountExt;
330 // Find the extended backedge taken count and extended trip count using
331 // SCEV. One of these should now match the RHS of the compare.
332 BackedgeTCExt =
333 SE->getNoopOrZeroExtend(BackedgeTakenCount, RHS->getType());
334 SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt,
335 RHS->getType(), L);
336 if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
337 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
338 return false;
339 }
340 }
341 // If the RHS of the compare is equal to the backedge taken count we need
342 // to add one to get the trip count.
343 if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
344 Value *NewRHS = ConstantInt::get(ConstantRHS->getContext(),
345 ConstantRHS->getValue() + 1);
346 return setLoopComponents(NewRHS, TripCount, Increment,
347 IterationInstructions);
348 }
349 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
350 }
351 // If the RHS isn't a constant then check that the reason it doesn't match
352 // the SCEV trip count is because the RHS is a ZExt or SExt instruction
353 // (and take the trip count to be the RHS).
354 if (!IsWidened) {
355 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
356 return false;
357 }
358 auto *TripCountInst = dyn_cast<Instruction>(RHS);
359 if (!TripCountInst) {
360 LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
361 return false;
362 }
363 if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
364 SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
365 LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
366 return false;
367 }
368 return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
369}
370
371// Finds the induction variable, increment and trip count for a simple loop that
372// we can flatten.
374 Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
375 PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
376 CondBrInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
377 LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
378
379 if (!L->isLoopSimplifyForm()) {
380 LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
381 return false;
382 }
383
384 // Currently, to simplify the implementation, the Loop induction variable must
385 // start at zero and increment with a step size of one.
386 if (!L->isCanonical(*SE)) {
387 LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
388 return false;
389 }
390
391 // There must be exactly one exiting block, and it must be the same at the
392 // latch.
393 BasicBlock *Latch = L->getLoopLatch();
394 if (L->getExitingBlock() != Latch) {
395 LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
396 return false;
397 }
398
399 // Find the induction PHI. If there is no induction PHI, we can't do the
400 // transformation. TODO: could other variables trigger this? Do we have to
401 // search for the best one?
402 InductionPHI = L->getInductionVariable(*SE);
403 if (!InductionPHI) {
404 LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
405 return false;
406 }
407 LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
408
409 bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
410 auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
411 if (ContinueOnTrue)
412 return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
413 else
414 return Pred == CmpInst::ICMP_EQ;
415 };
416
417 // Find Compare and make sure it is valid. getLatchCmpInst checks that the
418 // back branch of the latch is conditional.
419 ICmpInst *Compare = L->getLatchCmpInst();
420 if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
421 Compare->hasNUsesOrMore(2)) {
422 LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
423 return false;
424 }
425 BackBranch = cast<CondBrInst>(Latch->getTerminator());
426 IterationInstructions.insert(BackBranch);
427 LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
428 IterationInstructions.insert(Compare);
429 LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
430
431 // Find increment and trip count.
432 // There are exactly 2 incoming values to the induction phi; one from the
433 // pre-header and one from the latch. The incoming latch value is the
434 // increment variable.
435 Increment =
437 if ((Compare->getOperand(0) != Increment || !Increment->hasNUses(2)) &&
438 !Increment->hasNUses(1)) {
439 LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
440 return false;
441 }
442 // The trip count is the RHS of the compare. If this doesn't match the trip
443 // count computed by SCEV then this is because the trip count variable
444 // has been widened so the types don't match, or because it is a constant and
445 // another transformation has changed the compare (e.g. icmp ult %inc,
446 // tripcount -> icmp ult %j, tripcount-1), or both.
447 Value *RHS = Compare->getOperand(1);
448
449 return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
450 Increment, BackBranch, SE, IsWidened);
451}
452
453static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
454 // All PHIs in the inner and outer headers must either be:
455 // - The induction PHI, which we are going to rewrite as one induction in
456 // the new loop. This is already checked by findLoopComponents.
457 // - An outer header PHI with all incoming values from outside the loop.
458 // LoopSimplify guarantees we have a pre-header, so we don't need to
459 // worry about that here.
460 // - Pairs of PHIs in the inner and outer headers, which implement a
461 // loop-carried dependency that will still be valid in the new loop. To
462 // be valid, this variable must be modified only in the inner loop.
463
464 // The set of PHI nodes in the outer loop header that we know will still be
465 // valid after the transformation. These will not need to be modified (with
466 // the exception of the induction variable), but we do need to check that
467 // there are no unsafe PHI nodes.
468 SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
469 SafeOuterPHIs.insert(FI.OuterInductionPHI);
470
471 // Check that all PHI nodes in the inner loop header match one of the valid
472 // patterns.
473 for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
474 // The induction PHIs break these rules, and that's OK because we treat
475 // them specially when doing the transformation.
476 if (&InnerPHI == FI.InnerInductionPHI)
477 continue;
478 if (FI.isNarrowInductionPhi(&InnerPHI))
479 continue;
480
481 // Each inner loop PHI node must have two incoming values/blocks - one
482 // from the pre-header, and one from the latch.
483 assert(InnerPHI.getNumIncomingValues() == 2);
484 Value *PreHeaderValue =
485 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
486 Value *LatchValue =
487 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
488
489 // The incoming value from the outer loop must be the PHI node in the
490 // outer loop header, with no modifications made in the top of the outer
491 // loop.
492 PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
493 if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
494 LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
495 return false;
496 }
497
498 // The other incoming value must come from the inner loop, without any
499 // modifications in the tail end of the outer loop. We are in LCSSA form,
500 // so this will actually be a PHI in the inner loop's exit block, which
501 // only uses values from inside the inner loop.
502 PHINode *LCSSAPHI = dyn_cast<PHINode>(
503 OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
504 if (!LCSSAPHI) {
505 LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
506 return false;
507 }
508
509 // The value used by the LCSSA PHI must be the same one that the inner
510 // loop's PHI uses.
511 if (LCSSAPHI->hasConstantValue() != LatchValue) {
513 dbgs() << "LCSSA PHI incoming value does not match latch value\n");
514 return false;
515 }
516
517 LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
518 LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump());
519 LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump());
520 SafeOuterPHIs.insert(OuterPHI);
521 FI.InnerPHIsToTransform.insert(&InnerPHI);
522 }
523
524 for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
525 if (FI.isNarrowInductionPhi(&OuterPHI))
526 continue;
527 if (!SafeOuterPHIs.count(&OuterPHI)) {
528 LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
529 return false;
530 }
531 }
532
533 LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
534 return true;
535}
536
537static bool
538checkOuterLoopInsts(FlattenInfo &FI,
539 SmallPtrSetImpl<Instruction *> &IterationInstructions,
540 const TargetTransformInfo *TTI) {
541 // Check for instructions in the outer but not inner loop. If any of these
542 // have side-effects then this transformation is not legal, and if there is
543 // a significant amount of code here which can't be optimised out that it's
544 // not profitable (as these instructions would get executed for each
545 // iteration of the inner loop).
546 InstructionCost RepeatedInstrCost = 0;
547 for (auto *B : FI.OuterLoop->getBlocks()) {
548 if (FI.InnerLoop->contains(B))
549 continue;
550
551 for (auto &I : *B) {
552 if (!isa<PHINode>(&I) && !I.isTerminator() &&
554 LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
555 "side effects: ";
556 I.dump());
557 return false;
558 }
559 // The execution count of the outer loop's iteration instructions
560 // (increment, compare and branch) will be increased, but the
561 // equivalent instructions will be removed from the inner loop, so
562 // they make a net difference of zero.
563 if (IterationInstructions.count(&I))
564 continue;
565 // The unconditional branch to the inner loop's header will turn into
566 // a fall-through, so adds no cost.
568 if (Br && Br->getSuccessor() == FI.InnerLoop->getHeader())
569 continue;
570 // Multiplies of the outer iteration variable and inner iteration
571 // count will be optimised out.
572 if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
573 m_Specific(FI.InnerTripCount))))
574 continue;
575 InstructionCost Cost =
576 TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
577 LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
578 RepeatedInstrCost += Cost;
579 }
580 }
581
582 LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
583 << RepeatedInstrCost << "\n");
584 // Bail out if flattening the loops would cause instructions in the outer
585 // loop but not in the inner loop to be executed extra times.
586 if (RepeatedInstrCost > FI.Opts.loop_flatten_cost_threshold) {
587 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
588 return false;
589 }
590
591 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
592 return true;
593}
594
595
596
597// We require all uses of both induction variables to match this pattern:
598//
599// (OuterPHI * InnerTripCount) + InnerPHI
600//
601// Any uses of the induction variables not matching that pattern would
602// require a div/mod to reconstruct in the flattened loop, so the
603// transformation wouldn't be profitable.
604static bool checkIVUsers(FlattenInfo &FI) {
605 // Check that all uses of the inner loop's induction variable match the
606 // expected pattern, recording the uses of the outer IV.
607 SmallPtrSet<Value *, 4> ValidOuterPHIUses;
608 if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
609 return false;
610
611 // Check that there are no uses of the outer IV other than the ones found
612 // as part of the pattern above.
613 if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
614 return false;
615
616 LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
617 dbgs() << "Found " << FI.LinearIVUses.size()
618 << " value(s) that can be replaced:\n";
619 for (Value *V : FI.LinearIVUses) {
620 dbgs() << " ";
621 V->dump();
622 });
623 return true;
624}
625
626// Return an OverflowResult dependant on if overflow of the multiplication of
627// InnerTripCount and OuterTripCount can be assumed not to happen.
628static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
629 AssumptionCache *AC) {
630 Function *F = FI.OuterLoop->getHeader()->getParent();
631 const DataLayout &DL = F->getDataLayout();
632
633 // For debugging/testing.
634 if (FI.Opts.loop_flatten_assume_no_overflow)
636
637 // Check if the multiply could not overflow due to known ranges of the
638 // input values.
640 FI.InnerTripCount, FI.OuterTripCount,
641 SimplifyQuery(DL, DT, AC,
642 FI.OuterLoop->getLoopPreheader()->getTerminator()));
644 return OR;
645
646 auto CheckGEP = [&](GetElementPtrInst *GEP, Value *GEPOperand) {
647 for (Value *GEPUser : GEP->users()) {
648 auto *GEPUserInst = cast<Instruction>(GEPUser);
649 if (!isa<LoadInst>(GEPUserInst) &&
650 !(isa<StoreInst>(GEPUserInst) && GEP == GEPUserInst->getOperand(1)))
651 continue;
652 if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst, FI.InnerLoop))
653 continue;
654 // The IV is used as the operand of a GEP which dominates the loop
655 // latch, and the IV is at least as wide as the address space of the
656 // GEP. In this case, the GEP would wrap around the address space
657 // before the IV increment wraps, which would be UB.
658 if (GEP->isInBounds() &&
659 GEPOperand->getType()->getIntegerBitWidth() >=
660 DL.getPointerTypeSizeInBits(GEP->getType())) {
662 dbgs() << "use of linear IV would be UB if overflow occurred: ";
663 GEP->dump());
664 return true;
665 }
666 }
667 return false;
668 };
669
670 // Check if any IV user is, or is used by, a GEP that would cause UB if the
671 // multiply overflows.
672 for (Value *V : FI.LinearIVUses) {
673 if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
674 if (GEP->getNumIndices() == 1 && CheckGEP(GEP, GEP->getOperand(1)))
676 for (Value *U : V->users())
677 if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
678 if (CheckGEP(GEP, V))
680 }
681
683}
684
685static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
687 const TargetTransformInfo *TTI) {
688 SmallPtrSet<Instruction *, 8> IterationInstructions;
689 if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
690 FI.InnerInductionPHI, FI.InnerTripCount,
691 FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
692 return false;
693 if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
694 FI.OuterInductionPHI, FI.OuterTripCount,
695 FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
696 return false;
697
698 // Both of the loop trip count values must be invariant in the outer loop
699 // (non-instructions are all inherently invariant).
700 if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
701 LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
702 return false;
703 }
704 if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
705 LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
706 return false;
707 }
708
709 if (!checkPHIs(FI, TTI))
710 return false;
711
712 // FIXME: it should be possible to handle different types correctly.
713 if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
714 return false;
715
716 if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
717 return false;
718
719 // Find the values in the loop that can be replaced with the linearized
720 // induction variable, and check that there are no other uses of the inner
721 // or outer induction variable. If there were, we could still do this
722 // transformation, but we'd have to insert a div/mod to calculate the
723 // original IVs, so it wouldn't be profitable.
724 if (!checkIVUsers(FI))
725 return false;
726
727 LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
728 return true;
729}
730
731static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
734 MemorySSAUpdater *MSSAU) {
735 Function *F = FI.OuterLoop->getHeader()->getParent();
736 LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
737 {
738 using namespace ore;
739 OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
740 FI.InnerLoop->getHeader());
742 Remark << "Flattened into outer loop";
743 ORE.emit(Remark);
744 }
745
746 if (!FI.NewTripCount) {
747 FI.NewTripCount = BinaryOperator::CreateMul(
748 FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
749 FI.OuterLoop->getLoopPreheader()->getTerminator()->getIterator());
750 LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
751 FI.NewTripCount->dump());
752 }
753
754 // Fix up PHI nodes that take values from the inner loop back-edge, which
755 // we are about to remove.
756 FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
757
758 // The old Phi will be optimised away later, but for now we can't leave
759 // leave it in an invalid state, so are updating them too.
760 for (PHINode *PHI : FI.InnerPHIsToTransform)
761 PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
762
763 // Modify the trip count of the outer loop to be the product of the two
764 // trip counts.
765 cast<User>(FI.OuterBranch->getCondition())->setOperand(1, FI.NewTripCount);
766
767 // Replace the inner loop backedge with an unconditional branch to the exit.
768 BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
769 BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
770 Instruction *Term = InnerExitingBlock->getTerminator();
771 Instruction *BI = UncondBrInst::Create(InnerExitBlock, InnerExitingBlock);
772 BI->setDebugLoc(Term->getDebugLoc());
773 Term->eraseFromParent();
774
775 // Update the DomTree and MemorySSA.
776 DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
777 if (MSSAU)
778 MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
779
780 // Replace all uses of the polynomial calculated from the two induction
781 // variables with the one new one.
782 IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
783 for (Value *V : FI.LinearIVUses) {
784 Value *OuterValue = FI.OuterInductionPHI;
785 if (FI.Widened)
786 OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
787 "flatten.trunciv");
788
789 if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
790 // Replace the GEP with one that uses OuterValue as the offset.
791 auto *InnerGEP = cast<GetElementPtrInst>(GEP->getOperand(0));
792 Value *Base = InnerGEP->getOperand(0);
793 // When the base of the GEP doesn't dominate the outer induction phi then
794 // we need to insert the new GEP where the old GEP was.
795 if (!DT->dominates(Base, &*Builder.GetInsertPoint()))
796 Builder.SetInsertPoint(cast<Instruction>(V));
797 OuterValue =
798 Builder.CreateGEP(GEP->getSourceElementType(), Base, OuterValue,
799 "flatten." + V->getName(),
800 GEP->isInBounds() && InnerGEP->isInBounds());
801 }
802
803 LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with: ";
804 OuterValue->dump());
805 V->replaceAllUsesWith(OuterValue);
806 }
807
808 // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
809 // deleted, and invalidate any outer loop information.
810 SE->forgetLoop(FI.OuterLoop);
812 if (U)
813 U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
814 LI->erase(FI.InnerLoop);
815
816 // Increment statistic value.
817 NumFlattened++;
818
819 return true;
820}
821
822static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
824 const TargetTransformInfo *TTI) {
825 if (!FI.Opts.loop_flatten_widen_iv) {
826 LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
827 return false;
828 }
829
830 LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
831 Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
832 auto &DL = M->getDataLayout();
833 auto *InnerType = FI.InnerInductionPHI->getType();
834 auto *OuterType = FI.OuterInductionPHI->getType();
835 unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
836 auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
837
838 // If both induction types are less than the maximum legal integer width,
839 // promote both to the widest type available so we know calculating
840 // (OuterTripCount * InnerTripCount) as the new trip count is safe.
841 if (InnerType != OuterType ||
842 InnerType->getScalarSizeInBits() >= MaxLegalSize ||
843 MaxLegalType->getScalarSizeInBits() <
844 InnerType->getScalarSizeInBits() * 2) {
845 LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
846 return false;
847 }
848
849 SCEVExpander Rewriter(*SE, "loopflatten");
851 unsigned ElimExt = 0;
852 unsigned Widened = 0;
853
854 auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
855 PHINode *WidePhi =
856 createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
857 true /* HasGuards */, true /* UsePostIncrementRanges */);
858 if (!WidePhi)
859 return false;
860 SE->forgetLoop(FI.OuterLoop);
861 LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
862 LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
864 return true;
865 };
866
867 bool Deleted;
868 if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
869 return false;
870 // Add the narrow phi to list, so that it will be adjusted later when the
871 // the transformation is performed.
872 if (!Deleted)
873 FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
874
875 if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
876 return false;
877
878 assert(Widened && "Widened IV expected");
879 FI.Widened = true;
880
881 // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
882 FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
883 FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
884
885 // After widening, rediscover all the loop components.
886 return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
887}
888
889static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
892 MemorySSAUpdater *MSSAU,
893 const LoopAccessInfo &LAI) {
895 dbgs() << "Loop flattening running on outer loop "
896 << FI.OuterLoop->getHeader()->getName() << " and inner loop "
897 << FI.InnerLoop->getHeader()->getName() << " in "
898 << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
899
900 if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
901 return false;
902
903 // Check if we can widen the induction variables to avoid overflow checks.
904 bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
905
906 // It can happen that after widening of the IV, flattening may not be
907 // possible/happening, e.g. when it is deemed unprofitable. So bail here if
908 // that is the case.
909 // TODO: IV widening without performing the actual flattening transformation
910 // is not ideal. While this codegen change should not matter much, it is an
911 // unnecessary change which is better to avoid. It's unlikely this happens
912 // often, because if it's unprofitibale after widening, it should be
913 // unprofitabe before widening as checked in the first round of checks. But
914 // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
915 // relaxed. Because this is making a code change (the IV widening, but not
916 // the flattening), we return true here.
917 if (FI.Widened && !CanFlatten)
918 return true;
919
920 // If we have widened and can perform the transformation, do that here.
921 if (CanFlatten)
922 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
923
924 // Otherwise, if we haven't widened the IV, check if the new iteration
925 // variable might overflow. In this case, we need to version the loop, and
926 // select the original version at runtime if the iteration space is too
927 // large.
928 OverflowResult OR = checkOverflow(FI, DT, AC);
931 LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
932 return false;
933 } else if (OR == OverflowResult::MayOverflow) {
934 Module *M = FI.OuterLoop->getHeader()->getParent()->getParent();
935 const DataLayout &DL = M->getDataLayout();
936 if (!FI.Opts.loop_flatten_version_loops) {
937 LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
938 return false;
939 } else if (!DL.isLegalInteger(
940 FI.OuterTripCount->getType()->getScalarSizeInBits())) {
941 // If the trip count type isn't legal then it won't be possible to check
942 // for overflow using only a single multiply instruction, so don't
943 // flatten.
945 dbgs() << "Can't check overflow efficiently, not flattening\n");
946 return false;
947 }
948 LLVM_DEBUG(dbgs() << "Multiply might overflow, versioning loop\n");
949
950 // Version the loop. The overflow check isn't a runtime pointer check, so we
951 // pass an empty list of runtime pointer checks, causing LoopVersioning to
952 // emit 'false' as the branch condition, and add our own check afterwards.
953 BasicBlock *CheckBlock = FI.OuterLoop->getLoopPreheader();
954 ArrayRef<RuntimePointerCheck> Checks(nullptr, nullptr);
955 LoopVersioning LVer(LAI, Checks, FI.OuterLoop, LI, DT, SE, MSSAU);
956 LVer.versionLoop();
957
958 // Check for overflow by calculating the new tripcount using
959 // umul_with_overflow and then checking if it overflowed.
960 CondBrInst *Br = cast<CondBrInst>(CheckBlock->getTerminator());
961 assert(match(Br->getCondition(), m_Zero()) &&
962 "Expected branch condition to be false");
963 IRBuilder<> Builder(Br);
964 Value *Call = Builder.CreateIntrinsic(
965 Intrinsic::umul_with_overflow, FI.OuterTripCount->getType(),
966 {FI.OuterTripCount, FI.InnerTripCount},
967 /*FMFSource=*/nullptr, "flatten.mul");
968 FI.NewTripCount = Builder.CreateExtractValue(Call, 0, "flatten.tripcount");
969 Value *Overflow = Builder.CreateExtractValue(Call, 1, "flatten.overflow");
970 Br->setCondition(Overflow);
971 } else {
972 LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
973 }
974
975 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
976}
977
980 LPMUpdater &U) {
981
982 bool Changed = false;
983
984 std::optional<MemorySSAUpdater> MSSAU;
985 if (AR.MSSA) {
986 MSSAU = MemorySSAUpdater(AR.MSSA);
987 if (VerifyMemorySSA)
988 AR.MSSA->verifyMemorySSA();
989 }
990
991 // The loop flattening pass requires loops to be
992 // in simplified form, and also needs LCSSA. Running
993 // this pass will simplify all loops that contain inner loops,
994 // regardless of whether anything ends up being flattened.
995 LoopAccessInfoManager LAIM(AR.SE, AR.AA, AR.DT, AR.LI, &AR.TTI, nullptr,
996 &AR.AC);
997 for (Loop *InnerLoop : LN.getLoops()) {
998 auto *OuterLoop = InnerLoop->getParentLoop();
999 if (!OuterLoop)
1000 continue;
1001 FlattenInfo FI(OuterLoop, InnerLoop);
1002 Changed |=
1003 FlattenLoopPair(FI, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
1004 MSSAU ? &*MSSAU : nullptr, LAIM.getInfo(*OuterLoop));
1005 }
1006
1007 if (!Changed)
1008 return PreservedAnalyses::all();
1009
1010 if (AR.MSSA && VerifyMemorySSA)
1011 AR.MSSA->verifyMemorySSA();
1012
1013 auto PA = getLoopPassPreservedAnalyses();
1014 if (AR.MSSA)
1015 PA.preserve<MemorySSAAnalysis>();
1016 return PA;
1017}
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 findLoopComponents(Loop *L, SmallPtrSetImpl< Instruction * > &IterationInstructions, PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, CondBrInst *&BackBranch, ScalarEvolution *SE, bool IsWidened)
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 bool verifyTripCount(Value *RHS, Loop *L, SmallPtrSetImpl< Instruction * > &IterationInstructions, PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, CondBrInst *&BackBranch, ScalarEvolution *SE, bool IsWidened)
static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, AssumptionCache *AC)
static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI)
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:119
This pass exposes codegen information to IR-level passes.
virt reg Virtual Register Rewriter
Value * RHS
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:515
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; assumes that the block is well-formed.
Definition BasicBlock.h:237
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Conditional Branch instruction.
void setCondition(Value *V)
Value * getCondition() const
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:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
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:2918
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 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.
LLVM_ABI 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:950
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,...
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:695
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
StringRef getName() const
Definition LoopInfo.h:415
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
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:68
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.
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 void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
size_type size() const
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:222
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
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_Value()
Match an arbitrary value and ignore it.
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.
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.
@ 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.
@ 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
LLVM_ABI 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 ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:209
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=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:626
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
@ Global
Append to llvm.global_dtors.
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
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:2035
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.
@ 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.