LLVM 24.0.0git
LoopConstrainer.cpp
Go to the documentation of this file.
10
11using namespace llvm;
12
13static const char *ClonedLoopTag = "loop_constrainer.loop.clone";
14
15#define DEBUG_TYPE "loop-constrainer"
16
19 const SCEV *Start, const SCEV *Bound) {
20 // First, try to prove the predicate without applying loop guards.
21 if (SE.isLoopEntryGuardedByCond(L, Pred, Start, Bound))
22 return true;
23 // Otherwise, try again with loop guards applied to the SCEVs.
24 auto StartLG = SE.applyLoopGuards(Start, L);
25 auto BoundLG = SE.applyLoopGuards(Bound, L);
26 return SE.isLoopEntryGuardedByCond(L, Pred, StartLG, BoundLG);
27}
28
29/// Given a loop with an deccreasing induction variable, is it possible to
30/// safely calculate the bounds of a new loop using the given Predicate.
31static bool isSafeDecreasingBound(const SCEV *Start, const SCEV *BoundSCEV,
32 const SCEV *Step, ICmpInst::Predicate Pred,
33 unsigned LatchBrExitIdx, Loop *L,
34 ScalarEvolution &SE) {
35 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
36 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
37 return false;
38
39 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
40 return false;
41
42 assert(SE.isKnownNegative(Step) && "expecting negative step");
43
44 LLVM_DEBUG(dbgs() << "isSafeDecreasingBound with:\n");
45 LLVM_DEBUG(dbgs() << "Start: " << *Start << "\n");
46 LLVM_DEBUG(dbgs() << "Step: " << *Step << "\n");
47 LLVM_DEBUG(dbgs() << "BoundSCEV: " << *BoundSCEV << "\n");
48 LLVM_DEBUG(dbgs() << "Pred: " << Pred << "\n");
49 LLVM_DEBUG(dbgs() << "LatchExitBrIdx: " << LatchBrExitIdx << "\n");
50
51 bool IsSigned = ICmpInst::isSigned(Pred);
52 // The predicate that we need to check that the induction variable lies
53 // within bounds.
54 ICmpInst::Predicate BoundPred =
56
57 if (LatchBrExitIdx == 1)
58 return isLoopEntryGuardedByCond(SE, L, BoundPred, Start, BoundSCEV);
59
60 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be either 0 or 1");
61
62 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
63 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
66 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
67
68 const SCEV *MinusOne =
69 SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType()));
70
71 return isLoopEntryGuardedByCond(SE, L, BoundPred, Start, MinusOne) &&
72 isLoopEntryGuardedByCond(SE, L, BoundPred, BoundSCEV, Limit);
73}
74
75/// Given a loop with an increasing induction variable, is it possible to
76/// safely calculate the bounds of a new loop using the given Predicate.
77static bool isSafeIncreasingBound(const SCEV *Start, const SCEV *BoundSCEV,
78 const SCEV *Step, ICmpInst::Predicate Pred,
79 unsigned LatchBrExitIdx, Loop *L,
80 ScalarEvolution &SE) {
81 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
82 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
83 return false;
84
85 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
86 return false;
87
88 LLVM_DEBUG(dbgs() << "isSafeIncreasingBound with:\n");
89 LLVM_DEBUG(dbgs() << "Start: " << *Start << "\n");
90 LLVM_DEBUG(dbgs() << "Step: " << *Step << "\n");
91 LLVM_DEBUG(dbgs() << "BoundSCEV: " << *BoundSCEV << "\n");
92 LLVM_DEBUG(dbgs() << "Pred: " << Pred << "\n");
93 LLVM_DEBUG(dbgs() << "LatchExitBrIdx: " << LatchBrExitIdx << "\n");
94
95 bool IsSigned = ICmpInst::isSigned(Pred);
96 // The predicate that we need to check that the induction variable lies
97 // within bounds.
98 ICmpInst::Predicate BoundPred =
100
101 if (LatchBrExitIdx == 1)
102 return isLoopEntryGuardedByCond(SE, L, BoundPred, Start, BoundSCEV);
103
104 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
105
106 const SCEV *StepMinusOne = SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
107 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
108 APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth)
110 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
111
112 return (isLoopEntryGuardedByCond(SE, L, BoundPred, Start,
113 SE.getAddExpr(BoundSCEV, Step)) &&
114 isLoopEntryGuardedByCond(SE, L, BoundPred, BoundSCEV, Limit));
115}
116
117/// Returns estimate for max latch taken count of the loop of the narrowest
118/// available type. If the latch block has such estimate, it is returned.
119/// Otherwise, we use max exit count of whole loop (that is potentially of wider
120/// type than latch check itself), which is still better than no estimate.
122 const Loop &L) {
123 const SCEV *FromBlock =
124 SE.getExitCount(&L, L.getLoopLatch(), ScalarEvolution::SymbolicMaximum);
125 if (isa<SCEVCouldNotCompute>(FromBlock))
127 return FromBlock;
128}
129
130std::optional<LoopStructure>
132 bool AllowUnsignedLatchCond,
133 const char *&FailureReason) {
134 if (!L.isLoopSimplifyForm()) {
135 FailureReason = "loop not in LoopSimplify form";
136 return std::nullopt;
137 }
138
139 BasicBlock *Latch = L.getLoopLatch();
140 assert(Latch && "Simplified loops only have one latch!");
141
142 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
143 FailureReason = "loop has already been cloned";
144 return std::nullopt;
145 }
146
147 if (!L.isLoopExiting(Latch)) {
148 FailureReason = "no loop latch";
149 return std::nullopt;
150 }
151
152 BasicBlock *Header = L.getHeader();
153 BasicBlock *Preheader = L.getLoopPreheader();
154 if (!Preheader) {
155 FailureReason = "no preheader";
156 return std::nullopt;
157 }
158
159 CondBrInst *LatchBr = dyn_cast<CondBrInst>(Latch->getTerminator());
160 if (!LatchBr) {
161 FailureReason = "latch terminator not conditional branch";
162 return std::nullopt;
163 }
164
165 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
166
167 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
168 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
169 FailureReason = "latch terminator branch not conditional on integral icmp";
170 return std::nullopt;
171 }
172
173 const SCEV *MaxBETakenCount = getNarrowestLatchMaxTakenCountEstimate(SE, L);
174 if (isa<SCEVCouldNotCompute>(MaxBETakenCount)) {
175 FailureReason = "could not compute latch count";
176 return std::nullopt;
177 }
178 assert(SE.getLoopDisposition(MaxBETakenCount, &L) ==
180 "loop variant exit count doesn't make sense!");
181
182 ICmpInst::Predicate Pred = ICI->getPredicate();
183 Value *LeftValue = ICI->getOperand(0);
184 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
185 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
186
187 Value *RightValue = ICI->getOperand(1);
188 const SCEV *RightSCEV = SE.getSCEV(RightValue);
189
190 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
191 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
192 if (isa<SCEVAddRecExpr>(RightSCEV)) {
193 std::swap(LeftSCEV, RightSCEV);
194 std::swap(LeftValue, RightValue);
196 } else {
197 FailureReason = "no add recurrences in the icmp";
198 return std::nullopt;
199 }
200 }
201
202 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
203 if (AR->hasNoSignedWrap())
204 return true;
205
206 IntegerType *Ty = cast<IntegerType>(AR->getType());
207 IntegerType *WideTy =
208 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
209
210 const SCEVAddRecExpr *ExtendAfterOp =
212 if (ExtendAfterOp) {
213 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
214 const SCEV *ExtendedStep =
215 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
216
217 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
218 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
219
220 if (NoSignedWrap)
221 return true;
222 }
223
224 // We may have proved this when computing the sign extension above.
225 return AR->hasNoSignedWrap();
226 };
227
228 // `ICI` is interpreted as taking the backedge if the *next* value of the
229 // induction variable satisfies some constraint.
230
232 if (IndVarBase->getLoop() != &L) {
233 FailureReason = "LHS in cmp is not an AddRec for this loop";
234 return std::nullopt;
235 }
236 if (!IndVarBase->isAffine()) {
237 FailureReason = "LHS in icmp not induction variable";
238 return std::nullopt;
239 }
240 const SCEV *StepRec = IndVarBase->getStepRecurrence(SE);
241 if (!isa<SCEVConstant>(StepRec)) {
242 FailureReason = "LHS in icmp not induction variable";
243 return std::nullopt;
244 }
245 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
246
247 if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
248 FailureReason = "LHS in icmp needs nsw for equality predicates";
249 return std::nullopt;
250 }
251
252 assert(!StepCI->isZero() && "Zero step?");
253 bool IsIncreasing = !StepCI->isNegative();
255 const SCEV *StartNext = IndVarBase->getStart();
256 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
257 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
258 const SCEV *Step = SE.getSCEV(StepCI);
259
260 const SCEV *FixedRightSCEV = nullptr;
261
262 // If RightValue resides within loop (but still being loop invariant),
263 // regenerate it as preheader.
264 if (auto *I = dyn_cast<Instruction>(RightValue))
265 if (L.contains(I->getParent()))
266 FixedRightSCEV = RightSCEV;
267
268 if (IsIncreasing) {
269 bool DecreasedRightValueByOne = false;
270 if (StepCI->isOne()) {
271 // Try to turn eq/ne predicates to those we can work with.
272 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
273 // while (++i != len) { while (++i < len) {
274 // ... ---> ...
275 // } }
276 // If both parts are known non-negative, it is profitable to use
277 // unsigned comparison in increasing loop. This allows us to make the
278 // comparison check against "RightSCEV + 1" more optimistic.
280 isKnownNonNegativeInLoop(RightSCEV, &L, SE))
281 Pred = ICmpInst::ICMP_ULT;
282 else
283 Pred = ICmpInst::ICMP_SLT;
284 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
285 // while (true) { while (true) {
286 // if (++i == len) ---> if (++i > len - 1)
287 // break; break;
288 // ... ...
289 // } }
290 if (IndVarBase->hasNoUnsignedWrap() &&
291 cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/ false)) {
292 Pred = ICmpInst::ICMP_UGT;
293 RightSCEV =
294 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
295 DecreasedRightValueByOne = true;
296 } else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/ true)) {
297 Pred = ICmpInst::ICMP_SGT;
298 RightSCEV =
299 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
300 DecreasedRightValueByOne = true;
301 }
302 }
303 }
304
305 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
306 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
307 bool FoundExpectedPred =
308 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
309
310 if (!FoundExpectedPred) {
311 FailureReason = "expected icmp slt semantically, found something else";
312 return std::nullopt;
313 }
314
316 if (!IsSignedPredicate && !AllowUnsignedLatchCond) {
317 FailureReason = "unsigned latch conditions are explicitly prohibited";
318 return std::nullopt;
319 }
320
321 if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
322 LatchBrExitIdx, &L, SE)) {
323 FailureReason = "Unsafe loop bounds";
324 return std::nullopt;
325 }
326 if (LatchBrExitIdx == 0) {
327 // We need to increase the right value unless we have already decreased
328 // it virtually when we replaced EQ with SGT.
329 if (!DecreasedRightValueByOne)
330 FixedRightSCEV =
331 SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
332 } else {
333 assert(!DecreasedRightValueByOne &&
334 "Right value can be decreased only for LatchBrExitIdx == 0!");
335 }
336 } else {
337 bool IncreasedRightValueByOne = false;
338 if (StepCI->isMinusOne()) {
339 // Try to turn eq/ne predicates to those we can work with.
340 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
341 // while (--i != len) { while (--i > len) {
342 // ... ---> ...
343 // } }
344 // We intentionally don't turn the predicate into UGT even if we know
345 // that both operands are non-negative, because it will only pessimize
346 // our check against "RightSCEV - 1".
347 Pred = ICmpInst::ICMP_SGT;
348 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
349 // while (true) { while (true) {
350 // if (--i == len) ---> if (--i < len + 1)
351 // break; break;
352 // ... ...
353 // } }
354 if (IndVarBase->hasNoUnsignedWrap() &&
355 cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
356 Pred = ICmpInst::ICMP_ULT;
357 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
358 IncreasedRightValueByOne = true;
359 } else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
360 Pred = ICmpInst::ICMP_SLT;
361 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
362 IncreasedRightValueByOne = true;
363 }
364 }
365 }
366
367 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
368 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
369
370 bool FoundExpectedPred =
371 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
372
373 if (!FoundExpectedPred) {
374 FailureReason = "expected icmp sgt semantically, found something else";
375 return std::nullopt;
376 }
377
379 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
380
381 if (!IsSignedPredicate && !AllowUnsignedLatchCond) {
382 FailureReason = "unsigned latch conditions are explicitly prohibited";
383 return std::nullopt;
384 }
385
386 if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
387 LatchBrExitIdx, &L, SE)) {
388 FailureReason = "Unsafe bounds";
389 return std::nullopt;
390 }
391
392 if (LatchBrExitIdx == 0) {
393 // We need to decrease the right value unless we have already increased
394 // it virtually when we replaced EQ with SLT.
395 if (!IncreasedRightValueByOne)
396 FixedRightSCEV =
397 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
398 } else {
399 assert(!IncreasedRightValueByOne &&
400 "Right value can be increased only for LatchBrExitIdx == 0!");
401 }
402 }
403 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
404
405 assert(!L.contains(LatchExit) && "expected an exit block!");
406 SCEVExpander Expander(SE, "loop-constrainer");
407 Instruction *Ins = Preheader->getTerminator();
408
409 if (FixedRightSCEV)
410 RightValue =
411 Expander.expandCodeFor(FixedRightSCEV, FixedRightSCEV->getType(), Ins);
412
413 Value *IndVarStartV = Expander.expandCodeFor(IndVarStart, IndVarTy, Ins);
414 IndVarStartV->setName("indvar.start");
415
416 LoopStructure Result;
417
418 Result.Tag = "main";
419 Result.Header = Header;
420 Result.Latch = Latch;
421 Result.LatchBr = LatchBr;
422 Result.LatchExit = LatchExit;
423 Result.LatchBrExitIdx = LatchBrExitIdx;
424 Result.IndVarStart = IndVarStartV;
425 Result.IndVarStep = StepCI;
426 Result.IndVarBase = LeftValue;
427 Result.IndVarIncreasing = IsIncreasing;
428 Result.LoopExitAt = RightValue;
429 Result.IsSignedPredicate = IsSignedPredicate;
430 Result.ExitCountTy = cast<IntegerType>(MaxBETakenCount->getType());
431
432 FailureReason = nullptr;
433
434 return Result;
435}
436
437// Add metadata to the loop L to disable loop optimizations. Callers need to
438// confirm that optimizing loop L is not beneficial.
440 // We do not care about any existing loopID related metadata for L, since we
441 // are setting all loop metadata to false.
442 LLVMContext &Context = L.getHeader()->getContext();
443 // Reserve first location for self reference to the LoopID metadata node.
444 MDNode *Dummy = MDNode::get(Context, {});
445 MDNode *DisableUnroll = MDNode::get(
446 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
447 Metadata *FalseVal =
448 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
449 MDNode *DisableVectorize = MDNode::get(
450 Context,
451 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
452 MDNode *DisableLICMVersioning = MDNode::get(
453 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
454 MDNode *DisableDistribution = MDNode::get(
455 Context, {MDString::get(Context, "llvm.loop.distribute.disable")});
456 MDNode *NewLoopID =
457 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
458 DisableLICMVersioning, DisableDistribution});
459 // Set operand 0 to refer to the loop id itself.
460 NewLoopID->replaceOperandWith(0, NewLoopID);
461 L.setLoopID(NewLoopID);
462}
463
465 function_ref<void(Loop *, bool)> LPMAddNewLoop,
466 const LoopStructure &LS, ScalarEvolution &SE,
467 DominatorTree &DT, Type *T, SubRanges SR)
468 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
469 DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L), RangeTy(T),
470 MainLoopStructure(LS), SR(SR) {}
471
472void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
473 const char *Tag) const {
474 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
475 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
476 Result.Blocks.push_back(Clone);
477 Result.Map[BB] = Clone;
478 }
479
480 auto GetClonedValue = [&Result](Value *V) {
481 assert(V && "null values not in domain!");
482 auto It = Result.Map.find(V);
483 if (It == Result.Map.end())
484 return V;
485 return static_cast<Value *>(It->second);
486 };
487
488 auto *ClonedLatch =
489 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
490 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
491 MDNode::get(Ctx, {}));
492
493 Result.Structure = MainLoopStructure.map(GetClonedValue);
494 Result.Structure.Tag = Tag;
495
496 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
497 BasicBlock *ClonedBB = Result.Blocks[i];
498 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
499
500 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
501
502 for (Instruction &I : *ClonedBB)
505
506 // Exit blocks will now have one more predecessor and their PHI nodes need
507 // to be edited to reflect that. No phi nodes need to be introduced because
508 // the loop is in LCSSA.
509
510 for (auto *SBB : successors(OriginalBB)) {
511 if (OriginalLoop.contains(SBB))
512 continue; // not an exit block
513
514 for (PHINode &PN : SBB->phis()) {
515 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
516 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
517 SE.forgetLcssaPhiWithNewPredecessor(&OriginalLoop, &PN);
518 }
519 }
520 }
521}
522
523LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
524 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
525 BasicBlock *ContinuationBlock) const {
526 // We start with a loop with a single latch:
527 //
528 // +--------------------+
529 // | |
530 // | preheader |
531 // | |
532 // +--------+-----------+
533 // | ----------------\
534 // | / |
535 // +--------v----v------+ |
536 // | | |
537 // | header | |
538 // | | |
539 // +--------------------+ |
540 // |
541 // ..... |
542 // |
543 // +--------------------+ |
544 // | | |
545 // | latch >----------/
546 // | |
547 // +-------v------------+
548 // |
549 // |
550 // | +--------------------+
551 // | | |
552 // +---> original exit |
553 // | |
554 // +--------------------+
555 //
556 // We change the control flow to look like
557 //
558 //
559 // +--------------------+
560 // | |
561 // | preheader >-------------------------+
562 // | | |
563 // +--------v-----------+ |
564 // | /-------------+ |
565 // | / | |
566 // +--------v--v--------+ | |
567 // | | | |
568 // | header | | +--------+ |
569 // | | | | | |
570 // +--------------------+ | | +-----v-----v-----------+
571 // | | | |
572 // | | | .pseudo.exit |
573 // | | | |
574 // | | +-----------v-----------+
575 // | | |
576 // ..... | | |
577 // | | +--------v-------------+
578 // +--------------------+ | | | |
579 // | | | | | ContinuationBlock |
580 // | latch >------+ | | |
581 // | | | +----------------------+
582 // +---------v----------+ |
583 // | |
584 // | |
585 // | +---------------^-----+
586 // | | |
587 // +-----> .exit.selector |
588 // | |
589 // +----------v----------+
590 // |
591 // +--------------------+ |
592 // | | |
593 // | original exit <----+
594 // | |
595 // +--------------------+
596
597 RewrittenRangeInfo RRI;
598
599 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
600 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
601 &F, BBInsertLocation);
602 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
603 BBInsertLocation);
604
605 Instruction *PreheaderJump = Preheader->getTerminator();
606 bool Increasing = LS.IndVarIncreasing;
607 bool IsSignedPredicate = LS.IsSignedPredicate;
608
609 IRBuilder<> B(PreheaderJump);
610 auto NoopOrExt = [&](Value *V) {
611 if (V->getType() == RangeTy)
612 return V;
613 return IsSignedPredicate ? B.CreateSExt(V, RangeTy, "wide." + V->getName())
614 : B.CreateZExt(V, RangeTy, "wide." + V->getName());
615 };
616
617 // EnterLoopCond - is it okay to start executing this `LS'?
618 Value *EnterLoopCond = nullptr;
619 auto Pred =
620 Increasing
621 ? (IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT)
622 : (IsSignedPredicate ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
623 Value *IndVarStart = NoopOrExt(LS.IndVarStart);
624 EnterLoopCond = B.CreateICmp(Pred, IndVarStart, ExitSubloopAt);
625
626 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
627 PreheaderJump->eraseFromParent();
628
629 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
630 B.SetInsertPoint(LS.LatchBr);
631 Value *IndVarBase = NoopOrExt(LS.IndVarBase);
632 Value *TakeBackedgeLoopCond = B.CreateICmp(Pred, IndVarBase, ExitSubloopAt);
633
634 Value *CondForBranch = LS.LatchBrExitIdx == 1
635 ? TakeBackedgeLoopCond
636 : B.CreateNot(TakeBackedgeLoopCond);
637
638 LS.LatchBr->setCondition(CondForBranch);
639
640 B.SetInsertPoint(RRI.ExitSelector);
641
642 // IterationsLeft - are there any more iterations left, given the original
643 // upper bound on the induction variable? If not, we branch to the "real"
644 // exit.
645 Value *LoopExitAt = NoopOrExt(LS.LoopExitAt);
646 Value *IterationsLeft = B.CreateICmp(Pred, IndVarBase, LoopExitAt);
647 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
648
649 UncondBrInst *BranchToContinuation =
650 UncondBrInst::Create(ContinuationBlock, RRI.PseudoExit);
651
652 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
653 // each of the PHI nodes in the loop header. This feeds into the initial
654 // value of the same PHI nodes if/when we continue execution.
655 for (PHINode &PN : LS.Header->phis()) {
656 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
657 BranchToContinuation->getIterator());
658
659 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
660 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
661 RRI.ExitSelector);
662 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
663 }
664
665 RRI.IndVarEnd = PHINode::Create(IndVarBase->getType(), 2, "indvar.end",
666 BranchToContinuation->getIterator());
667 RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
668 RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
669
670 // The latch exit now has a branch from `RRI.ExitSelector' instead of
671 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
672 LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector);
673
674 return RRI;
675}
676
677void LoopConstrainer::rewriteIncomingValuesForPHIs(
678 LoopStructure &LS, BasicBlock *ContinuationBlock,
679 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
680 unsigned PHIIndex = 0;
681 for (PHINode &PN : LS.Header->phis())
682 PN.setIncomingValueForBlock(ContinuationBlock,
683 RRI.PHIValuesAtPseudoExit[PHIIndex++]);
684
685 LS.IndVarStart = RRI.IndVarEnd;
686}
687
688BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
689 BasicBlock *OldPreheader,
690 const char *Tag) const {
691 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
692 UncondBrInst::Create(LS.Header, Preheader);
693
694 LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
695
696 return Preheader;
697}
698
699void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
700 Loop *ParentLoop = OriginalLoop.getParentLoop();
701 if (!ParentLoop)
702 return;
703
704 for (BasicBlock *BB : BBs)
705 ParentLoop->addBasicBlockToLoop(BB, LI);
706}
707
708Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
710 bool IsSubloop) {
711 Loop &New = *LI.AllocateLoop();
712 if (Parent)
713 Parent->addChildLoop(&New);
714 else
715 LI.addTopLevelLoop(&New);
716 LPMAddNewLoop(&New, IsSubloop);
717
718 // Add all of the blocks in Original to the new loop.
719 for (auto *BB : Original->blocks())
720 if (LI.getLoopFor(BB) == Original)
721 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
722
723 // Add all of the subloops to the new loop.
724 for (Loop *SubLoop : *Original)
725 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
726
727 return &New;
728}
729
731 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
732 assert(Preheader != nullptr && "precondition!");
733
734 OriginalPreheader = Preheader;
735 MainLoopPreheader = Preheader;
736 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
737 bool Increasing = MainLoopStructure.IndVarIncreasing;
738 IntegerType *IVTy = cast<IntegerType>(RangeTy);
739
740 SCEVExpander Expander(SE, "loop-constrainer");
741 Instruction *InsertPt = OriginalPreheader->getTerminator();
742
743 // It would have been better to make `PreLoop' and `PostLoop'
744 // `std::optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
745 // constructor.
746 ClonedLoop PreLoop, PostLoop;
747 bool NeedsPreLoop =
748 Increasing ? SR.LowLimit.has_value() : SR.HighLimit.has_value();
749 bool NeedsPostLoop =
750 Increasing ? SR.HighLimit.has_value() : SR.LowLimit.has_value();
751
752 Value *ExitPreLoopAt = nullptr;
753 Value *ExitMainLoopAt = nullptr;
754 const SCEVConstant *MinusOneS =
755 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
756
757 if (NeedsPreLoop) {
758 const SCEV *ExitPreLoopAtSCEV = nullptr;
759
760 if (Increasing)
761 ExitPreLoopAtSCEV = *SR.LowLimit;
762 else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
763 IsSignedPredicate))
764 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
765 else {
766 LLVM_DEBUG(dbgs() << "could not prove no-overflow when computing "
767 << "preloop exit limit. HighLimit = "
768 << *(*SR.HighLimit) << "\n");
769 return false;
770 }
771
772 if (!Expander.isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt)) {
773 LLVM_DEBUG(dbgs() << "could not prove that it is safe to expand the"
774 << " preloop exit limit " << *ExitPreLoopAtSCEV
775 << " at block " << InsertPt->getParent()->getName()
776 << "\n");
777 return false;
778 }
779
780 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
781 ExitPreLoopAt->setName("exit.preloop.at");
782 }
783
784 if (NeedsPostLoop) {
785 const SCEV *ExitMainLoopAtSCEV = nullptr;
786
787 if (Increasing)
788 ExitMainLoopAtSCEV = *SR.HighLimit;
789 else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
790 IsSignedPredicate))
791 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
792 else {
793 LLVM_DEBUG(dbgs() << "could not prove no-overflow when computing "
794 << "mainloop exit limit. LowLimit = "
795 << *(*SR.LowLimit) << "\n");
796 return false;
797 }
798
799 if (!Expander.isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt)) {
800 LLVM_DEBUG(dbgs() << "could not prove that it is safe to expand the"
801 << " main loop exit limit " << *ExitMainLoopAtSCEV
802 << " at block " << InsertPt->getParent()->getName()
803 << "\n");
804 return false;
805 }
806
807 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
808 ExitMainLoopAt->setName("exit.mainloop.at");
809 }
810
811 // We clone these ahead of time so that we don't have to deal with changing
812 // and temporarily invalid IR as we transform the loops.
813 if (NeedsPreLoop)
814 cloneLoop(PreLoop, "preloop");
815 if (NeedsPostLoop)
816 cloneLoop(PostLoop, "postloop");
817
818 RewrittenRangeInfo PreLoopRRI;
819
820 if (NeedsPreLoop) {
821 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
822 PreLoop.Structure.Header);
823
824 MainLoopPreheader =
825 createPreheader(MainLoopStructure, Preheader, "mainloop");
826 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
827 ExitPreLoopAt, MainLoopPreheader);
828 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
829 PreLoopRRI);
830 }
831
832 BasicBlock *PostLoopPreheader = nullptr;
833 RewrittenRangeInfo PostLoopRRI;
834
835 if (NeedsPostLoop) {
836 PostLoopPreheader =
837 createPreheader(PostLoop.Structure, Preheader, "postloop");
838 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
839 ExitMainLoopAt, PostLoopPreheader);
840 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
841 PostLoopRRI);
842 }
843
844 BasicBlock *NewMainLoopPreheader =
845 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
846 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
847 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
848 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
849
850 // Some of the above may be nullptr, filter them out before passing to
851 // addToParentLoopIfNeeded.
852 auto NewBlocksEnd =
853 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
854
855 addToParentLoopIfNeeded(ArrayRef(std::begin(NewBlocks), NewBlocksEnd));
856
857 DT.recalculate(F);
858
859 // We need to first add all the pre and post loop blocks into the loop
860 // structures (as part of createClonedLoopStructure), and then update the
861 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
862 // LI when LoopSimplifyForm is generated.
863 Loop *PreL = nullptr, *PostL = nullptr;
864 if (!PreLoop.Blocks.empty()) {
865 PreL = createClonedLoopStructure(&OriginalLoop,
866 OriginalLoop.getParentLoop(), PreLoop.Map,
867 /* IsSubLoop */ false);
868 }
869
870 if (!PostLoop.Blocks.empty()) {
871 PostL =
872 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
873 PostLoop.Map, /* IsSubLoop */ false);
874 }
875
876 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
877 auto CanonicalizeLoop = [&](Loop *L, bool IsOriginalLoop) {
878 formLCSSARecursively(*L, DT, &LI, &SE);
879 simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, true);
880 // Pre/post loops are slow paths, we do not need to perform any loop
881 // optimizations on them.
882 if (!IsOriginalLoop)
884 };
885 if (PreL)
886 CanonicalizeLoop(PreL, false);
887 if (PostL)
888 CanonicalizeLoop(PostL, false);
889 CanonicalizeLoop(&OriginalLoop, true);
890
891 /// At this point:
892 /// - We've broken a "main loop" out of the loop in a way that the "main loop"
893 /// runs with the induction variable in a subset of [Begin, End).
894 /// - There is no overflow when computing "main loop" exit limit.
895 /// - Max latch taken count of the loop is limited.
896 /// It guarantees that induction variable will not overflow iterating in the
897 /// "main loop".
898 if (isa<OverflowingBinaryOperator>(MainLoopStructure.IndVarBase))
899 if (IsSignedPredicate)
900 cast<BinaryOperator>(MainLoopStructure.IndVarBase)
901 ->setHasNoSignedWrap(true);
902 /// TODO: support unsigned predicate.
903 /// To add NUW flag we need to prove that both operands of BO are
904 /// non-negative. E.g:
905 /// ...
906 /// %iv.next = add nsw i32 %iv, -1
907 /// %cmp = icmp ult i32 %iv.next, %n
908 /// br i1 %cmp, label %loopexit, label %loop
909 ///
910 /// -1 is MAX_UINT in terms of unsigned int. Adding anything but zero will
911 /// overflow, therefore NUW flag is not legal here.
912
913 return true;
914}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static const char * ClonedLoopTag
static bool isLoopEntryGuardedByCond(ScalarEvolution &SE, Loop *L, ICmpInst::Predicate Pred, const SCEV *Start, const SCEV *Bound)
static const SCEV * getNarrowestLatchMaxTakenCountEstimate(ScalarEvolution &SE, const Loop &L)
Returns estimate for max latch taken count of the loop of the narrowest available type.
static bool isSafeDecreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an deccreasing induction variable, is it possible to safely calculate the bounds of...
static void DisableAllLoopOptsOnLoop(Loop &L)
static bool isSafeIncreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an increasing induction variable, is it possible to safely calculate the bounds of ...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
#define LLVM_DEBUG(...)
Definition Debug.h:119
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Conditional Branch instruction.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isNegative() const
Definition Constants.h:214
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LLVM_ABI LoopConstrainer(Loop &L, LoopInfo &LI, function_ref< void(Loop *, bool)> LPMAddNewLoop, const LoopStructure &LS, ScalarEvolution &SE, DominatorTree &DT, Type *T, SubRanges SR)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
Root of the metadata hierarchy.
Definition Metadata.h:64
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
This node represents a polynomial recurrence on the trip count of the specified loop.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
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 * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
@ LoopInvariant
The SCEV is loop-invariant.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:450
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned max.
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned min.
LLVM_ABI bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
LoopStructure()=default
static LLVM_ABI std::optional< LoopStructure > parseLoopStructure(ScalarEvolution &, Loop &, bool, const char *&)