LLVM 22.0.0git
LoopRotationUtils.cpp
Go to the documentation of this file.
1//===----------------- LoopRotationUtils.cpp -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides utilities to convert a loop into a loop with bottom test.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/Statistic.h"
24#include "llvm/IR/CFG.h"
25#include "llvm/IR/DebugInfo.h"
26#include "llvm/IR/Dominators.h"
28#include "llvm/IR/MDBuilder.h"
31#include "llvm/Support/Debug.h"
38using namespace llvm;
39
40#define DEBUG_TYPE "loop-rotate"
41
42STATISTIC(NumNotRotatedDueToHeaderSize,
43 "Number of loops not rotated due to the header size");
44STATISTIC(NumInstrsHoisted,
45 "Number of instructions hoisted into loop preheader");
46STATISTIC(NumInstrsDuplicated,
47 "Number of instructions cloned into loop preheader");
48STATISTIC(NumRotated, "Number of loops rotated");
49
50static cl::opt<bool>
51 MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
52 cl::desc("Allow loop rotation multiple times in order to reach "
53 "a better latch exit"));
54
55// Probability that a rotated loop has zero trip count / is never entered.
56static constexpr uint32_t ZeroTripCountWeights[] = {1, 127};
57
58namespace {
59/// A simple loop rotation transformation.
60class LoopRotate {
61 const unsigned MaxHeaderSize;
62 LoopInfo *LI;
65 DominatorTree *DT;
67 MemorySSAUpdater *MSSAU;
68 const SimplifyQuery &SQ;
69 bool RotationOnly;
70 bool IsUtilMode;
71 bool PrepareForLTO;
72
73public:
74 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
77 const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
78 bool PrepareForLTO)
79 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
80 MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
81 IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
82 bool processLoop(Loop *L);
83
84private:
85 bool rotateLoop(Loop *L, bool SimplifiedLatch);
86 bool simplifyLoopLatch(Loop *L);
87};
88} // end anonymous namespace
89
90/// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
91/// previously exist in the map, and the value was inserted.
93 bool Inserted = VM.insert({K, V}).second;
94 assert(Inserted);
95 (void)Inserted;
96}
97/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
98/// old header into the preheader. If there were uses of the values produced by
99/// these instruction that were outside of the loop, we have to insert PHI nodes
100/// to merge the two values. Do this now.
102 BasicBlock *OrigPreheader,
104 ScalarEvolution *SE,
105 SmallVectorImpl<PHINode*> *InsertedPHIs) {
106 // Remove PHI node entries that are no longer live.
107 BasicBlock::iterator I, E = OrigHeader->end();
108 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
109 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
110
111 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
112 // as necessary.
113 SSAUpdater SSA(InsertedPHIs);
114 for (I = OrigHeader->begin(); I != E; ++I) {
115 Value *OrigHeaderVal = &*I;
116
117 // If there are no uses of the value (e.g. because it returns void), there
118 // is nothing to rewrite.
119 if (OrigHeaderVal->use_empty())
120 continue;
121
122 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
123
124 // The value now exits in two versions: the initial value in the preheader
125 // and the loop "next" value in the original header.
126 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
127 // Force re-computation of OrigHeaderVal, as some users now need to use the
128 // new PHI node.
129 if (SE)
130 SE->forgetValue(OrigHeaderVal);
131 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
132 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
133
134 // Visit each use of the OrigHeader instruction.
135 for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
136 // SSAUpdater can't handle a non-PHI use in the same block as an
137 // earlier def. We can easily handle those cases manually.
138 Instruction *UserInst = cast<Instruction>(U.getUser());
139 if (!isa<PHINode>(UserInst)) {
140 BasicBlock *UserBB = UserInst->getParent();
141
142 // The original users in the OrigHeader are already using the
143 // original definitions.
144 if (UserBB == OrigHeader)
145 continue;
146
147 // Users in the OrigPreHeader need to use the value to which the
148 // original definitions are mapped.
149 if (UserBB == OrigPreheader) {
150 U = OrigPreHeaderVal;
151 continue;
152 }
153 }
154
155 // Anything else can be handled by SSAUpdater.
156 SSA.RewriteUse(U);
157 }
158
159 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
160 // intrinsics.
161 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
162 llvm::findDbgValues(OrigHeaderVal, DbgVariableRecords);
163
164 for (DbgVariableRecord *DVR : DbgVariableRecords) {
165 // The original users in the OrigHeader are already using the original
166 // definitions.
167 BasicBlock *UserBB = DVR->getMarker()->getParent();
168 if (UserBB == OrigHeader)
169 continue;
170
171 // Users in the OrigPreHeader need to use the value to which the
172 // original definitions are mapped and anything else can be handled by
173 // the SSAUpdater. To avoid adding PHINodes, check if the value is
174 // available in UserBB, if not substitute poison.
175 Value *NewVal;
176 if (UserBB == OrigPreheader)
177 NewVal = OrigPreHeaderVal;
178 else if (SSA.HasValueForBlock(UserBB))
179 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
180 else
181 NewVal = PoisonValue::get(OrigHeaderVal->getType());
182 DVR->replaceVariableLocationOp(OrigHeaderVal, NewVal);
183 }
184 }
185}
186
187// Assuming both header and latch are exiting, look for a phi which is only
188// used outside the loop (via a LCSSA phi) in the exit from the header.
189// This means that rotating the loop can remove the phi.
191 BasicBlock *Header = L->getHeader();
192 BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
193 assert(BI && BI->isConditional() && "need header with conditional exit");
194 BasicBlock *HeaderExit = BI->getSuccessor(0);
195 if (L->contains(HeaderExit))
196 HeaderExit = BI->getSuccessor(1);
197
198 for (auto &Phi : Header->phis()) {
199 // Look for uses of this phi in the loop/via exits other than the header.
200 if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
201 return cast<Instruction>(U)->getParent() != HeaderExit;
202 }))
203 continue;
204 return true;
205 }
206 return false;
207}
208
209// Check that latch exit is deoptimizing (which means - very unlikely to happen)
210// and there is another exit from the loop which is non-deoptimizing.
211// If we rotate latch to that exit our loop has a better chance of being fully
212// canonical.
213//
214// It can give false positives in some rare cases.
216 BasicBlock *Latch = L->getLoopLatch();
217 assert(Latch && "need latch");
218 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
219 // Need normal exiting latch.
220 if (!BI || !BI->isConditional())
221 return false;
222
223 BasicBlock *Exit = BI->getSuccessor(1);
224 if (L->contains(Exit))
225 Exit = BI->getSuccessor(0);
226
227 // Latch exit is non-deoptimizing, no need to rotate.
228 if (!Exit->getPostdominatingDeoptimizeCall())
229 return false;
230
232 L->getUniqueExitBlocks(Exits);
233 if (!Exits.empty()) {
234 // There is at least one non-deoptimizing exit.
235 //
236 // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
237 // as it can conservatively return false for deoptimizing exits with
238 // complex enough control flow down to deoptimize call.
239 //
240 // That means here we can report success for a case where
241 // all exits are deoptimizing but one of them has complex enough
242 // control flow (e.g. with loops).
243 //
244 // That should be a very rare case and false positives for this function
245 // have compile-time effect only.
246 return any_of(Exits, [](const BasicBlock *BB) {
248 });
249 }
250 return false;
251}
252
253static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
254 bool HasConditionalPreHeader,
255 bool SuccsSwapped) {
256 MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
257 if (WeightMD == nullptr)
258 return;
259
260 // LoopBI should currently be a clone of PreHeaderBI with the same
261 // metadata. But we double check to make sure we don't have a degenerate case
262 // where instsimplify changed the instructions.
263 if (WeightMD != getBranchWeightMDNode(LoopBI))
264 return;
265
267 extractFromBranchWeightMD32(WeightMD, Weights);
268 if (Weights.size() != 2)
269 return;
270 uint32_t OrigLoopExitWeight = Weights[0];
271 uint32_t OrigLoopBackedgeWeight = Weights[1];
272
273 if (SuccsSwapped)
274 std::swap(OrigLoopExitWeight, OrigLoopBackedgeWeight);
275
276 // Update branch weights. Consider the following edge-counts:
277 //
278 // | |-------- |
279 // V V | V
280 // Br i1 ... | Br i1 ...
281 // | | | | |
282 // x| y| | becomes: | y0| |-----
283 // V V | | V V |
284 // Exit Loop | | Loop |
285 // | | | Br i1 ... |
286 // ----- | | | |
287 // x0| x1| y1 | |
288 // V V ----
289 // Exit
290 //
291 // The following must hold:
292 // - x == x0 + x1 # counts to "exit" must stay the same.
293 // - y0 == x - x0 == x1 # how often loop was entered at all.
294 // - y1 == y - y0 # How often loop was repeated (after first iter.).
295 //
296 // We cannot generally deduce how often we had a zero-trip count loop so we
297 // have to make a guess for how to distribute x among the new x0 and x1.
298
299 uint32_t ExitWeight0; // aka x0
300 uint32_t ExitWeight1; // aka x1
301 uint32_t EnterWeight; // aka y0
302 uint32_t LoopBackWeight; // aka y1
303 if (OrigLoopExitWeight > 0 && OrigLoopBackedgeWeight > 0) {
304 ExitWeight0 = 0;
305 if (HasConditionalPreHeader) {
306 // Here we cannot know how many 0-trip count loops we have, so we guess:
307 if (OrigLoopBackedgeWeight >= OrigLoopExitWeight) {
308 // If the loop count is bigger than the exit count then we set
309 // probabilities as if 0-trip count nearly never happens.
310 ExitWeight0 = ZeroTripCountWeights[0];
311 // Scale up counts if necessary so we can match `ZeroTripCountWeights`
312 // for the `ExitWeight0`:`ExitWeight1` (aka `x0`:`x1` ratio`) ratio.
313 while (OrigLoopExitWeight < ZeroTripCountWeights[1] + ExitWeight0) {
314 // ... but don't overflow.
315 uint32_t const HighBit = uint32_t{1} << (sizeof(uint32_t) * 8 - 1);
316 if ((OrigLoopBackedgeWeight & HighBit) != 0 ||
317 (OrigLoopExitWeight & HighBit) != 0)
318 break;
319 OrigLoopBackedgeWeight <<= 1;
320 OrigLoopExitWeight <<= 1;
321 }
322 } else {
323 // If there's a higher exit-count than backedge-count then we set
324 // probabilities as if there are only 0-trip and 1-trip cases.
325 ExitWeight0 = OrigLoopExitWeight - OrigLoopBackedgeWeight;
326 }
327 } else {
328 // Theoretically, if the loop body must be executed at least once, the
329 // backedge count must be not less than exit count. However the branch
330 // weight collected by sampling-based PGO may be not very accurate due to
331 // sampling. Therefore this workaround is required here to avoid underflow
332 // of unsigned in following update of branch weight.
333 if (OrigLoopExitWeight > OrigLoopBackedgeWeight)
334 OrigLoopBackedgeWeight = OrigLoopExitWeight;
335 }
336 assert(OrigLoopExitWeight >= ExitWeight0 && "Bad branch weight");
337 ExitWeight1 = OrigLoopExitWeight - ExitWeight0;
338 EnterWeight = ExitWeight1;
339 assert(OrigLoopBackedgeWeight >= EnterWeight && "Bad branch weight");
340 LoopBackWeight = OrigLoopBackedgeWeight - EnterWeight;
341 } else if (OrigLoopExitWeight == 0) {
342 if (OrigLoopBackedgeWeight == 0) {
343 // degenerate case... keep everything zero...
344 ExitWeight0 = 0;
345 ExitWeight1 = 0;
346 EnterWeight = 0;
347 LoopBackWeight = 0;
348 } else {
349 // Special case "LoopExitWeight == 0" weights which behaves like an
350 // endless where we don't want loop-enttry (y0) to be the same as
351 // loop-exit (x1).
352 ExitWeight0 = 0;
353 ExitWeight1 = 0;
354 EnterWeight = 1;
355 LoopBackWeight = OrigLoopBackedgeWeight;
356 }
357 } else {
358 // loop is never entered.
359 assert(OrigLoopBackedgeWeight == 0 && "remaining case is backedge zero");
360 ExitWeight0 = 1;
361 ExitWeight1 = 1;
362 EnterWeight = 0;
363 LoopBackWeight = 0;
364 }
365
366 const uint32_t LoopBIWeights[] = {
367 SuccsSwapped ? LoopBackWeight : ExitWeight1,
368 SuccsSwapped ? ExitWeight1 : LoopBackWeight,
369 };
370 setBranchWeights(LoopBI, LoopBIWeights, /*IsExpected=*/false);
371 if (HasConditionalPreHeader) {
372 const uint32_t PreHeaderBIWeights[] = {
373 SuccsSwapped ? EnterWeight : ExitWeight0,
374 SuccsSwapped ? ExitWeight0 : EnterWeight,
375 };
376 setBranchWeights(PreHeaderBI, PreHeaderBIWeights, /*IsExpected=*/false);
377 }
378}
379
380/// Rotate loop LP. Return true if the loop is rotated.
381///
382/// \param SimplifiedLatch is true if the latch was just folded into the final
383/// loop exit. In this case we may want to rotate even though the new latch is
384/// now an exiting branch. This rotation would have happened had the latch not
385/// been simplified. However, if SimplifiedLatch is false, then we avoid
386/// rotating loops in which the latch exits to avoid excessive or endless
387/// rotation. LoopRotate should be repeatable and converge to a canonical
388/// form. This property is satisfied because simplifying the loop latch can only
389/// happen once across multiple invocations of the LoopRotate pass.
390///
391/// If -loop-rotate-multi is enabled we can do multiple rotations in one go
392/// so to reach a suitable (non-deoptimizing) exit.
393bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
394 // If the loop has only one block then there is not much to rotate.
395 if (L->getBlocks().size() == 1)
396 return false;
397
398 bool Rotated = false;
399 do {
400 BasicBlock *OrigHeader = L->getHeader();
401 BasicBlock *OrigLatch = L->getLoopLatch();
402
403 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
404 if (!BI || BI->isUnconditional())
405 return Rotated;
406
407 // If the loop header is not one of the loop exiting blocks then
408 // either this loop is already rotated or it is not
409 // suitable for loop rotation transformations.
410 if (!L->isLoopExiting(OrigHeader))
411 return Rotated;
412
413 // If the loop latch already contains a branch that leaves the loop then the
414 // loop is already rotated.
415 if (!OrigLatch)
416 return Rotated;
417
418 // Rotate if either the loop latch does *not* exit the loop, or if the loop
419 // latch was just simplified. Or if we think it will be profitable.
420 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
423 return Rotated;
424
425 // Check size of original header and reject loop if it is very big or we can't
426 // duplicate blocks inside it.
427 {
429 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
430
432 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
433 if (Metrics.notDuplicatable) {
435 dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
436 << " instructions: ";
437 L->dump());
438 return Rotated;
439 }
440 if (Metrics.Convergence != ConvergenceKind::None) {
441 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
442 "instructions: ";
443 L->dump());
444 return Rotated;
445 }
446 if (!Metrics.NumInsts.isValid()) {
447 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
448 " with invalid cost: ";
449 L->dump());
450 return Rotated;
451 }
452 if (Metrics.NumInsts > MaxHeaderSize) {
453 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
454 << Metrics.NumInsts
455 << " instructions, which is more than the threshold ("
456 << MaxHeaderSize << " instructions): ";
457 L->dump());
458 ++NumNotRotatedDueToHeaderSize;
459 return Rotated;
460 }
461
462 // When preparing for LTO, avoid rotating loops with calls that could be
463 // inlined during the LTO stage.
464 if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
465 return Rotated;
466 }
467
468 // Now, this loop is suitable for rotation.
469 BasicBlock *OrigPreheader = L->getLoopPreheader();
470
471 // If the loop could not be converted to canonical form, it must have an
472 // indirectbr in it, just give up.
473 if (!OrigPreheader || !L->hasDedicatedExits())
474 return Rotated;
475
476 // Anything ScalarEvolution may know about this loop or the PHI nodes
477 // in its header will soon be invalidated. We should also invalidate
478 // all outer loops because insertion and deletion of blocks that happens
479 // during the rotation may violate invariants related to backedge taken
480 // infos in them.
481 if (SE) {
482 SE->forgetTopmostLoop(L);
483 // We may hoist some instructions out of loop. In case if they were cached
484 // as "loop variant" or "loop computable", these caches must be dropped.
485 // We also may fold basic blocks, so cached block dispositions also need
486 // to be dropped.
487 SE->forgetBlockAndLoopDispositions();
488 }
489
490 LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
491 if (MSSAU && VerifyMemorySSA)
492 MSSAU->getMemorySSA()->verifyMemorySSA();
493
494 // Find new Loop header. NewHeader is a Header's one and only successor
495 // that is inside loop. Header's other successor is outside the
496 // loop. Otherwise loop is not suitable for rotation.
497 BasicBlock *Exit = BI->getSuccessor(0);
498 BasicBlock *NewHeader = BI->getSuccessor(1);
499 bool BISuccsSwapped = L->contains(Exit);
500 if (BISuccsSwapped)
501 std::swap(Exit, NewHeader);
502 assert(NewHeader && "Unable to determine new loop header");
503 assert(L->contains(NewHeader) && !L->contains(Exit) &&
504 "Unable to determine loop header and exit blocks");
505
506 // This code assumes that the new header has exactly one predecessor.
507 // Remove any single-entry PHI nodes in it.
508 assert(NewHeader->getSinglePredecessor() &&
509 "New header doesn't have one pred!");
510 FoldSingleEntryPHINodes(NewHeader);
511
512 // Begin by walking OrigHeader and populating ValueMap with an entry for
513 // each Instruction.
514 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
515 ValueToValueMapTy ValueMap, ValueMapMSSA;
516
517 // For PHI nodes, the value available in OldPreHeader is just the
518 // incoming value from OldPreHeader.
519 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
521 PN->getIncomingValueForBlock(OrigPreheader));
522
523 // For the rest of the instructions, either hoist to the OrigPreheader if
524 // possible or create a clone in the OldPreHeader if not.
525 Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
526
527 // Record all debug records preceding LoopEntryBranch to avoid
528 // duplication.
529 using DbgHash =
530 std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
531 auto makeHash = [](const DbgVariableRecord *D) -> DbgHash {
532 auto VarLocOps = D->location_ops();
533 return {{hash_combine_range(VarLocOps), D->getVariable()},
534 D->getExpression()};
535 };
536
537 SmallDenseSet<DbgHash, 8> DbgRecords;
538 // Build DbgVariableRecord hashes for DbgVariableRecords attached to the
539 // terminator.
540 for (const DbgVariableRecord &DVR :
541 filterDbgVars(OrigPreheader->getTerminator()->getDbgRecordRange()))
542 DbgRecords.insert(makeHash(&DVR));
543
544 // Remember the local noalias scope declarations in the header. After the
545 // rotation, they must be duplicated and the scope must be cloned. This
546 // avoids unwanted interaction across iterations.
547 SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
548 for (Instruction &I : *OrigHeader)
549 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
550 NoAliasDeclInstructions.push_back(Decl);
551
552 Module *M = OrigHeader->getModule();
553
554 // Track the next DbgRecord to clone. If we have a sequence where an
555 // instruction is hoisted instead of being cloned:
556 // DbgRecord blah
557 // %foo = add i32 0, 0
558 // DbgRecord xyzzy
559 // %bar = call i32 @foobar()
560 // where %foo is hoisted, then the DbgRecord "blah" will be seen twice, once
561 // attached to %foo, then when %foo his hoisted it will "fall down" onto the
562 // function call:
563 // DbgRecord blah
564 // DbgRecord xyzzy
565 // %bar = call i32 @foobar()
566 // causing it to appear attached to the call too.
567 //
568 // To avoid this, cloneDebugInfoFrom takes an optional "start cloning from
569 // here" position to account for this behaviour. We point it at any
570 // DbgRecords on the next instruction, here labelled xyzzy, before we hoist
571 // %foo. Later, we only only clone DbgRecords from that position (xyzzy)
572 // onwards, which avoids cloning DbgRecord "blah" multiple times. (Stored as
573 // a range because it gives us a natural way of testing whether
574 // there were DbgRecords on the next instruction before we hoisted things).
576 (I != E) ? I->getDbgRecordRange() : DbgMarker::getEmptyDbgRecordRange();
577
578 while (I != E) {
579 Instruction *Inst = &*I++;
580
581 // If the instruction's operands are invariant and it doesn't read or write
582 // memory, then it is safe to hoist. Doing this doesn't change the order of
583 // execution in the preheader, but does prevent the instruction from
584 // executing in each iteration of the loop. This means it is safe to hoist
585 // something that might trap, but isn't safe to hoist something that reads
586 // memory (without proving that the loop doesn't write).
587 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
588 !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
589 !isa<AllocaInst>(Inst) &&
590 // It is not safe to hoist the value of these instructions in
591 // coroutines, as the addresses of otherwise eligible variables (e.g.
592 // thread-local variables and errno) may change if the coroutine is
593 // resumed in a different thread.Therefore, we disable this
594 // optimization for correctness. However, this may block other correct
595 // optimizations.
596 // FIXME: This should be reverted once we have a better model for
597 // memory access in coroutines.
598 !Inst->getFunction()->isPresplitCoroutine()) {
599
600 if (!NextDbgInsts.empty()) {
601 auto DbgValueRange =
602 LoopEntryBranch->cloneDebugInfoFrom(Inst, NextDbgInsts.begin());
603 RemapDbgRecordRange(M, DbgValueRange, ValueMap,
605 // Erase anything we've seen before.
606 for (DbgVariableRecord &DVR :
607 make_early_inc_range(filterDbgVars(DbgValueRange)))
608 if (DbgRecords.count(makeHash(&DVR)))
609 DVR.eraseFromParent();
610 }
611
612 NextDbgInsts = I->getDbgRecordRange();
613
614 Inst->moveBefore(LoopEntryBranch->getIterator());
615
616 ++NumInstrsHoisted;
617 continue;
618 }
619
620 // Otherwise, create a duplicate of the instruction.
621 Instruction *C = Inst->clone();
622 if (const DebugLoc &DL = C->getDebugLoc())
624
625 C->insertBefore(LoopEntryBranch->getIterator());
626
627 ++NumInstrsDuplicated;
628
629 if (!NextDbgInsts.empty()) {
630 auto Range = C->cloneDebugInfoFrom(Inst, NextDbgInsts.begin());
633 NextDbgInsts = DbgMarker::getEmptyDbgRecordRange();
634 // Erase anything we've seen before.
635 for (DbgVariableRecord &DVR :
637 if (DbgRecords.count(makeHash(&DVR)))
638 DVR.eraseFromParent();
639 }
640
641 // Eagerly remap the operands of the instruction.
644
645 // With the operands remapped, see if the instruction constant folds or is
646 // otherwise simplifyable. This commonly occurs because the entry from PHI
647 // nodes allows icmps and other instructions to fold.
649 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
650 // If so, then delete the temporary instruction and stick the folded value
651 // in the map.
653 if (!C->mayHaveSideEffects()) {
654 C->eraseFromParent();
655 C = nullptr;
656 }
657 } else {
659 }
660 if (C) {
661 // Otherwise, stick the new instruction into the new block!
662 C->setName(Inst->getName());
663
664 if (auto *II = dyn_cast<AssumeInst>(C))
665 AC->registerAssumption(II);
666 // MemorySSA cares whether the cloned instruction was inserted or not, and
667 // not whether it can be remapped to a simplified value.
668 if (MSSAU)
669 InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
670 }
671 }
672
673 if (!NoAliasDeclInstructions.empty()) {
674 // There are noalias scope declarations:
675 // (general):
676 // Original: OrigPre { OrigHeader NewHeader ... Latch }
677 // after: (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
678 //
679 // with D: llvm.experimental.noalias.scope.decl,
680 // U: !noalias or !alias.scope depending on D
681 // ... { D U1 U2 } can transform into:
682 // (0) : ... { D U1 U2 } // no relevant rotation for this part
683 // (1) : ... D' { U1 U2 D } // D is part of OrigHeader
684 // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
685 //
686 // We now want to transform:
687 // (1) -> : ... D' { D U1 U2 D'' }
688 // (2) -> : ... D' U1' { D U2 D'' U1'' }
689 // D: original llvm.experimental.noalias.scope.decl
690 // D', U1': duplicate with replaced scopes
691 // D'', U1'': different duplicate with replaced scopes
692 // This ensures a safe fallback to 'may_alias' introduced by the rotate,
693 // as U1'' and U1' scopes will not be compatible wrt to the local restrict
694
695 // Clone the llvm.experimental.noalias.decl again for the NewHeader.
696 BasicBlock::iterator NewHeaderInsertionPoint =
697 NewHeader->getFirstNonPHIIt();
698 for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
699 LLVM_DEBUG(dbgs() << " Cloning llvm.experimental.noalias.scope.decl:"
700 << *NAD << "\n");
701 Instruction *NewNAD = NAD->clone();
702 NewNAD->insertBefore(*NewHeader, NewHeaderInsertionPoint);
703 }
704
705 // Scopes must now be duplicated, once for OrigHeader and once for
706 // OrigPreHeader'.
707 {
708 auto &Context = NewHeader->getContext();
709
710 SmallVector<MDNode *, 8> NoAliasDeclScopes;
711 for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
712 NoAliasDeclScopes.push_back(NAD->getScopeList());
713
714 LLVM_DEBUG(dbgs() << " Updating OrigHeader scopes\n");
715 cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
716 "h.rot");
717 LLVM_DEBUG(OrigHeader->dump());
718
719 // Keep the compile time impact low by only adapting the inserted block
720 // of instructions in the OrigPreHeader. This might result in slightly
721 // more aliasing between these instructions and those that were already
722 // present, but it will be much faster when the original PreHeader is
723 // large.
724 LLVM_DEBUG(dbgs() << " Updating part of OrigPreheader scopes\n");
725 auto *FirstDecl =
726 cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
727 auto *LastInst = &OrigPreheader->back();
728 cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
729 Context, "pre.rot");
730 LLVM_DEBUG(OrigPreheader->dump());
731
732 LLVM_DEBUG(dbgs() << " Updated NewHeader:\n");
733 LLVM_DEBUG(NewHeader->dump());
734 }
735 }
736
737 // Along with all the other instructions, we just cloned OrigHeader's
738 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
739 // successors by duplicating their incoming values for OrigHeader.
740 for (BasicBlock *SuccBB : successors(OrigHeader))
741 for (BasicBlock::iterator BI = SuccBB->begin();
742 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
743 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
744
745 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
746 // OrigPreHeader's old terminator (the original branch into the loop), and
747 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
748 LoopEntryBranch->eraseFromParent();
749 OrigPreheader->flushTerminatorDbgRecords();
750
751 // Update MemorySSA before the rewrite call below changes the 1:1
752 // instruction:cloned_instruction_or_value mapping.
753 if (MSSAU) {
754 InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
755 MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
756 ValueMapMSSA);
757 }
758
759 SmallVector<PHINode*, 2> InsertedPHIs;
760 // If there were any uses of instructions in the duplicated block outside the
761 // loop, update them, inserting PHI nodes as required
762 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
763 &InsertedPHIs);
764
765 // Attach debug records to the new phis if that phi uses a value that
766 // previously had debug metadata attached. This keeps the debug info
767 // up-to-date in the loop body.
768 if (!InsertedPHIs.empty())
769 insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
770
771 // NewHeader is now the header of the loop.
772 L->moveToHeader(NewHeader);
773 assert(L->getHeader() == NewHeader && "Latch block is our new header");
774
775 // Inform DT about changes to the CFG.
776 if (DT) {
777 // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
778 // the DT about the removed edge to the OrigHeader (that got removed).
780 {DominatorTree::Insert, OrigPreheader, Exit},
781 {DominatorTree::Insert, OrigPreheader, NewHeader},
782 {DominatorTree::Delete, OrigPreheader, OrigHeader}};
783
784 if (MSSAU) {
785 MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
786 if (VerifyMemorySSA)
787 MSSAU->getMemorySSA()->verifyMemorySSA();
788 } else {
789 DT->applyUpdates(Updates);
790 }
791 }
792
793 // At this point, we've finished our major CFG changes. As part of cloning
794 // the loop into the preheader we've simplified instructions and the
795 // duplicated conditional branch may now be branching on a constant. If it is
796 // branching on a constant and if that constant means that we enter the loop,
797 // then we fold away the cond branch to an uncond branch. This simplifies the
798 // loop in cases important for nested loops, and it also means we don't have
799 // to split as many edges.
800 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
801 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
802 const Value *Cond = PHBI->getCondition();
803 const bool HasConditionalPreHeader =
804 !isa<ConstantInt>(Cond) ||
805 PHBI->getSuccessor(cast<ConstantInt>(Cond)->isZero()) != NewHeader;
806
807 updateBranchWeights(*PHBI, *BI, HasConditionalPreHeader, BISuccsSwapped);
808
809 if (HasConditionalPreHeader) {
810 // The conditional branch can't be folded, handle the general case.
811 // Split edges as necessary to preserve LoopSimplify form.
812
813 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
814 // thus is not a preheader anymore.
815 // Split the edge to form a real preheader.
817 OrigPreheader, NewHeader,
818 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
819 NewPH->setName(NewHeader->getName() + ".lr.ph");
820
821 // Preserve canonical loop form, which means that 'Exit' should have only
822 // one predecessor. Note that Exit could be an exit block for multiple
823 // nested loops, causing both of the edges to now be critical and need to
824 // be split.
826 bool SplitLatchEdge = false;
827 for (BasicBlock *ExitPred : ExitPreds) {
828 // We only need to split loop exit edges.
829 Loop *PredLoop = LI->getLoopFor(ExitPred);
830 if (!PredLoop || PredLoop->contains(Exit) ||
831 isa<IndirectBrInst>(ExitPred->getTerminator()))
832 continue;
833 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
834 BasicBlock *ExitSplit = SplitCriticalEdge(
835 ExitPred, Exit,
836 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
837 ExitSplit->moveBefore(Exit);
838 }
839 assert(SplitLatchEdge &&
840 "Despite splitting all preds, failed to split latch exit?");
841 (void)SplitLatchEdge;
842 } else {
843 // We can fold the conditional branch in the preheader, this makes things
844 // simpler. The first step is to remove the extra edge to the Exit block.
845 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
846 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI->getIterator());
847 NewBI->setDebugLoc(PHBI->getDebugLoc());
848 PHBI->eraseFromParent();
849
850 // With our CFG finalized, update DomTree if it is available.
851 if (DT) DT->deleteEdge(OrigPreheader, Exit);
852
853 // Update MSSA too, if available.
854 if (MSSAU)
855 MSSAU->removeEdge(OrigPreheader, Exit);
856 }
857
858 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
859 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
860
861 if (MSSAU && VerifyMemorySSA)
862 MSSAU->getMemorySSA()->verifyMemorySSA();
863
864 // Now that the CFG and DomTree are in a consistent state again, try to merge
865 // the OrigHeader block into OrigLatch. This will succeed if they are
866 // connected by an unconditional branch. This is just a cleanup so the
867 // emitted code isn't too gross in this common case.
868 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
869 BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
870 bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
871 if (DidMerge)
873
874 if (MSSAU && VerifyMemorySSA)
875 MSSAU->getMemorySSA()->verifyMemorySSA();
876
877 LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
878
879 ++NumRotated;
880
881 Rotated = true;
882 SimplifiedLatch = false;
883
884 // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
885 // Deoptimizing latch exit is not a generally typical case, so we just loop over.
886 // TODO: if it becomes a performance bottleneck extend rotation algorithm
887 // to handle multiple rotations in one go.
889
890
891 return true;
892}
893
894/// Determine whether the instructions in this range may be safely and cheaply
895/// speculated. This is not an important enough situation to develop complex
896/// heuristics. We handle a single arithmetic instruction along with any type
897/// conversions.
900 bool seenIncrement = false;
901 bool MultiExitLoop = false;
902
903 if (!L->getExitingBlock())
904 MultiExitLoop = true;
905
906 for (BasicBlock::iterator I = Begin; I != End; ++I) {
907
909 return false;
910
911 switch (I->getOpcode()) {
912 default:
913 return false;
914 case Instruction::GetElementPtr:
915 // GEPs are cheap if all indices are constant.
916 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
917 return false;
918 // fall-thru to increment case
919 [[fallthrough]];
920 case Instruction::Add:
921 case Instruction::Sub:
922 case Instruction::And:
923 case Instruction::Or:
924 case Instruction::Xor:
925 case Instruction::Shl:
926 case Instruction::LShr:
927 case Instruction::AShr: {
928 Value *IVOpnd =
929 !isa<Constant>(I->getOperand(0))
930 ? I->getOperand(0)
931 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
932 if (!IVOpnd)
933 return false;
934
935 // If increment operand is used outside of the loop, this speculation
936 // could cause extra live range interference.
937 if (MultiExitLoop) {
938 for (User *UseI : IVOpnd->users()) {
939 auto *UserInst = cast<Instruction>(UseI);
940 if (!L->contains(UserInst))
941 return false;
942 }
943 }
944
945 if (seenIncrement)
946 return false;
947 seenIncrement = true;
948 break;
949 }
950 case Instruction::Trunc:
951 case Instruction::ZExt:
952 case Instruction::SExt:
953 // ignore type conversions
954 break;
955 }
956 }
957 return true;
958}
959
960/// Fold the loop tail into the loop exit by speculating the loop tail
961/// instructions. Typically, this is a single post-increment. In the case of a
962/// simple 2-block loop, hoisting the increment can be much better than
963/// duplicating the entire loop header. In the case of loops with early exits,
964/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
965/// canonical form so downstream passes can handle it.
966///
967/// I don't believe this invalidates SCEV.
968bool LoopRotate::simplifyLoopLatch(Loop *L) {
969 BasicBlock *Latch = L->getLoopLatch();
970 if (!Latch || Latch->hasAddressTaken())
971 return false;
972
973 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
974 if (!Jmp || !Jmp->isUnconditional())
975 return false;
976
977 BasicBlock *LastExit = Latch->getSinglePredecessor();
978 if (!LastExit || !L->isLoopExiting(LastExit))
979 return false;
980
981 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
982 if (!BI)
983 return false;
984
985 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
986 return false;
987
988 LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
989 << LastExit->getName() << "\n");
990
991 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
992 MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
993 /*PredecessorWithTwoSuccessors=*/true);
994
995 if (SE) {
996 // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
997 SE->forgetBlockAndLoopDispositions();
998 }
999
1000 if (MSSAU && VerifyMemorySSA)
1001 MSSAU->getMemorySSA()->verifyMemorySSA();
1002
1003 return true;
1004}
1005
1006/// Rotate \c L, and return true if any modification was made.
1007bool LoopRotate::processLoop(Loop *L) {
1008 // Save the loop metadata.
1009 MDNode *LoopMD = L->getLoopID();
1010
1011 bool SimplifiedLatch = false;
1012
1013 // Simplify the loop latch before attempting to rotate the header
1014 // upward. Rotation may not be needed if the loop tail can be folded into the
1015 // loop exit.
1016 if (!RotationOnly)
1017 SimplifiedLatch = simplifyLoopLatch(L);
1018
1019 bool MadeChange = rotateLoop(L, SimplifiedLatch);
1020 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
1021 "Loop latch should be exiting after loop-rotate.");
1022
1023 // Restore the loop metadata.
1024 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
1025 if ((MadeChange || SimplifiedLatch) && LoopMD)
1026 L->setLoopID(LoopMD);
1027
1028 return MadeChange || SimplifiedLatch;
1029}
1030
1031
1032/// The utility to convert a loop into a loop with bottom test.
1036 const SimplifyQuery &SQ, bool RotationOnly = true,
1037 unsigned Threshold = unsigned(-1),
1038 bool IsUtilMode = true, bool PrepareForLTO) {
1039 LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
1040 IsUtilMode, PrepareForLTO);
1041 return LR.processLoop(L);
1042}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
bool End
Definition: ELF_riscv.cpp:480
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:546
static constexpr uint32_t ZeroTripCountWeights[]
static bool canRotateDeoptimizingLatchExit(Loop *L)
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End, Loop *L)
Determine whether the instructions in this range may be safely and cheaply speculated.
static cl::opt< bool > MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden, cl::desc("Allow loop rotation multiple times in order to reach " "a better latch exit"))
static bool profitableToRotateLoopExitingLatch(Loop *L)
static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI, bool HasConditionalPreHeader, bool SuccsSwapped)
static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V)
Insert (K, V) pair into the ValueToValueMap, and verify the key did not previously exist in the map,...
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *InsertedPHIs)
RewriteUsesOfClonedInstructions - We just cloned the instructions from the old header into the prehea...
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Trace Metrics
Memory SSA
Definition: MemorySSA.cpp:72
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
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:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
iterator end()
Definition: BasicBlock.h:472
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:459
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:690
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:337
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:437
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:445
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
Definition: BasicBlock.cpp:699
LLVM_ABI DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:131
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.h:386
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:233
LLVM_ABI const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
Definition: BasicBlock.cpp:302
const Instruction & back() const
Definition: BasicBlock.h:484
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
DWARF expression.
static iterator_range< simple_ilist< DbgRecord >::iterator > getEmptyDbgRecordRange()
LLVM_ABI const BasicBlock * getParent() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition: DebugLoc.h:124
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
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:165
bool isPresplitCoroutine() const
Determine if the function is presplit coroutine.
Definition: Function.h:539
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
Definition: Instruction.h:105
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:513
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:82
bool isTerminator() const
Definition: Instruction.h:315
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:510
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:40
Metadata node.
Definition: Metadata.h:1077
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1885
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:39
The main scalar evolution driver.
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:283
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:169
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: ValueMap.h:177
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:390
iterator_range< user_iterator > users()
Definition: Value.h:426
bool use_empty() const
Definition: Value.h:346
iterator_range< use_iterator > uses()
Definition: Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:5465
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:174
const ParentTy * getParent() const
Definition: ilist_node.h:34
self_iterator getIterator()
Definition: ilist_node.h:134
A range adaptor for a pair of iterators.
IteratorT begin() const
@ Exit
Definition: COFF.h:863
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
Definition: DebugInfo.cpp:124
auto successors(const MachineBasicBlock *BB)
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:663
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 ...
LLVM_ABI void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition: Local.cpp:1879
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1751
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
Definition: ValueMapper.h:317
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
@ 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:207
LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:84
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
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.
Definition: ValueMapper.h:289
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
auto predecessors(const MachineBasicBlock *BB)
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI, AssumptionCache *AC, DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, const SimplifyQuery &SQ, bool RotationOnly, unsigned Threshold, bool IsUtilMode, bool PrepareForLTO=false)
Convert a loop into a loop with bottom test.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:469
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:853
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:34
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
Definition: CodeMetrics.cpp:71
Option class for critical edge splitting.