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");
48
49// Probability that a rotated loop has zero trip count / is never entered.
50static constexpr uint32_t ZeroTripCountWeights[] = {1, 127};
51
52namespace {
53/// A simple loop rotation transformation.
54class LoopRotate {
55 const unsigned MaxHeaderSize;
56 LoopInfo *LI;
57 const TargetTransformInfo *TTI;
58 AssumptionCache *AC;
59 DominatorTree *DT;
60 ScalarEvolution *SE;
61 MemorySSAUpdater *MSSAU;
62 const SimplifyQuery &SQ;
63 bool RotationOnly;
64 bool IsUtilMode;
65 bool PrepareForLTO;
66
67public:
68 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
69 const TargetTransformInfo *TTI, AssumptionCache *AC,
70 DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
71 const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
72 bool PrepareForLTO)
73 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
74 MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
75 IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
76 bool processLoop(Loop *L);
77
78private:
79 bool rotateLoop(Loop *L, bool SimplifiedLatch);
80 bool simplifyLoopLatch(Loop *L);
81};
82} // end anonymous namespace
83
84/// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
85/// previously exist in the map, and the value was inserted.
87 bool Inserted = VM.insert({K, V}).second;
88 assert(Inserted);
89 (void)Inserted;
90}
91/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
92/// old header into the preheader. If there were uses of the values produced by
93/// these instruction that were outside of the loop, we have to insert PHI nodes
94/// to merge the two values. Do this now.
96 BasicBlock *OrigPreheader,
99 SmallVectorImpl<PHINode*> *InsertedPHIs) {
100 // Remove PHI node entries that are no longer live.
101 BasicBlock::iterator I, E = OrigHeader->end();
102 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
103 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
104
105 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
106 // as necessary.
107 SSAUpdater SSA(InsertedPHIs);
108 for (I = OrigHeader->begin(); I != E; ++I) {
109 Value *OrigHeaderVal = &*I;
110
111 // If there are no uses of the value (e.g. because it returns void), there
112 // is nothing to rewrite.
113 if (OrigHeaderVal->use_empty())
114 continue;
115
116 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
117
118 // The value now exits in two versions: the initial value in the preheader
119 // and the loop "next" value in the original header.
120 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
121 // Force re-computation of OrigHeaderVal, as some users now need to use the
122 // new PHI node.
123 if (SE)
124 SE->forgetValue(OrigHeaderVal);
125 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
126 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
127
128 // Visit each use of the OrigHeader instruction.
129 for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
130 // SSAUpdater can't handle a non-PHI use in the same block as an
131 // earlier def. We can easily handle those cases manually.
132 Instruction *UserInst = cast<Instruction>(U.getUser());
133 if (!isa<PHINode>(UserInst)) {
134 BasicBlock *UserBB = UserInst->getParent();
135
136 // The original users in the OrigHeader are already using the
137 // original definitions.
138 if (UserBB == OrigHeader)
139 continue;
140
141 // Users in the OrigPreHeader need to use the value to which the
142 // original definitions are mapped.
143 if (UserBB == OrigPreheader) {
144 U = OrigPreHeaderVal;
145 continue;
146 }
147 }
148
149 // Anything else can be handled by SSAUpdater.
150 SSA.RewriteUse(U);
151 }
152
153 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
154 // intrinsics.
155 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
156 llvm::findDbgValues(OrigHeaderVal, DbgVariableRecords);
157
158 for (DbgVariableRecord *DVR : DbgVariableRecords) {
159 // The original users in the OrigHeader are already using the original
160 // definitions.
161 BasicBlock *UserBB = DVR->getMarker()->getParent();
162 if (UserBB == OrigHeader)
163 continue;
164
165 // Users in the OrigPreHeader need to use the value to which the
166 // original definitions are mapped and anything else can be handled by
167 // the SSAUpdater. To avoid adding PHINodes, check if the value is
168 // available in UserBB, if not substitute poison.
169 Value *NewVal;
170 if (UserBB == OrigPreheader)
171 NewVal = OrigPreHeaderVal;
172 else if (SSA.HasValueForBlock(UserBB))
173 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
174 else
175 NewVal = PoisonValue::get(OrigHeaderVal->getType());
176 DVR->replaceVariableLocationOp(OrigHeaderVal, NewVal);
177 }
178 }
179}
180
181// Assuming both header and latch are exiting, look for a phi which is only
182// used outside the loop (via a LCSSA phi) in the exit from the header.
183// This means that rotating the loop can remove the phi.
185 BasicBlock *Header = L->getHeader();
186 BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
187 assert(BI && BI->isConditional() && "need header with conditional exit");
188 BasicBlock *HeaderExit = BI->getSuccessor(0);
189 if (L->contains(HeaderExit))
190 HeaderExit = BI->getSuccessor(1);
191
192 for (auto &Phi : Header->phis()) {
193 // Look for uses of this phi in the loop/via exits other than the header.
194 if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
195 return cast<Instruction>(U)->getParent() != HeaderExit;
196 }))
197 continue;
198 return true;
199 }
200 return false;
201}
202
203static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
204 bool HasConditionalPreHeader,
205 bool SuccsSwapped) {
206 MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
207 if (WeightMD == nullptr)
208 return;
209
210 // LoopBI should currently be a clone of PreHeaderBI with the same
211 // metadata. But we double check to make sure we don't have a degenerate case
212 // where instsimplify changed the instructions.
213 if (WeightMD != getBranchWeightMDNode(LoopBI))
214 return;
215
217 extractFromBranchWeightMD32(WeightMD, Weights);
218 if (Weights.size() != 2)
219 return;
220 uint32_t OrigLoopExitWeight = Weights[0];
221 uint32_t OrigLoopBackedgeWeight = Weights[1];
222
223 if (SuccsSwapped)
224 std::swap(OrigLoopExitWeight, OrigLoopBackedgeWeight);
225
226 // Update branch weights. Consider the following edge-counts:
227 //
228 // | |-------- |
229 // V V | V
230 // Br i1 ... | Br i1 ...
231 // | | | | |
232 // x| y| | becomes: | y0| |-----
233 // V V | | V V |
234 // Exit Loop | | Loop |
235 // | | | Br i1 ... |
236 // ----- | | | |
237 // x0| x1| y1 | |
238 // V V ----
239 // Exit
240 //
241 // The following must hold:
242 // - x == x0 + x1 # counts to "exit" must stay the same.
243 // - y0 == x - x0 == x1 # how often loop was entered at all.
244 // - y1 == y - y0 # How often loop was repeated (after first iter.).
245 //
246 // We cannot generally deduce how often we had a zero-trip count loop so we
247 // have to make a guess for how to distribute x among the new x0 and x1.
248
249 uint32_t ExitWeight0; // aka x0
250 uint32_t ExitWeight1; // aka x1
251 uint32_t EnterWeight; // aka y0
252 uint32_t LoopBackWeight; // aka y1
253 if (OrigLoopExitWeight > 0 && OrigLoopBackedgeWeight > 0) {
254 ExitWeight0 = 0;
255 if (HasConditionalPreHeader) {
256 // Here we cannot know how many 0-trip count loops we have, so we guess:
257 if (OrigLoopBackedgeWeight >= OrigLoopExitWeight) {
258 // If the loop count is bigger than the exit count then we set
259 // probabilities as if 0-trip count nearly never happens.
260 ExitWeight0 = ZeroTripCountWeights[0];
261 // Scale up counts if necessary so we can match `ZeroTripCountWeights`
262 // for the `ExitWeight0`:`ExitWeight1` (aka `x0`:`x1` ratio`) ratio.
263 while (OrigLoopExitWeight < ZeroTripCountWeights[1] + ExitWeight0) {
264 // ... but don't overflow.
265 uint32_t const HighBit = uint32_t{1} << (sizeof(uint32_t) * 8 - 1);
266 if ((OrigLoopBackedgeWeight & HighBit) != 0 ||
267 (OrigLoopExitWeight & HighBit) != 0)
268 break;
269 OrigLoopBackedgeWeight <<= 1;
270 OrigLoopExitWeight <<= 1;
271 }
272 } else {
273 // If there's a higher exit-count than backedge-count then we set
274 // probabilities as if there are only 0-trip and 1-trip cases.
275 ExitWeight0 = OrigLoopExitWeight - OrigLoopBackedgeWeight;
276 }
277 } else {
278 // Theoretically, if the loop body must be executed at least once, the
279 // backedge count must be not less than exit count. However the branch
280 // weight collected by sampling-based PGO may be not very accurate due to
281 // sampling. Therefore this workaround is required here to avoid underflow
282 // of unsigned in following update of branch weight.
283 if (OrigLoopExitWeight > OrigLoopBackedgeWeight)
284 OrigLoopBackedgeWeight = OrigLoopExitWeight;
285 }
286 assert(OrigLoopExitWeight >= ExitWeight0 && "Bad branch weight");
287 ExitWeight1 = OrigLoopExitWeight - ExitWeight0;
288 EnterWeight = ExitWeight1;
289 assert(OrigLoopBackedgeWeight >= EnterWeight && "Bad branch weight");
290 LoopBackWeight = OrigLoopBackedgeWeight - EnterWeight;
291 } else if (OrigLoopExitWeight == 0) {
292 if (OrigLoopBackedgeWeight == 0) {
293 // degenerate case... keep everything zero...
294 ExitWeight0 = 0;
295 ExitWeight1 = 0;
296 EnterWeight = 0;
297 LoopBackWeight = 0;
298 } else {
299 // Special case "LoopExitWeight == 0" weights which behaves like an
300 // endless where we don't want loop-enttry (y0) to be the same as
301 // loop-exit (x1).
302 ExitWeight0 = 0;
303 ExitWeight1 = 0;
304 EnterWeight = 1;
305 LoopBackWeight = OrigLoopBackedgeWeight;
306 }
307 } else {
308 // loop is never entered.
309 assert(OrigLoopBackedgeWeight == 0 && "remaining case is backedge zero");
310 ExitWeight0 = 1;
311 ExitWeight1 = 1;
312 EnterWeight = 0;
313 LoopBackWeight = 0;
314 }
315
316 const uint32_t LoopBIWeights[] = {
317 SuccsSwapped ? LoopBackWeight : ExitWeight1,
318 SuccsSwapped ? ExitWeight1 : LoopBackWeight,
319 };
320 setBranchWeights(LoopBI, LoopBIWeights, /*IsExpected=*/false);
321 if (HasConditionalPreHeader) {
322 const uint32_t PreHeaderBIWeights[] = {
323 SuccsSwapped ? EnterWeight : ExitWeight0,
324 SuccsSwapped ? ExitWeight0 : EnterWeight,
325 };
326 setBranchWeights(PreHeaderBI, PreHeaderBIWeights, /*IsExpected=*/false);
327 }
328}
329
330/// Rotate loop LP. Return true if the loop is rotated.
331///
332/// \param SimplifiedLatch is true if the latch was just folded into the final
333/// loop exit. In this case we may want to rotate even though the new latch is
334/// now an exiting branch. This rotation would have happened had the latch not
335/// been simplified. However, if SimplifiedLatch is false, then we avoid
336/// rotating loops in which the latch exits to avoid excessive or endless
337/// rotation. LoopRotate should be repeatable and converge to a canonical
338/// form. This property is satisfied because simplifying the loop latch can only
339/// happen once across multiple invocations of the LoopRotate pass.
340bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
341 // If the loop has only one block then there is not much to rotate.
342 if (L->getBlocks().size() == 1)
343 return false;
344
345 bool Rotated = false;
346 BasicBlock *OrigHeader = L->getHeader();
347 BasicBlock *OrigLatch = L->getLoopLatch();
348
349 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
350 if (!BI || BI->isUnconditional())
351 return Rotated;
352
353 // If the loop header is not one of the loop exiting blocks then
354 // either this loop is already rotated or it is not
355 // suitable for loop rotation transformations.
356 if (!L->isLoopExiting(OrigHeader))
357 return Rotated;
358
359 // If the loop latch already contains a branch that leaves the loop then the
360 // loop is already rotated.
361 if (!OrigLatch)
362 return Rotated;
363
364 // Rotate if the loop latch was just simplified. Or if it makes the loop exit
365 // count computable. Or if we think it will be profitable.
366 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
368 return Rotated;
369
370 // Check size of original header and reject loop if it is very big or we can't
371 // duplicate blocks inside it.
372 {
373 SmallPtrSet<const Value *, 32> EphValues;
374 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
375
376 CodeMetrics Metrics;
377 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
378 if (Metrics.notDuplicatable) {
380 dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
381 << " instructions: ";
382 L->dump());
383 return Rotated;
384 }
385 if (Metrics.Convergence != ConvergenceKind::None) {
386 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
387 "instructions: ";
388 L->dump());
389 return Rotated;
390 }
391 if (!Metrics.NumInsts.isValid()) {
392 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
393 " with invalid cost: ";
394 L->dump());
395 return Rotated;
396 }
397 if (Metrics.NumInsts > MaxHeaderSize) {
398 LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
399 << Metrics.NumInsts
400 << " instructions, which is more than the threshold ("
401 << MaxHeaderSize << " instructions): ";
402 L->dump());
403 ++NumNotRotatedDueToHeaderSize;
404 return Rotated;
405 }
406
407 // When preparing for LTO, avoid rotating loops with calls that could be
408 // inlined during the LTO stage.
409 if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
410 return Rotated;
411 }
412
413 // Now, this loop is suitable for rotation.
414 BasicBlock *OrigPreheader = L->getLoopPreheader();
415
416 // If the loop could not be converted to canonical form, it must have an
417 // indirectbr in it, just give up.
418 if (!OrigPreheader || !L->hasDedicatedExits())
419 return Rotated;
420
421 // Anything ScalarEvolution may know about this loop or the PHI nodes
422 // in its header will soon be invalidated. We should also invalidate
423 // all outer loops because insertion and deletion of blocks that happens
424 // during the rotation may violate invariants related to backedge taken
425 // infos in them.
426 if (SE) {
427 SE->forgetTopmostLoop(L);
428 // We may hoist some instructions out of loop. In case if they were cached
429 // as "loop variant" or "loop computable", these caches must be dropped.
430 // We also may fold basic blocks, so cached block dispositions also need
431 // to be dropped.
433 }
434
435 LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
436 if (MSSAU && VerifyMemorySSA)
437 MSSAU->getMemorySSA()->verifyMemorySSA();
438
439 // Find new Loop header. NewHeader is a Header's one and only successor
440 // that is inside loop. Header's other successor is outside the
441 // loop. Otherwise loop is not suitable for rotation.
442 BasicBlock *Exit = BI->getSuccessor(0);
443 BasicBlock *NewHeader = BI->getSuccessor(1);
444 bool BISuccsSwapped = L->contains(Exit);
445 if (BISuccsSwapped)
446 std::swap(Exit, NewHeader);
447 assert(NewHeader && "Unable to determine new loop header");
448 assert(L->contains(NewHeader) && !L->contains(Exit) &&
449 "Unable to determine loop header and exit blocks");
450
451 // This code assumes that the new header has exactly one predecessor.
452 // Remove any single-entry PHI nodes in it.
453 assert(NewHeader->getSinglePredecessor() &&
454 "New header doesn't have one pred!");
455 FoldSingleEntryPHINodes(NewHeader);
456
457 // Begin by walking OrigHeader and populating ValueMap with an entry for
458 // each Instruction.
459 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
460 ValueToValueMapTy ValueMap, ValueMapMSSA;
461
462 // For PHI nodes, the value available in OldPreHeader is just the
463 // incoming value from OldPreHeader.
464 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
465 InsertNewValueIntoMap(ValueMap, PN,
466 PN->getIncomingValueForBlock(OrigPreheader));
467
468 // For the rest of the instructions, either hoist to the OrigPreheader if
469 // possible or create a clone in the OldPreHeader if not.
470 Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
471
472 // Record all debug records preceding LoopEntryBranch to avoid
473 // duplication.
474 using DbgHash =
475 std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
476 auto makeHash = [](const DbgVariableRecord *D) -> DbgHash {
477 auto VarLocOps = D->location_ops();
478 return {{hash_combine_range(VarLocOps), D->getVariable()},
479 D->getExpression()};
480 };
481
482 SmallDenseSet<DbgHash, 8> DbgRecords;
483 // Build DbgVariableRecord hashes for DbgVariableRecords attached to the
484 // terminator.
485 for (const DbgVariableRecord &DVR :
486 filterDbgVars(OrigPreheader->getTerminator()->getDbgRecordRange()))
487 DbgRecords.insert(makeHash(&DVR));
488
489 // Remember the local noalias scope declarations in the header. After the
490 // rotation, they must be duplicated and the scope must be cloned. This
491 // avoids unwanted interaction across iterations.
492 SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
493 for (Instruction &I : *OrigHeader)
494 if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
495 NoAliasDeclInstructions.push_back(Decl);
496
497 Module *M = OrigHeader->getModule();
498
499 // Track the next DbgRecord to clone. If we have a sequence where an
500 // instruction is hoisted instead of being cloned:
501 // DbgRecord blah
502 // %foo = add i32 0, 0
503 // DbgRecord xyzzy
504 // %bar = call i32 @foobar()
505 // where %foo is hoisted, then the DbgRecord "blah" will be seen twice, once
506 // attached to %foo, then when %foo his hoisted it will "fall down" onto the
507 // function call:
508 // DbgRecord blah
509 // DbgRecord xyzzy
510 // %bar = call i32 @foobar()
511 // causing it to appear attached to the call too.
512 //
513 // To avoid this, cloneDebugInfoFrom takes an optional "start cloning from
514 // here" position to account for this behaviour. We point it at any
515 // DbgRecords on the next instruction, here labelled xyzzy, before we hoist
516 // %foo. Later, we only only clone DbgRecords from that position (xyzzy)
517 // onwards, which avoids cloning DbgRecord "blah" multiple times. (Stored as
518 // a range because it gives us a natural way of testing whether
519 // there were DbgRecords on the next instruction before we hoisted things).
521 (I != E) ? I->getDbgRecordRange() : DbgMarker::getEmptyDbgRecordRange();
522
523 while (I != E) {
524 Instruction *Inst = &*I++;
525
526 // If the instruction's operands are invariant and it doesn't read or write
527 // memory, then it is safe to hoist. Doing this doesn't change the order of
528 // execution in the preheader, but does prevent the instruction from
529 // executing in each iteration of the loop. This means it is safe to hoist
530 // something that might trap, but isn't safe to hoist something that reads
531 // memory (without proving that the loop doesn't write).
532 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
533 !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
534 !isa<AllocaInst>(Inst) &&
535 // It is not safe to hoist the value of these instructions in
536 // coroutines, as the addresses of otherwise eligible variables (e.g.
537 // thread-local variables and errno) may change if the coroutine is
538 // resumed in a different thread.Therefore, we disable this
539 // optimization for correctness. However, this may block other correct
540 // optimizations.
541 // FIXME: This should be reverted once we have a better model for
542 // memory access in coroutines.
543 !Inst->getFunction()->isPresplitCoroutine()) {
544
545 if (!NextDbgInsts.empty()) {
546 auto DbgValueRange =
547 LoopEntryBranch->cloneDebugInfoFrom(Inst, NextDbgInsts.begin());
548 RemapDbgRecordRange(M, DbgValueRange, ValueMap,
550 // Erase anything we've seen before.
551 for (DbgVariableRecord &DVR :
552 make_early_inc_range(filterDbgVars(DbgValueRange)))
553 if (DbgRecords.count(makeHash(&DVR)))
554 DVR.eraseFromParent();
555 }
556
557 NextDbgInsts = I->getDbgRecordRange();
558
559 Inst->moveBefore(LoopEntryBranch->getIterator());
560
561 ++NumInstrsHoisted;
562 continue;
563 }
564
565 // Otherwise, create a duplicate of the instruction.
566 Instruction *C = Inst->clone();
567 if (const DebugLoc &DL = C->getDebugLoc())
568 mapAtomInstance(DL, ValueMap);
569
570 C->insertBefore(LoopEntryBranch->getIterator());
571
572 ++NumInstrsDuplicated;
573
574 if (!NextDbgInsts.empty()) {
575 auto Range = C->cloneDebugInfoFrom(Inst, NextDbgInsts.begin());
576 RemapDbgRecordRange(M, Range, ValueMap,
578 NextDbgInsts = DbgMarker::getEmptyDbgRecordRange();
579 // Erase anything we've seen before.
580 for (DbgVariableRecord &DVR : make_early_inc_range(filterDbgVars(Range)))
581 if (DbgRecords.count(makeHash(&DVR)))
582 DVR.eraseFromParent();
583 }
584
585 // Eagerly remap the operands of the instruction.
586 RemapInstruction(C, ValueMap,
588
589 // With the operands remapped, see if the instruction constant folds or is
590 // otherwise simplifyable. This commonly occurs because the entry from PHI
591 // nodes allows icmps and other instructions to fold.
593 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
594 // If so, then delete the temporary instruction and stick the folded value
595 // in the map.
596 InsertNewValueIntoMap(ValueMap, Inst, V);
597 if (!C->mayHaveSideEffects()) {
598 C->eraseFromParent();
599 C = nullptr;
600 }
601 } else {
602 InsertNewValueIntoMap(ValueMap, Inst, C);
603 }
604 if (C) {
605 // Otherwise, stick the new instruction into the new block!
606 C->setName(Inst->getName());
607
608 if (auto *II = dyn_cast<AssumeInst>(C))
610 // MemorySSA cares whether the cloned instruction was inserted or not, and
611 // not whether it can be remapped to a simplified value.
612 if (MSSAU)
613 InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
614 }
615 }
616
617 if (!NoAliasDeclInstructions.empty()) {
618 // There are noalias scope declarations:
619 // (general):
620 // Original: OrigPre { OrigHeader NewHeader ... Latch }
621 // after: (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
622 //
623 // with D: llvm.experimental.noalias.scope.decl,
624 // U: !noalias or !alias.scope depending on D
625 // ... { D U1 U2 } can transform into:
626 // (0) : ... { D U1 U2 } // no relevant rotation for this part
627 // (1) : ... D' { U1 U2 D } // D is part of OrigHeader
628 // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
629 //
630 // We now want to transform:
631 // (1) -> : ... D' { D U1 U2 D'' }
632 // (2) -> : ... D' U1' { D U2 D'' U1'' }
633 // D: original llvm.experimental.noalias.scope.decl
634 // D', U1': duplicate with replaced scopes
635 // D'', U1'': different duplicate with replaced scopes
636 // This ensures a safe fallback to 'may_alias' introduced by the rotate,
637 // as U1'' and U1' scopes will not be compatible wrt to the local restrict
638
639 // Clone the llvm.experimental.noalias.decl again for the NewHeader.
640 BasicBlock::iterator NewHeaderInsertionPoint =
641 NewHeader->getFirstNonPHIIt();
642 for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
643 LLVM_DEBUG(dbgs() << " Cloning llvm.experimental.noalias.scope.decl:"
644 << *NAD << "\n");
645 Instruction *NewNAD = NAD->clone();
646 NewNAD->insertBefore(*NewHeader, NewHeaderInsertionPoint);
647 }
648
649 // Scopes must now be duplicated, once for OrigHeader and once for
650 // OrigPreHeader'.
651 {
652 auto &Context = NewHeader->getContext();
653
654 SmallVector<MDNode *, 8> NoAliasDeclScopes;
655 for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
656 NoAliasDeclScopes.push_back(NAD->getScopeList());
657
658 LLVM_DEBUG(dbgs() << " Updating OrigHeader scopes\n");
659 cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
660 "h.rot");
661 LLVM_DEBUG(OrigHeader->dump());
662
663 // Keep the compile time impact low by only adapting the inserted block
664 // of instructions in the OrigPreHeader. This might result in slightly
665 // more aliasing between these instructions and those that were already
666 // present, but it will be much faster when the original PreHeader is
667 // large.
668 LLVM_DEBUG(dbgs() << " Updating part of OrigPreheader scopes\n");
669 auto *FirstDecl =
670 cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
671 auto *LastInst = &OrigPreheader->back();
672 cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
673 Context, "pre.rot");
674 LLVM_DEBUG(OrigPreheader->dump());
675
676 LLVM_DEBUG(dbgs() << " Updated NewHeader:\n");
677 LLVM_DEBUG(NewHeader->dump());
678 }
679 }
680
681 // Along with all the other instructions, we just cloned OrigHeader's
682 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
683 // successors by duplicating their incoming values for OrigHeader.
684 for (BasicBlock *SuccBB : successors(OrigHeader))
685 for (BasicBlock::iterator BI = SuccBB->begin();
686 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
687 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
688
689 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
690 // OrigPreHeader's old terminator (the original branch into the loop), and
691 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
692 LoopEntryBranch->eraseFromParent();
693 OrigPreheader->flushTerminatorDbgRecords();
694
695 // Update MemorySSA before the rewrite call below changes the 1:1
696 // instruction:cloned_instruction_or_value mapping.
697 if (MSSAU) {
698 InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
699 MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
700 ValueMapMSSA);
701 }
702
703 SmallVector<PHINode *, 2> InsertedPHIs;
704 // If there were any uses of instructions in the duplicated block outside the
705 // loop, update them, inserting PHI nodes as required
706 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
707 &InsertedPHIs);
708
709 // Attach debug records to the new phis if that phi uses a value that
710 // previously had debug metadata attached. This keeps the debug info
711 // up-to-date in the loop body.
712 if (!InsertedPHIs.empty())
713 insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
714
715 // NewHeader is now the header of the loop.
716 L->moveToHeader(NewHeader);
717 assert(L->getHeader() == NewHeader && "Latch block is our new header");
718
719 // Inform DT about changes to the CFG.
720 if (DT) {
721 // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
722 // the DT about the removed edge to the OrigHeader (that got removed).
724 {DominatorTree::Insert, OrigPreheader, Exit},
725 {DominatorTree::Insert, OrigPreheader, NewHeader},
726 {DominatorTree::Delete, OrigPreheader, OrigHeader}};
727
728 if (MSSAU) {
729 MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
730 if (VerifyMemorySSA)
731 MSSAU->getMemorySSA()->verifyMemorySSA();
732 } else {
733 DT->applyUpdates(Updates);
734 }
735 }
736
737 // At this point, we've finished our major CFG changes. As part of cloning
738 // the loop into the preheader we've simplified instructions and the
739 // duplicated conditional branch may now be branching on a constant. If it is
740 // branching on a constant and if that constant means that we enter the loop,
741 // then we fold away the cond branch to an uncond branch. This simplifies the
742 // loop in cases important for nested loops, and it also means we don't have
743 // to split as many edges.
744 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
745 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
746 const Value *Cond = PHBI->getCondition();
747 const bool HasConditionalPreHeader =
749 PHBI->getSuccessor(cast<ConstantInt>(Cond)->isZero()) != NewHeader;
750
751 updateBranchWeights(*PHBI, *BI, HasConditionalPreHeader, BISuccsSwapped);
752
753 if (HasConditionalPreHeader) {
754 // The conditional branch can't be folded, handle the general case.
755 // Split edges as necessary to preserve LoopSimplify form.
756
757 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
758 // thus is not a preheader anymore.
759 // Split the edge to form a real preheader.
761 OrigPreheader, NewHeader,
762 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
763 NewPH->setName(NewHeader->getName() + ".lr.ph");
764
765 // Preserve canonical loop form, which means that 'Exit' should have only
766 // one predecessor. Note that Exit could be an exit block for multiple
767 // nested loops, causing both of the edges to now be critical and need to
768 // be split.
770 bool SplitLatchEdge = false;
771 for (BasicBlock *ExitPred : ExitPreds) {
772 // We only need to split loop exit edges.
773 Loop *PredLoop = LI->getLoopFor(ExitPred);
774 if (!PredLoop || PredLoop->contains(Exit) ||
775 isa<IndirectBrInst>(ExitPred->getTerminator()))
776 continue;
777 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
778 BasicBlock *ExitSplit = SplitCriticalEdge(
779 ExitPred, Exit,
780 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
781 ExitSplit->moveBefore(Exit);
782 }
783 assert(SplitLatchEdge &&
784 "Despite splitting all preds, failed to split latch exit?");
785 (void)SplitLatchEdge;
786 } else {
787 // We can fold the conditional branch in the preheader, this makes things
788 // simpler. The first step is to remove the extra edge to the Exit block.
789 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
790 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI->getIterator());
791 NewBI->setDebugLoc(PHBI->getDebugLoc());
792 PHBI->eraseFromParent();
793
794 // With our CFG finalized, update DomTree if it is available.
795 if (DT)
796 DT->deleteEdge(OrigPreheader, Exit);
797
798 // Update MSSA too, if available.
799 if (MSSAU)
800 MSSAU->removeEdge(OrigPreheader, Exit);
801 }
802
803 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
804 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
805
806 if (MSSAU && VerifyMemorySSA)
807 MSSAU->getMemorySSA()->verifyMemorySSA();
808
809 // Now that the CFG and DomTree are in a consistent state again, try to merge
810 // the OrigHeader block into OrigLatch. This will succeed if they are
811 // connected by an unconditional branch. This is just a cleanup so the
812 // emitted code isn't too gross in this common case.
813 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
814 BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
815 bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
816 if (DidMerge)
818
819 if (MSSAU && VerifyMemorySSA)
820 MSSAU->getMemorySSA()->verifyMemorySSA();
821
822 LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
823
824 return true;
825}
826
827/// Determine whether the instructions in this range may be safely and cheaply
828/// speculated. This is not an important enough situation to develop complex
829/// heuristics. We handle a single arithmetic instruction along with any type
830/// conversions.
832 BasicBlock::iterator End, Loop *L) {
833 bool seenIncrement = false;
834 bool MultiExitLoop = false;
835
836 if (!L->getExitingBlock())
837 MultiExitLoop = true;
838
839 for (BasicBlock::iterator I = Begin; I != End; ++I) {
840
842 return false;
843
844 switch (I->getOpcode()) {
845 default:
846 return false;
847 case Instruction::GetElementPtr:
848 // GEPs are cheap if all indices are constant.
849 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
850 return false;
851 // fall-thru to increment case
852 [[fallthrough]];
853 case Instruction::Add:
854 case Instruction::Sub:
855 case Instruction::And:
856 case Instruction::Or:
857 case Instruction::Xor:
858 case Instruction::Shl:
859 case Instruction::LShr:
860 case Instruction::AShr: {
861 Value *IVOpnd =
862 !isa<Constant>(I->getOperand(0))
863 ? I->getOperand(0)
864 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
865 if (!IVOpnd)
866 return false;
867
868 // If increment operand is used outside of the loop, this speculation
869 // could cause extra live range interference.
870 if (MultiExitLoop) {
871 for (User *UseI : IVOpnd->users()) {
872 auto *UserInst = cast<Instruction>(UseI);
873 if (!L->contains(UserInst))
874 return false;
875 }
876 }
877
878 if (seenIncrement)
879 return false;
880 seenIncrement = true;
881 break;
882 }
883 case Instruction::Trunc:
884 case Instruction::ZExt:
885 case Instruction::SExt:
886 // ignore type conversions
887 break;
888 }
889 }
890 return true;
891}
892
893/// Fold the loop tail into the loop exit by speculating the loop tail
894/// instructions. Typically, this is a single post-increment. In the case of a
895/// simple 2-block loop, hoisting the increment can be much better than
896/// duplicating the entire loop header. In the case of loops with early exits,
897/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
898/// canonical form so downstream passes can handle it.
899///
900/// I don't believe this invalidates SCEV.
901bool LoopRotate::simplifyLoopLatch(Loop *L) {
902 BasicBlock *Latch = L->getLoopLatch();
903 if (!Latch || Latch->hasAddressTaken())
904 return false;
905
906 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
907 if (!Jmp || !Jmp->isUnconditional())
908 return false;
909
910 BasicBlock *LastExit = Latch->getSinglePredecessor();
911 if (!LastExit || !L->isLoopExiting(LastExit))
912 return false;
913
914 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
915 if (!BI)
916 return false;
917
918 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
919 return false;
920
921 LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
922 << LastExit->getName() << "\n");
923
924 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
925 MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
926 /*PredecessorWithTwoSuccessors=*/true);
927
928 if (SE) {
929 // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
931 }
932
933 if (MSSAU && VerifyMemorySSA)
934 MSSAU->getMemorySSA()->verifyMemorySSA();
935
936 return true;
937}
938
939/// Rotate \c L, and return true if any modification was made.
940bool LoopRotate::processLoop(Loop *L) {
941 // Save the loop metadata.
942 MDNode *LoopMD = L->getLoopID();
943
944 bool SimplifiedLatch = false;
945
946 // Simplify the loop latch before attempting to rotate the header
947 // upward. Rotation may not be needed if the loop tail can be folded into the
948 // loop exit.
949 if (!RotationOnly)
950 SimplifiedLatch = simplifyLoopLatch(L);
951
952 bool MadeChange = rotateLoop(L, SimplifiedLatch);
953 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
954 "Loop latch should be exiting after loop-rotate.");
955
956 // Restore the loop metadata.
957 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
958 if ((MadeChange || SimplifiedLatch) && LoopMD)
959 L->setLoopID(LoopMD);
960
961 return MadeChange || SimplifiedLatch;
962}
963
964
965/// The utility to convert a loop into a loop with bottom test.
969 const SimplifyQuery &SQ, bool RotationOnly = true,
970 unsigned Threshold = unsigned(-1),
971 bool IsUtilMode = true, bool PrepareForLTO) {
972 LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
973 IsUtilMode, PrepareForLTO);
974 return LR.processLoop(L);
975}
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")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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:539
static constexpr uint32_t ZeroTripCountWeights[]
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 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 Check Debug Module
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
const Instruction & back() const
Definition BasicBlock.h:484
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.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
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.
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
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
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....
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.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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.
bool isTerminator() const
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.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition LoopInfo.h:441
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1078
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
LLVM_ABI void updateForClonedBlockIntoPred(BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM)
LLVM_ABI void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT, bool UpdateDTFirst=false)
Apply CFG updates, analogous with the DT edge updates.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
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.
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 forgetTopmostLoop(const Loop *L)
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...
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
See the file comment.
Definition ValueMap.h:84
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:167
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition ValueMap.h:175
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()
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
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:180
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT begin() const
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.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.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:644
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:632
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.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
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:1732
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.
@ 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
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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:548
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
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...
TargetTransformInfo TTI
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.
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.
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:560
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:466
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:869
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).